Sherlock and the Valid String — HackerRank Medium

iAwale
2 min readMar 16, 2020

Link to problem

Link to solution

Before we get on to solving the problem, let us understand it. The problem

  • gives us a string build up of characters a-z
  • wants us to count the occurrence of each character
  • wants us to check if we can reduce 1 from any character’s count and make all of them equal

To do this, first we create an array of size 26 and store the count of each character in the index according to its ASCII value-97 to start ‘a’ from 0;

Then we check if there is a difference of more than 1 between the first two elements which would immediately make the string invalid. Otherwise, we check for elements that are unequal to both of them, meaning we increase the count of changes required (isValidCount).

Thus if this count goes up by more than one, we return “NO” as the string is invalid.

We could also add the specific difference between the two elements to isValidCount as well.

Test cases :

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response