Facebook/Meta ML/SWE Phone Screen| Pass | TLV | Random pick with weight
Company: Meta (Facebook)
Role: unknown
Interview Stage: Phone Screen
Location: TLV
Year: unknown
Original Post Content:
Here are the problems; none of them are on LeetCode, but similar ones.
First
Given a cake with strawberries on it, figure out if we can cut the cake n times and make all the pieces have exact same number of strawberries
Example:
Input: cake: [1, 2, 3] where the number in vector represents the number of strawberries on that part of the cake.
n = 1
Result: True
Example cut: 1 2 | 3
n = 2
Result: False
My answer:
def divide_cake(cake, n):
sum_s = sum(cake)
target = sum_s / (n+1)
curr_s = 0
if sum_s % target != 0:
return False
for i in cake:
curr_s = i + curr_s
if curr_s < target:
continue
elif curr_s > target:
return False
else:
curr_s = 0
return True
-----
Second:
Given a list of city names and their corresponding populations, write a program to output a random city name subject to the following constraint: the probability of the program to output a city's name is based on its population divided by the sum of all cities' population. Assume the program will be repeatedly called many times.
For example:
NY: 7
SF: 5
LA: 8
The probability to generate NY is 7/20, SF is 5/20, LA is 8/20.
similar to RANDOM PICK WITH WEIGHT
class RandomCities():
def __init__(self, cities:Dict):
self.sum_array = []
self.cities_populations_sum = {}
self.population = 0
for city, pop in cities.item():
self.population += pop
self.cities_populations_sum[self.population] = city
self.sum_array.append(self.population)
def get_random_city(self):
random_value = random.(0, self.population)
l, r = 0, len(self.sum_array) - 1
while l < r:
m = (l + r) // 2
if self.sum_array[m] < random_value:
l = m + 1
else:
r = m
return self.cities_populations_sum[r]