Facebook | Phone | Fill grid with players

Anonymous User
487
Sep 03, 2022
Sep 03, 2022

Software Engineer, Machine Learning | Remote | Canada

Question 1

Given a n*n grid (n = 8) and m types of players (m = 4), fill the grid with players evenly and randomly such as every configuration possible has equal probability to be generated. You may assume that n is always a multiple of m (so each player has n/m positions to fill).

Example:

for n = 2 and m = 2, the following configurations should have equal chance to be generated: [[2,2], [1,1]] ; [[1,1], [2,2]] ; [[1,2], [1,2]] ; [[1, 2], [2,1]]; [[2, 1], [2,1]] ; [[2, 1], [1,2]]

Follow up question:

What is the time complexity of your algorithm?

Proposed solution (not accepted by interviewer):

def fill_grid(grid, n_players = 4):
  # Each player has the same allowed number of spots
  p_budget = (len(grid) * len(grid[0])) // n_players
  p_dic = {p : p_budget for p in range(1, n_players + 1)}

  for i in range(len(grid)):
    for j in range(len(grid[0])):
      while True:
        s = random.randint(1, n_players)
        if p_dic[s] == 0:
          continue
        p_dic[s] -= 1
        grid[i][j] = s
        break

Question 2

You are given a directed acyclic graph as a list of pairs, where the first element is a source node and the second element the destination node. Write a function that takes two nodes and returns whether they have a common ancestor or not.

Example 1:

Input: ([[A, B], [A, C], [A, D], [B, G], [E, F]] ; B; G)
Output: True

Example 2:

Input: ([[A, B], [A, C], [A, D], [B, G], [E, F]] ; B; F)
Output: False

Follow up question:

BFS usually runs at O(|E| + |V|). Can we do better (in terms of complexity)?

Comments (6)