Skip to content

Instantly share code, notes, and snippets.

@mstepniowski
Last active April 23, 2020 21:51
Show Gist options
  • Save mstepniowski/4660602 to your computer and use it in GitHub Desktop.
Save mstepniowski/4660602 to your computer and use it in GitHub Desktop.
Solutions to Facebook Hacker Cup 2013 Qualification Round problems (in Python)

Beautiful strings

When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.

The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)

You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?

Input

The input file consists of a single integer m followed by m lines.

Output

Your output should consist of, for each test case, a line containing the string "Case #x: y" where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

Constraints

5 ≤ m ≤ 50

2 ≤ length of s ≤ 500

Balanced Smileys

Your friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go :(

Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.

A message has balanced parentheses if it consists of one of the following:

  • An empty string ""
  • One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  • An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  • A message with balanced parentheses followed by another message with balanced parentheses.
  • A smiley face ":)" or a frowny face ":("

Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

Input

The first line of the input contains a number T (1 ≤ T ≤ 50), the number of test cases. The following T lines each contain a message of length s that you got from John.

Output

For each of the test cases numbered in order from 1 to T, output "Case #i: " followed by a string stating whether or not it is possible that the message had balanced parentheses. If it is, the string should be "YES", else it should be "NO" (all quotes for clarity only)

Constraints

1 ≤ length of s ≤ 100

Find the Min

After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.

John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is not contained in the previous k values of m.

For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1.

John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him.

Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]).

Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given non-negative integers a, b, c and positive integer r, the known values of m can be calculated as follows:

m[0] = a
m[i] = (b * m[i - 1] + c) % r, 0 < i < k

Input

The first line contains an integer T (T <= 20), the number of test cases. This is followed by T test cases, consisting of 2 lines each. The first line of each test case contains 2 space separated integers, n, k (1 <= k <= 10^5, k < n <= 10^9). The second line of each test case contains 4 space separated integers a, b, c, r (0 <= a, b, c <= 10^9, 1 <= r <= 10^9).

Output

For each test case, output a single line containing the case number and the nth element of m.

#!/usr/bin/env python
from collections import Counter
import re
def beauty(s):
s = re.sub(r'[^a-z]', '', s.lower())
r = 0
for j, (char, count) in enumerate(sorted(Counter(s).items(),
key=lambda item: -item[1])):
r += (26 - j) * count
return r
if __name__ == '__main__':
import sys
for j, line in enumerate(list(sys.stdin)[1:]):
print "Case #{}: {}".format(j + 1, beauty(line))
#!/usr/bin/env python
from collections import deque
from heapq import heapify, heappush, heappop
INFINITY = 10 ** 5 + 1
def rand(a, b, c, r):
return (b * a + c) % r
def overwrite_duplicates(l, value=INFINITY):
seen = set([])
for i in xrange(len(l) - 1, -1, -1):
if l[i] in seen:
l[i] = value
seen.add(l[i])
def findmin(n, k, a, b, c, r):
# Prepare available_numbers heap, used_numbers set and used_numbers_ordered deque
# (We use used_numbers as a hack to avoid removing numbers from heap).
available_numbers = set(range(k))
used_numbers = set()
used_numbers_ordered = []
for i in xrange(k):
available_numbers.discard(a)
used_numbers_ordered.append(a)
a = rand(a, b, c, r)
available_numbers = list(available_numbers)
heapify(available_numbers)
overwrite_duplicates(used_numbers_ordered)
used_numbers_ordered = deque(used_numbers_ordered)
# Take advantage of the cyclical property of the problem
next_cycle = n
if n > 2 * k:
next_cycle = 2 * k + 2 + (n % (k + 1))
# Calculate m[n]
for i in xrange(k, next_cycle):
# Find the smallest available number
while True:
min_number = heappop(available_numbers)
if min_number not in used_numbers:
# Available: USE IT!
used_numbers.add(min_number)
used_numbers_ordered.append(min_number)
break
# Return last number to set of available numbers
returned_number = used_numbers_ordered.popleft()
heappush(available_numbers, returned_number)
used_numbers.discard(min_number)
return min_number
def read_numbers(line):
if line[-1] == '\n':
line = line[:-1]
return [int(x) for x in line.split()]
if __name__ == '__main__':
import sys
case_count = int(sys.stdin.readline()[:-1])
for i in range(1, case_count + 1):
n, k = read_numbers(sys.stdin.readline())
a, b, c, r = read_numbers(sys.stdin.readline())
print "Case #{}: {}".format(i, findmin(n, k, a, b, c, r))
#!/usr/bin/env python
import re
def is_balanced(text):
"""Given text containing only braces ((, ), {, }), returns `True`
if they can be balanced. Returns `False` otherwise.
Curly braces ({ and }) are treated as optional.
"""
min_level, max_level = (0, 0)
for c in text:
if c == '(':
min_level += 1
max_level += 1
elif c == ')':
min_level = max(min_level - 1, 0)
max_level -= 1
if max_level < 0:
return False
elif c == '{':
max_level += 1
elif c == '}':
min_level = max(min_level - 1, 0)
return min_level <= 0 <= max_level
def smileys(text):
if re.search(r'[^a-z:() ]', text):
# Correct string may contain only characters: 'a' to 'z',
# ' ' (a space), ':' (a colon) and '(' ')' (parentheses)
return False
# Clean text
text = text.replace(':)', '}')
text = text.replace(':(', '{')
text = re.sub(r'[a-z: ]', '', text)
return is_balanced(text)
if __name__ == '__main__':
import sys
for j, line in enumerate(list(sys.stdin)[1:]):
print "Case #{}: {}".format(j + 1, 'YES' if smileys(line[:-1]) else 'NO')
@rbrito
Copy link

rbrito commented Jan 29, 2013

Super creative way of dealing with smileys and reducing the difficulty of the problem. I will take a closer look at it soon (I hope).

@mehemmedv
Copy link

In this method , you replace all smiley and frowny face with { or } , and then just find is it right sequence or not ? If so I think it will be wrong .

@mstepniowski
Copy link
Author

@mehemmedv I keep track of the minimal (min_level) and maximal level ( max_level) of nesting I'm at after reading each paren. I treat curly braces as optional: } changes only the min_level while { changes only the max_level. After each step I check whether there is a way to interpret the part I've already read correctly (max_level >= 0). That way after the loop I need to only check whether there is some way to close all parentheses (if and only if min_level <= 0 and max_level >= 0).

I think that my approach here is correct. I hope that the above explanation cleared everything for you.

@lc0
Copy link

lc0 commented Jan 29, 2013

hi @zuber,

what do you think about following pattern?

(a():(:)(:)):())))

you can expand into

(a
(
    ):
    (:)
(
    :)
    ):
(
    ))))

Seems like a pretty balanced, but you solution says, that isn't. Am I wrong?

@mstepniowski
Copy link
Author

@lc0 String in your example can't be balanced. It's easy to see that, as there are only four emoticons in the string:

(()
          :(
          :)
(
          :)
)
          :(
))))

There are 3 opening parentheses (() and 6 closing parentheses ()) in the string. Even if you change the two :) to closing parentheses, you won't be able to close all parentheses, so the string can't be balanced. (A string containing only parentheses must have an equal number of opening and closing paretheses in order to be balanced. That condition is necessary but not sufficient).

@lc0
Copy link

lc0 commented Jan 29, 2013

what can you say about my expanded version from the previous comments?

(a
(
    ):
    (:)
(
    :)
    ):
(
    ))))

4 opening and 4 closing parentheses. With two :), one (: and (:)

@mstepniowski
Copy link
Author

@lc0 (:) is not an emoticon. Same for (: and ):. Look again at the problem statement. There are only two emoticons: A smiley face :) or a frowny face :(.

@mstepniowski
Copy link
Author

All solutions correct NAILED IT!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment