Sherlock and the Valid String – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
1 Month Preparation Kit Solutions – HackerRank
C++ Sherlock and the Valid String HackerRank Solution
#include <bits/stdc++.h>
using namespace std;
char s[1234567];
int main() {
scanf("%s", s);
int n = strlen(s);
vector <int> cnt(26, 0);
for (int i = 0; i < n; i++) {
cnt[s[i] - 'a']++;
}
for (int i = 0; i <= 26; i++) {
if (cnt[i] == 0) {
continue;
}
if (i < 26) {
cnt[i]--;
}
vector <int> a = cnt;
sort(a.begin(), a.end());
int res = a[25];
bool ok = true;
for (int j = 0; j < 26; j++) {
if (a[j] != 0 && a[j] != res) {
ok = false;
break;
}
}
if (ok) {
puts("YES");
return 0;
}
if (i < 26) {
cnt[i]++;
}
}
puts("NO");
return 0;
}
Java Sherlock and the Valid String HackerRank Solution
import java.util.*;
import java.io.*;
public class June_2015_A {
static BufferedReader br;
static PrintWriter pr;
static StringTokenizer st;
public static void main (String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pr = new PrintWriter(new OutputStreamWriter(System.out));
//br = new BufferedReader(new FileReader("in.txt"));
//pr = new PrintWriter(new FileWriter("out.txt"));
char[] in = next().toCharArray();
int[] cnt = new int[26];
for (int i = 0; i < in.length; i++)
cnt[in[i] - 'a']++;
int res = 0;
HashMap<Integer, Integer> buckets = new HashMap<Integer, Integer>();
for (int i = 0; i < 26; i++)
if (cnt[i] > 0) {
if (!buckets.containsKey(cnt[i]))
buckets.put(cnt[i], 0);
buckets.put(cnt[i], buckets.get(cnt[i])+1);
}
int min = 1 << 30;
for (Map.Entry<Integer, Integer> e : buckets.entrySet()) {
min = Math.min(min, e.getValue());
}
if (buckets.size() == 1 || (buckets.size() == 2 && min <= 1))
System.out.println("YES");
else
System.out.println("NO");
pr.close();
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readCharacter () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return br.readLine().trim();
}
}
Python 3 Sherlock and the Valid String HackerRank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT PYTHON 2
s = str(raw_input())
d = {}
for c in s:
if c in d:
d[c]+=1
else:
d[c]=1
k = sorted(d.values())
if len(k) == 1:
print "YES"
elif k[0] == 1 and k[1] == k[-1]:
print "YES"
else:
print "YES" if k[-1]-k[0] <= 1 and (k[-1] != k[-2] or k[0] == k[-1]) else "NO"
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the isValid function below.
def isValid(s):
d = Counter(s)
counts = Counter(d.values())
if len(counts) == 1:
return "YES"
elif len(counts) > 2:
return "NO"
else:
max_v = max(counts.values())
k1, k2 = counts.keys()
if (max_v == len(d) - 1):
if (abs(k1 - k2) == 1):
return "YES"
elif (min(k1, k2) == 1):
if counts[1] == 1:
return "YES"
else:
return "NO"
else:
return "NO"
else:
return "NO"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
JavaScript Sherlock and the Valid String HackerRank Solution
function countHighest(high, array){
var i = 0,
counter = 0;
for (i = 0; i < array.length; i++){
if (array[i] === high){
counter++;
}
}
return counter;
}
function countLowest(low, array){
var i = 0,
counter = 0;
for (i = 0; i < array.length; i++){
if (array[i] === low){
counter++;
}
}
return counter;
}
function getLowestValue(alphaArr){
var i = 0,
low = -1;
for (i = 0; i < alphaArr.length; i++){
if (alphaArr[i] !== 0) {
if (low === -1){
low = alphaArr[i];
} else if (low > alphaArr[i] ){
low = alphaArr[i];
}
}
}
return low;
}
function getHighestValue(alphaArr){
var i = 0,
high = 0;
for (i = 0; i < alphaArr.length; i++){
if (high < alphaArr[i]){
high = alphaArr[i];
}
}
return high;
}
function createAlphaArray(string){
var i = 0,
alphaArr = [];
for (i = 0; i < 26; i++){
alphaArr.push(0);
}
for (i = 0; i < string.length; i++){
alphaArr[string.charCodeAt(i) - 97]++;
}
return alphaArr;
}
function processData(input) {
var string = '',
alpha = [],
high = 0, low = 0,
numberOfHighs = 0, numberOfLows = 0;
string = input.split('\n')[0];
alpha = createAlphaArray(string);
high = getHighestValue(alpha);
low = getLowestValue(alpha);
// console.log(alpha);
// if the difference of high and low is greater than or equal to 2,
// string immediately fails
if (high - low >= 2){
if (low === 1 && countLowest(low, alpha) === 1){
console.log('YES');
} else {
console.log('NO');
}
} else if (high === low){
console.log('YES');
} else {
numberOfHighs = countHighest(high, alpha);
numberOfLows = countLowest(low, alpha);
// if we have more highs than lows, we must check number of lows
if (numberOfHighs > numberOfLows){
if (numberOfLows === 1){
console.log('YES');
} else {
console.log('NO');
}
} else if (numberOfLows > numberOfHighs){
if (numberOfHighs === 1){
console.log('YES');
} else {
console.log('NO');
}
} else if (numberOfLows === numberOfHighs){
if (numberOfHighs === 1){
console.log('YES');
}
else {
console.log('NO');
}
}
}
//nsole.log('Highest: ' + high + ' | Lowest: ' + low);
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
C Sherlock and the Valid String HackerRank Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int test(int *alphabet)
{
int num = alphabet[0];
int i;
for(i = 1; i < 26; i++)
{
if(alphabet[i] == num)
{
num = alphabet[i];
}
else if(alphabet[i] != num && alphabet[i] != 0)
return 0;
}
return 1;
}
int main() {
int i = 0;
int alphabet[26];
int c = EOF;
int num, pass = 0;
for(i = 0; i < 26; i++)
alphabet[i] = 0;
while (( c = getchar() ) != '\n' && c != EOF)
{
alphabet[c - '0' - 49]++;
}
if(test(alphabet))
printf("YES\n");
else
{
for(i = 0; i < 26; i++)
{
if(i != 0)
alphabet[i - 1]++;
alphabet[i]--;
if(test(alphabet))
{
printf("YES\n");
pass = 1;
break;
}
}
if(pass == 0)
printf("NO\n");
}
return 0;
}
Leave a comment below