← Questions

Substring search and weighted random sampling

0
GoogleCodingLast asked Mar 2026

A coding interview question asked in Google's first round (coding), last asked Mar 2026. It tests strings, randomization and sampling.

Two problems for a machine learning engineer screen.

Part 1: substring search

Find every position where a pattern occurs in a text, overlapping occurrences included. Start with the direct approach, then do better than checking every position from scratch.

Unless you agree on a different interface with the interviewer, assume:

  • find_all(text: str, pattern: str) -> list[int] — the start indices of every occurrence, in increasing order. Agree with the interviewer what the empty pattern returns.
find_all("abababa", "aba")  ->  [0, 2, 4]
find_all("hello", "ll")     ->  [2]
find_all("abc", "d")        ->  []

Part 2: weighted random sampling

Pick an index at random with probability proportional to its weight.

  • WeightedSampler(weights: list[float]) — weights are non-negative and at least one is positive.
  • sample() -> int — returns i with probability weights[i] / sum(weights).
s = WeightedSampler([1, 3])
s.sample()    # 0 with probability 0.25, 1 with probability 0.75

Constraints

  • Part 1: text up to 10^6 characters, pattern up to 10^5.
  • Part 2: up to 10^5 weights; up to 10^6 calls to sample.

Clarifying questions

  • Part 1: are overlapping matches counted? What alphabet?
  • Part 2: are weights integers or floats? Can they change after construction?
  • Part 2: how many samples will be drawn, compared with the number of weights?

What a strong answer covers

  • Part 1: the naive O(n * m) scan, then KMP (failure function, O(n + m)), the Z-algorithm or Rabin-Karp with a rolling hash (expected linear, with hash collisions checked).
  • Part 2: prefix sums of the weights, a uniform draw in [0, total), and a binary search for the first prefix sum greater than the draw: O(n) setup, O(log n) per sample. Zero weights must never be chosen.
  • The alias method for O(1) sampling after O(n) setup, when there are many samples.
  • Testing a random function: a fixed seed, and checking frequencies over many draws against the expected probabilities with a tolerance.

Follow-ups

  • Part 2 with weights that change: a Fenwick tree for O(log n) updates and samples.
  • Sample k distinct items by weight without replacement.
  • Weighted reservoir sampling over a stream of unknown length.

Where it's asked

  • Google · First round: coding · Last asked Mar 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

strings · randomization · sampling

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding