Facebook/Meta ML/SWE Phone Screen| Pass | TLV | Random pick with weight

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-04-30Added By Anonymous
Source: Link
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):\n\tsum_s = sum(cake)\n\ttarget = sum_s / (n+1)\n\tcurr_s = 0\n\n\tif sum_s % target != 0:\n\t\treturn False\n\n\tfor i in cake:\n\t\tcurr_s = i + curr_s\n\t\tif curr_s < target:\n\t\t\tcontinue\n\t\telif curr_s > target:\n\t\t\treturn False\n\t\telse:\n\t\t\tcurr_s = 0\n\n\treturn True\n

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():\n\tdef __init__(self, cities:Dict):\n\t\tself.sum_array = []\n\t\tself.cities_populations_sum = {}\n\t\tself.population = 0\n\n\t\tfor city, pop in cities.item():\n\t\t\tself.population += pop\n\t\t\tself.cities_populations_sum[self.population] = city\n\t\t\tself.sum_array.append(self.population)\n\n\tdef get_random_city(self):\n\t\trandom_value = random.(0, self.population)\n\t\tl, r = 0, len(self.sum_array) - 1\n\n\t\twhile l < r:\n\t\t\tm = (l + r) // 2\n\t\t\tif self.sum_array[m] < random_value:\n\t\t\t\tl = m + 1\n\t\t\telse:\n\t\t\t\tr = m\n\n\t\treturn self.cities_populations_sum[r]\n
Comments