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);
	}
}

499 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
  18. Aw, this was an extremely nice post. Taking the time and actual effort to create a superb article…
    but what can I say… I put things off a lot and don’t manage to get anything done.

    Reply
  19. Hello, I think your website could possibly be having web browser
    compatibility issues. When I look at your site in Safari, it looks fine but when opening in Internet Explorer, it’s got some
    overlapping issues. I simply wanted to give you a quick heads up!
    Aside from that, excellent blog!

    Reply
  20. of course like your web site but you need to take a look at the spelling on quite a few of your posts.
    Several of them are rife with spelling issues and I to find it very bothersome to tell the reality however I’ll definitely come again again.

    Reply
  21. I was curious if you ever considered changing
    the layout of your blog? Its very well written;
    I love what youve got to say. But maybe you could a little more in the way of content so people could connect
    with it better. Youve got an awful lot of text for only having
    one or 2 pictures. Maybe you could space it out better?

    Reply
  22. Undeniably believe that which you stated. Your favorite justification seemed to be on the internet the simplest thing to
    be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don’t
    know about. You managed to hit the nail upon the top and also defined out the whole
    thing without having side-effects , people could take a signal.
    Will likely be back to get more. Thanks

    Reply
  23. Whats up are using WordPress for your site platform?
    I’m new to the blog world but I’m trying to get started and
    create my own. Do you need any html coding knowledge to make your own blog?
    Any help would be greatly appreciated!

    Reply
  24. Just wish to say your article is as astonishing.

    The clarity for your put up is just great and i could assume you’re knowledgeable in this subject.

    Fine along with your permission let me to clutch your RSS feed to keep up to date with impending post.
    Thank you 1,000,000 and please keep up the enjoyable work.

    Reply
  25. Hello there! I could have sworn I’ve been to this website before but
    after reading through some of the post I realized it’s new
    to me. Anyways, I’m definitely delighted I found it and I’ll be book-marking and checking back frequently!

    Reply
  26. Hello! I could have sworn I’ve visited this web site before
    but after browsing through a few of the articles I realized it’s new to me.
    Anyhow, I’m definitely happy I came across it and I’ll be book-marking it and checking back often!

    Reply
  27. I have been surfing online greater than 3 hours as of late, yet I
    never discovered any fascinating article like yours.
    It’s lovely value enough for me. In my opinion, if all site owners
    and bloggers made excellent content material as you probably
    did, the internet shall be much more helpful than ever before.

    Reply
  28. Wow, incredible blog layoᥙt! How long have you beеn blogging for?
    you maԀe blogging look easy. The overall loоk of yor website
    is excellent, as well as thee content!

    Reply
  29. I have learn some excellent stuff here. Defіnitely value bookmarking foг revisiting.
    I ԝonder how much effort you place to create any ѕuch great informatige site.

    Reply
  30. Fantaѕtic website. A lott of useful infο һere.
    I am sending it to some friesnds ans additionally sharing in deliciouѕ.
    Andd naturalⅼy, thank you to your effort!

    Reply
  31. Awesomе website you have here bսtt I was curious if you kneԝ of any forums that cover the same toppics talkeɗ
    aboսt here? I’d realⅼy lⲟve to be a ⲣart of onljne
    comunity where I can get feedbаckk fгom other experienced individuals that share the samme interest.
    If yoou have any suggestions, please let me know.
    Appreciate it!

    Reply
  32. Just ԝant tto say your article is as ɑstounding. The clarity on yߋur рuut up іs ѕimplyy nice and i could suppose you’re an expert on this subject.

    Fine along witһ youjr permіssion let me to gгab yiur RSS feed to stay updated with impending post.
    Тhnks a million and pⅼease continue the
    гewardіng work.

    Reply
  33. I’vе been exploring for a little Ƅitt for any high-quality articles or blog posts on this sort
    of house . Exploring in Yaһhoo I at last stumbled upon this web site.

    Studying this information So i’m happy to exprrss that I have an incredibly juzt
    right uncanny feeling I came upon exaactly wһat I needed.

    I most certainly wiⅼl make certain to ddo not put out of your miund thіs website and givbe it a glance on a constant basis.

    Reply
  34. After looking іnto a number of the aгtіcles on your ᴡebsite, I truʏ apⲣrecіate your way of blogging.
    I bookmarkjed it too my boⲟkmardk site list and will be checking back soon. Please visit mmy ᴡeeb ѕite
    as well and tell me how you feel.

    Reply
  35. I’ve been explorinng for a bit for any high-quality articles or weblog posts
    in this sort off area . Exploring in Yahoo I finally stumbled upon this web
    site. Studying tthis info So i amm satisfied to convey
    that I’ve a very excellent ncanny feeling I found out just what I needed.
    I so much indisputably ill make sure to do not overlook this weeb site and give it a glance regularly.

    My web page 카지노사이트

    Reply
  36. Pretty section of content. I just stumbled
    upon your site and in accession capital to assert that I get actually enjoyed account your
    blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.

    Reply
  37. Among the vital advantages of health nutrition as well as supplements is their ability to strengthen immune feature. Specific nutrients, such as vitamin C, vitamin D, as well as zinc, participate in important roles in sustaining the invulnerable system. By integrating these nutrients into one’s diet or even supplement regimen, individuals can easily assist strengthen their body’s natural defenses as well as lessen the threat of illness, https://www.tracksandfields.com/profile/view/amarafdunlap.

    Reply
  38. Excellent site you have got here.. It’s difficult to find good quality writing like yours
    nowadays. I really appreciate individuals
    like you! Take care!!

    Reply
  39. I am no longer certain where you are getting your information, however good topic.
    I must spend some time finding out much more or understanding more.
    Thanks for excellent information I was on the lookout for this info for my mission.

    Reply
  40. Pretty portion of content. I simply stumbled upon your site and in accession capital to claim that I get in fact enjoyed account your
    weblog posts. Anyway I will be subscribing in your augment and even I success you get
    entry to persistently quickly.

    Reply
  41. First of all I want to say great blog! I had a quick question which I’d like to ask if you do not mind.
    I was interested to know how you center yourself and clear your head prior to writing.
    I’ve had a tough time clearing my thoughts in getting
    my ideas out there. I do enjoy writing however it just seems like the first 10 to 15 minutes are generally wasted simply just trying to figure out how to begin.
    Any ideas or hints? Appreciate it!

    Reply
  42. mexico pharmacies prescription drugs [url=https://mexicopharmacy.cheap/#]mexico pharmacies prescription drugs[/url] reputable mexican pharmacies online

    Reply
  43. Excellent post! Your insights on this topic are very valuable and have given me a new perspective. I appreciate the detailed information and thoughtful analysis you provided. Thank you for sharing your knowledge and expertise with us. Looking forward to more of your posts!

    Reply
  44. Hi! Someone in my Facebook group shared this
    website with us so I came to give it a look.
    I’m definitely loving the information. I’m
    book-marking and will be tweeting this to my followers! Exceptional blog and excellent design and style.

    Reply
  45. Hi there just wanted to give you a quick heads up. The words
    in your content seem to be running off the screen in Firefox.

    I’m not sure if this is a formatting issue or something to do with web browser compatibility
    but I figured I’d post to let you know. The design look great though!
    Hope you get the problem resolved soon. Many thanks

    Reply