Sherlock and the Valid String : Looking for “Sherlock and the Valid String” solution for Hackerrank problem? Get solution with source code and detailed explainer video.

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 1 character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES, otherwise return NO.
Go to problem statement

Explanation Video:


Youtube Channel partner: CodingCart
Mentor: Satyendra Jaiswal
Langauge: Python

Source Code:  for isValid function


# Complete the isValid function below.
def isValid(s):
    a=Counter(s)
    val=list(a.values())
    res=Counter(val)
    v=list(res.keys())
    if len(s)==1 or (max(v)-min(v))==0:
        return'YES'
    elif len(v)<3 and ((max(v)-min(v)==1 and res.get(max(v))==1) or (min(v)==1 and res.get(min(v))==1)):
        return 'YES'
    else:
        return'NO'       
coming soon…
coming soon…

Full Source Code: Sherlock and the Valid String


#!/bin/python3

import math
import os
import random
import re
import sys
from collections import Counter
# Complete the isValid function below.
def isValid(s):
    a=Counter(s)
    val=list(a.values())
    res=Counter(val)
    v=list(res.keys())
    if len(s)==1 or (max(v)-min(v))==0:
        return'YES'
    elif len(v)<3 and ((max(v)-min(v)==1 and res.get(max(v))==1) or (min(v)==1 and res.get(min(v))==1)):
        return 'YES'
    else:
        return'NO'

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = isValid(s)

    fptr.write(result + '\n')

    fptr.close()



coming soon…
coming soon…

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our Youtube Channel.

This post is in partner with CodingCart.