Skip to content

Instantly share code, notes, and snippets.

@SidSam
Last active May 9, 2016 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SidSam/6431ee029f38d7aca1ec90b7ec0e869f to your computer and use it in GitHub Desktop.
Save SidSam/6431ee029f38d7aca1ec90b7ec0e869f to your computer and use it in GitHub Desktop.
HackerRank problem on strings
# A "valid" string is a string SS such that for all distinct characters in SS each such character occurs the same number of times in SS.
# For example, aabb is a valid string because the frequency of both characters a and b is 22, whereas aabbc is not a valid string because the frequency of characters a, b, and c is not the same.
# Watson gives a string SS to Sherlock and asks him to remove some characters from the string such that the new string is a "valid" string.
# Sherlock wants to know from you if it is possible to be done with less than or equal to one removal.
# Input Format
# The first and only line contains SS, the string Watson gives to Sherlock.
# Output Format
# Output YES if string SS can be converted to a "valid" string by removing less than or equal to one character.
# Else, output NO.
# Constraints:
# 1≤size of stringS≤1051≤size of stringS≤105
# String SS contains lowercase letters (a-z) only.
from collections import Counter
c = Counter(raw_input())
d = Counter(c.values())
distinct_counts = list(set(d.elements()))
if len(d) == 1:
print "YES"
elif len(d) == 2:
the_greater_count = max(distinct_counts[0], distinct_counts[1])
the_lesser_count = min(distinct_counts[0], distinct_counts[1])
if the_greater_count - the_lesser_count == 1:
if d[the_greater_count] == 1:
print "YES"
elif d[the_lesser_count] == 1:
print "YES"
else:
print "NO"
elif d[the_lesser_count] == 1:
print "YES"
else:
print "NO"
else:
print "NO"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment