Sherlock and the Valid String in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank, Algorithm Solutions of Problem Solving Section in Java. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Sherlock and the Valid String in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Introduction To Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results. 

Advantages of Algorithms:

  • It is easy to understand.
  • Algorithm is a step-wise representation of a solution to a given problem.
  • In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Link for the ProblemSherlock and the Valid String – Hacker Rank Solution

Sherlock and the Valid String – Hacker Rank Solution

Problem:

Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just  character at  index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.

Example

This is a valid string because frequencies are .

This is a valid string because we can remove one  and have  of each character in the remaining string.

This string is not valid as we can only remove  occurrence of . That leaves character frequencies of .

Function Description

Complete the isValid function in the editor below.

isValid has the following parameter(s):

  • string s: a string

Returns

  • string: either YES or NO

Input Format

A single string .

Constraints

  • Each character 

Sample Input 0

aabbcd

Sample Output 0

NO

Explanation 0

Given , we would need to remove two characters, both c and d  aabb or a and b  abcd, to make it valid. We are limited to removing only one character, so  is invalid.

Sample Input 1

aabbccddeefghi

Sample Output 1

NO

Explanation 1

Frequency counts for the letters are as follows:

{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2, 'f': 1, 'g': 1, 'h': 1, 'i': 1}

There are two ways to make the valid string:

  • Remove  characters with a frequency of : .
  • Remove  characters of frequency : .

Neither of these is an option.

Sample Input 2

abcdefghhgfedecba

Sample Output 2

YES

Explanation 2

All characters occur twice except for  which occurs  times. We can delete one instance of  to have a valid string.

Sherlock and the Valid String – Hacker Rank Solution
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Kanahaiya Gupta
 *
 */
public class SherlockAndTheValidString {
	static String isValid(String s) {
		int a[] = new int[26];
		for (int i = 0; i < s.length(); i++) {
			int index = s.charAt(i) - 'a';
			a[index]++;
		}
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < 26; i++) {
			if (a[i] != 0) {
				if (map.containsKey(a[i])) {
					map.put(a[i], map.get(a[i]) + 1);
				} else {
					map.put(a[i], 1);
				}
			}
		}
		if (map.size() == 1)
			return "YES";
		if (map.size() == 2) {
			Set<Entry<Integer, Integer>> entrySet = map.entrySet();
			Iterator it = entrySet.iterator();
			Entry<Integer, Integer> e1 = (Entry<Integer, Integer>) it.next();
			int key1 = e1.getKey();
			int value1 = e1.getValue();
			Entry<Integer, Integer> e2 = (Entry<Integer, Integer>) it.next();
			int key2 = e2.getKey();
			int value2 = e2.getValue();
			if (value1 == 1 || value2 == 1 && Math.abs(key1 - key2) == 1)
				return "YES";
		}
		return "NO";
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.next();
		String result = isValid(s);
		System.out.println(result);
	}
}

34 thoughts on “Sherlock and the Valid String in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]”

  1. This design is wicked! You obviously know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well,
    almost…HaHa!) Excellent job. I really loved what you had to say, and more than that, how you presented it.

    Too cool!

    Reply
  2. Very nice post. I just stumbled upon your blog and wished to say that I have truly loved surfing around your blog posts.
    In any case I will be subscribing to your feed and I am hoping you write
    once more soon!

    Reply
  3. Thanks for the marvelous posting! I really enjoyed reading it, you are a great author.I will ensure that I bookmark
    your blog and will often come back from now on. I want to encourage you to definitely continue your great job, have a nice evening!

    Reply
  4. Hello There. I found your blog using msn. This is an extremely well
    written article. I will make sure to bookmark it and come
    back to read more of your useful information. Thanks for the post.
    I’ll definitely comeback.

    Reply
  5. Greetings! This is my first comment here so I just wanted to give a quick shout out and
    say I truly enjoy reading your articles. Can you recommend any other blogs/websites/forums that deal with the same topics?

    Thanks for your time!

    Reply
  6. Greetings, I do think your web site could possibly be having
    web browser compatibility problems. Whenever I take a look at your site in Safari, it looks fine however, if opening in IE,
    it has some overlapping issues. I merely wanted to provide you with a quick heads up!
    Besides that, great website!

    Reply
  7. What you wrote made a lot of sense. But, what about this?
    what if you were to create a awesome title? I ain’t saying your information isn’t solid,
    however what if you added a post title that makes people desire more?

    I mean Sherlock and the Valid String in Algorithm | HackerRank Programming Solutions |
    HackerRank Problem Solving Solutions in Java [💯Correct] – Techno-RJ is a
    little plain. You should peek at Yahoo’s front page and see how they write
    article headlines to grab viewers interested. You might add a related video or
    a pic or two to grab readers excited about everything’ve written. In my opinion, it would
    bring your website a little bit more interesting.

    Reply
  8. I do trust all the ideas you’ve presented to your post.
    They are really convincing and will definitely work. Nonetheless, the posts are very brief for newbies.
    May you please lengthen them a bit from subsequent time?

    Thank you for the post.

    Reply
  9. I blog frequently and I really thank you for your content. The article has really peaked my interest. I will bookmark your website and keep checking for new information about once a week. I opted in for your RSS feed too.

    Reply
  10. Does your site have a contact page? I’m having trouble locating it but, I’d like to
    shoot you an e-mail. I’ve got some ideas for your blog you
    might be interested in hearing. Either way, great website and I look forward to seeing it improve over time.

    Reply
  11. Having read this I thought it was extremely enlightening.

    I appreciate you spending some time and effort to put this information together.
    I once again find myself personally spending a lot of time both reading and commenting.
    But so what, it was still worthwhile!

    Reply
  12. Excellent blog here! Also your web site loads up very fast!
    What host are you using? Can I get your affiliate link on your host?
    I want my web site loaded up as fast as yours lol

    Reply
  13. Hi there! This post could not be written much better! Looking through this post reminds
    me of my previous roommate! He constantly kept talking about this.
    I will forward this post to him. Fairly certain he’ll have a great read.
    Many thanks for sharing!

    Reply
  14. Greetings, There’s no doubt that your site could be having web browser compatibility problems.
    Whenever I take a look at your site in Safari, it
    looks fine however, if opening in Internet Explorer, it’s got some overlapping issues.
    I just wanted to provide you with a quick heads up! Apart from that,
    great website!

    Reply
  15. wonderful put up, very informative. I’m wondering why the opposite experts of
    this sector do not notice this. You should proceed your writing.
    I am sure, you have a great readers’ base already!

    Reply
  16. That is really interesting, You are an excessively professional blogger.

    I’ve joined your rss feed and stay up for seeking more of your fantastic post.
    Additionally, I’ve shared your website in my social networks

    Reply
  17. Thank you a bunch for sharing this with all people you really understand what you are speaking about!
    Bookmarked. Please also discuss with my website =).
    We will have a hyperlink trade contract between us

    Reply

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock