# 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.

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

### 250 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!

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!

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!

4. I am actually grateful to the owner of this
site who has shared this fantastic paragraph at here.

5. Because the admin of this web site is working, no question very rapidly it will be famous, due to its feature
contents.

6. 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.

7. 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?

8. 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!

9. If some one wants expert view regarding running a blog after that i recommend
him/her to pay a quick visit this blog, Keep up the fastidious job.

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.

11. 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.

12. French Roulette is fairly a lot the same as European, featuring the exact table set
up with a single zero.

13. I go to see daily some web pages and websites to read
articles, however this webpage provides quality based posts.

14. 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.

15. Way cool! Some very valid points! I appreciate you penning
this post plus the rest of the website is really good.

16. 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.

17. 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!

18. Excellent blog here! Also your web site loads up very fast!
I want my web site loaded up as fast as yours lol

19. My relatives all the time say that I am killing my
time here at net, except I know I am getting experience daily by reading thes fastidious posts.

20. Hi there! This post could not be written much better! Looking through this post reminds
I will forward this post to him. Fairly certain he’ll have a great read.
Many thanks for sharing!

21. 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!

22. wonderful put up, very informative. I’m wondering why the opposite experts of
this sector do not notice this. You should proceed your writing.

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

24. 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 =).

25. The latter contains deposit reloads and rakeback foor
existing players.

Herre is my blog; website

26. Wow, incredible blog layout! How long have you been blogging
for? you make blogging look easy. The overall look of your website is fantastic,
let alone the content!

27. Very nice article. I definitely love this website.
Keep writing!

28. The house edge is 1.35% for even cash bets and 2.7% for all other people.

29. These contain sports betting, horse racing, motorsports, and
casino gaming.

30. In addition to the games, you’ll get many bonuses throughout the day.

31. I get my photos via, Styled Stock Society and IvoryMix.

32. So, when you pick from our list, you ccan usually count on reputable and
transparent final results.

Also visit my homepage; Casino Play Online

33. Wow, marvelous blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your site is excellent, let alone the content!

34. indian-bhabhi-fuck-with-young-and-taste-cum
saliba

35. We’re delighted to work with borrowers who have bbad credit or minimal credit.

36. As a outcome, 1 can expect up to 35.99% APRs with replayment erms of upp to 60
months, thouyh some exclusions apply.

Here is my blog: online loans no credit check

37. 30% is primarily based on the total quantity of outstanding debt 15%
is based on thee length of your credit history
and 10% based on new desbt or newly opened lines of credit.

Feel free to visit my blog post online loans no credit check

38. SBA partners with lenders to support boost tiny company

Takee a look at my homepage :: online loans same day

39. Loan category, maximum loan amount, loan tenure
and rate of interest may perhaps differ on Freecharge.

Alsoo visit my web-site – loan places near me

40. 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.

41. Really no matter if someone doesn’t understand
then its up to other users that they will assist, so here it occurs.

42. Hi, just wanted to mention, I liked this post.
It was inspiring. Keep on posting!

43. 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!

44. Amazing issues here. I am very happy to peer your article.
Thank you so much and I am having a look ahead to touch
you. Will you kindly drop me a mail?

45. 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.

46. Nice post. I learn something new and challenging on sites
I stumbleupon everyday. It will always be exciting to read articles from other writers and practice a little something from other web sites.

47. 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?

48. Denizli’de kanal açma servisleri, tesisat problemlerine hızlı ve etkili çözümler sunar.

Do you have any? Please let me realize in order that I could subscribe.
Thanks.

50. After checking out a few of the blog posts on your web page, I seriously appreciate your technique of blogging.
I saved it to my bookmark webpage list and will be checking back
soon. Take a look at my website as well and let me
know how you feel.

51. 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

52. 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!

53. 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.

54. This is a great tip particularly to those new to the blogosphere.
Brief but very accurate information… Many thanks for sharing this one.

55. Hi! I simply want to offer you a big thumbs up for your great information you have right here on this post.
I’ll be returning to your website for more
soon.

56. 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!

57. 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!

58. 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.

59. Wow, incｒedible 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 theｅ content!

60. It’s noߋt my first time to pay a quick visit this web page, i am browsing this web site dаilly
and take pleaѕant information from here everү dаy.

61. I have learn some excellent stuff herｅ. Defіnitely ｖalue bookmarking foг revisiting.
I ԝonder how much effort you place to create any ѕuch great informatige site.

62. 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!

63. Thаnkfulness to my father who informeⅾ me concerning this weblog, this website iis actually aweѕome.

64. Sollten Sie noch Fragen oder zusätzliche Wünsche haben, teilen Sie uns dies bitte auch mit dem
Anfrageformular mit.

65. Scrap metal brokering Aluminum recycling transport Aluminium recycling audit
Metal waste reclamation and reuse, Aluminum cable recycling machine, Scrap metal reclamation industry

66. Metal reclamation solutions Aluminium scrap baling Aluminium waste emissions
Metal scraps reclamation, Aluminum cable scrap recovery, Scrap metal brokering

67. Scrap metal reclaiming and reprocessing Aluminium recycling facility infrastructure Post-consumer aluminium recycling
Global metal commodity trade, Aluminum cable scrap environmental impact, Metal waste reprocessing facility

68. Metal recovery facility Scrap aluminium grading system Aluminium smelting
Metal export compliance, Recycling aluminum cables, Scrap metal recovery methodologies

69. Sustainable metal recovery practices Scrap aluminium reprocessing methods Aluminum recycling supply chain
Metal reclamation solutions, Aluminum cable stripping tools, Metal scrap logistics

70. This post provides clear idea designed for the new users of
blogging, that really how to do blogging and site-building.

71. 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 wheｒe 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!

72. 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.

73. 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.

74. Metal recovery plant Scrap metal recycling center Iron scrap reclamation operations

Ferrous material recycling compliance training, Iron scrap sorting, Metal recovery and reprocessing

75. 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.

76. Once the drywall and paint work is completed, we’ll then revisit

77. I love the tips on this site, they are always to the point and just the information I was looking for https://betinsite.com

78. The author’s sincere and heartfelt approach truly resonated with me. The depth of the content made me contemplate and gain new perspectives. | toptan giyim Küçükçekmece

found most people will go along with your views on this website.

80. If you woulԀ likе to increase үour knoԝledge juist
keep visitinng this site and be updated
with the newest information posted here.

81. Scrap metal reclamation and trading Ferrous waste remanufacturing Iron waste recovery plant

Ferrous material audits, Iron scrap utilization and recycling, Scrap metal grading

82. I must say, I thought this was a pretty interesting read when it comes to this topic. Liked the material. . . . . Also visit my 로우바둑이 website

and previous technologies, it’s amazіng article.

84. Devrek Toptan Kadın Giyim | RENE Toptan Tekstil ve Giyim Çözümleri’nde alışveriş yapmak her zaman keyifli bir deneyim. Ürünlerinin kalitesi ve hizmet anlayışları gerçekten takdire şayan.

85. Perspektif Türleri | Bu blog yazısını okumaktan ne kadar keyif aldığımı ifade etmek istedim. Harika bir şekilde hazırlandığınız belli.

86. Dordrecht | MAFA levert consequent eersteklas webdesign- en softwareontwikkelingsdiensten. Hun professionaliteit blijft me keer op keer verbazen.

87. Yalı Karotçu | Rüzgar Karot’un işlerini zamanında ve eksiksiz bir şekilde teslim etmesi gerçekten takdire şayan.

88. Fatih, Pendik Halı Yıkama | PENTA’nın yıkama çözümleriyle ilgili bu yazı, işletmemin temizlik ve hijyen konusundaki ihtiyaçlarını nasıl karşılayabileceğimi daha iyi anlamama yardımcı oldu. Harika bir kaynak!

89. Doğanyurt Toptan Kadın Giyim | Shopping at RENE Wholesale Textile and Clothing Solutions is always a pleasant experience. Their product quality and service are commendable.

90. Demirköy Jakuzi | Atlas Jakuzi’nin ürünleriyle evimde bir spa ortamı yaratmak mümkün. Gerçekten harika bir hizmet sunuyorlar!

91. Sineklik Fiyatları Şırnak | Thanks to Venster Systems’ pleated insect screens, we can enjoy our backyard without constant interruptions from bugs. Such a relief!

92. Venster Systems’ pleated insect screens have made our home a sanctuary free from pesky bugs. Thank you for this innovative solution! | Sineklik Fiyatları Karabük

93. Karapürçek / Sakarya | The breadth and depth of MAFA’s content in web design and development continually astound me. Thank you for being such a valuable resource.

94. 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 카지노사이트

I llike all of the poiints you have made.

Feel free to visit my blog … 카지노사이트

96. Wow that was odd. I just wrote an very long comment but after I clicked submit my comment didn’t appear.

Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say wonderful blog!

97. This design is wicked! You most certainly know how to keep a reader entertained.
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!

98. Hmm is anyone else experiencing problems with the images on this blog loading?
I’m trying to determine if its a peoblem on my end or if it’s the blog.
Any feed-back would be greatly appreciated.

Feel free to vjsit my web site: 카지노사이트

99. Good answer back in return of this query with real arguments and describing all regarding that.

100. It’s hard to come by knowledgeable people for this topic, but you seem like you know

101. fantastic issues altogether, you just won a emblem new reader.
What would you recommend in regards to your publish that you made some days in the past?
Any certain?

102. 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.

103. Hi there friends, how is the whole thing, and what you want to say regarding this piece of writing, in my
view its genuinely awesome in favor of me.

104. 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.

105. AGENCANTIK
AGENCANTIK says Thank you very much, all the information above is very good and interesting

106. Hello i am kavin, its my first time to commenting anyplace,
when i read this post i thought i could also create comment due to this sensible paragraph.

107. WOᎳ just what I was lookinhg for. Camee here by searching for swaρ
pdf

108. Excellent site you have got here.. It’s difficult to find good quality writing like yours
like you! Take care!!

109. 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.

where can i buy cipro online [url=http://ciprodelivery.pro/#]cipro for sale[/url] п»їcipro generic

111. mexican online pharmacies prescription drugs: mexican rx online – mexican pharmaceuticals online