Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added sherlock-and-valid-string.py #77

Merged
merged 1 commit into from
Oct 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions HackerRank/sherlock-and-valid-string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'''URL = https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem'''
#Question
'''
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.
'''

#ANSWERS
import math
import os
import random
import re
import sys

# Completing the isValid function below.
def isValid(s):

char_dict = {}
for char in s:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
#initiated largest and smallest count with last char
min_count = char_dict[char]
max_count = char_dict[char]
# counting 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
#updated 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()