Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with exactly 3).

Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with exactly 3).
from collections import Counter
def step(live):
    c = Counter((r + dr, q + dq) for r, q in live
                for dr in (-1, 0, 1) for dq in (-1, 0, 1) if dr or dq)
    return {p for p, k in c.items() if k == 3 or (k == 2 and p in live)}
live = {(0, 1), (1, 2), (2, 0), (2, 1), (2, 2), (5, 5), (5, 6), (6, 5)}
for _ in range(4): live = step(live)
print(len(live))
What is printed?
  1. A. 9
  2. B. 8
  3. C. 10
  4. D. 5

Correct answer: A. 9

The first five cells form a glider, which keeps 5 live cells and simply moves one cell diagonally every 4 generations. The L-shaped triomino at (5,5) becomes a 2 × 2 block (a still life) after one step. Over 4 steps the two do not interact, so 5 + 4 = 9.

More Coding Interview Problems questions

Exams that ask this topic