Sherlock and the Valid String – HackerRank Solution

In this post, we will solve Sherlock and the Valid String HackerRank Solution. This problem (Sherlock and the Valid String) is a part of HackerRank Problem Solving series.

Solution – Sherlock and the Valid String – HackerRank Solution

C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<cstring>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int nl,l,i;
    int count=0;
    int arr[26]={0};
    char str[100000];
    cin>>str;
    l=strlen(str);
    for(i=0;i<l;i++)
        {
       int x=str[i]-97;
        arr[x]++;  
    }
    l=0;
    sort(arr,arr+26);
   /* for(i=0;i<26;i++)
        {
        cout<<arr[i]<<" ";
    }*/
  
    for(i=0;i<26;i++)
        {
        if(arr[i]==0)
            l++;
    }
    if(arr[l]==1)
       {
        l++;
        count++;
    }
        
    for(i=l+1;i<26;i++)
        {
        if(arr[i]!=arr[l])
            {
            count++;
        }
    }
    if(count>1)
        cout<<"NO"<<endl;
    else
        cout<<"YES"<<endl;
    return 0;
}

Python

import math
import os
import random
import re
import sys

# Complete the isValid function below.
def isValid(s):
    # Go over string and count how many times string occured
    char_dict = {}
    for char in s:
        if char in char_dict:
            char_dict[char] += 1
        else:
            char_dict[char] = 1
    #initiate largest and smallest count with last char
    min_count = char_dict[char]
    max_count = char_dict[char]
    # count how many times a count occured
    count_dict = {}
    for char, value in char_dict.items():
        if value in count_dict:
            count_dict[value] += 1
        else:
            count_dict[value] = 1
        #also update max and min count
        if value < min_count:
            min_count = value
        if value > max_count:
            max_count = value
    # final test:
    if len(count_dict) == 1:
        return 'YES'
    elif len(count_dict) == 2:
        if count_dict[max_count] == 1 and max_count - min_count == 1:
            return 'YES'
        elif count_dict[min_count] == 1 and min_count == 1:
            return 'YES'
    return 'NO'

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

    s = input()

    result = isValid(s)

    fptr.write(result + '\n')

    fptr.close()

Java

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        
        Map<Character, Integer> frequencies = new HashMap<>();
        
        for(char letter : s.toCharArray())
        {
            if(frequencies.containsKey(letter))
                frequencies.put(letter, frequencies.get(letter) + 1);
            else
                frequencies.put(letter, 1);
        }
        
        
        
        Set<Integer> st = new HashSet<>();
        for(int freq : frequencies.values())
        {
            st.add(freq);
        }
        
        if(st.size() > 2)//More than 2 frequencies
            System.out.println("NO");
        else if(st.size() == 1)
            System.out.println("YES");
        else//2 different frequencies
        {
            int f1 = 0;
            int f2 = 0;
            int f1Count = 0;
            int f2Count = 0;
            int i = 0;
            for(int n : st)
            {
                if(i == 0) f1 = n;
                else f2 = n;
                i++;
            }
            
            for(int freq : frequencies.values())
            {
                if(freq == f1) f1Count++;
                if(freq == f2) f2Count++;
            }
            
            
            
            if((f1 == 1 && f1Count == 1 ) || (f2 == 1 && f2Count == 1 ))
                System.out.println("YES");
            else if ((Math.abs(f1 - f2)  == 1) && (f1Count == 1 || f2Count == 1))
                System.out.println("YES");
            else
                System.out.println("NO");
        }
    }
}

Note: This problem (Sherlock and the Valid String) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *