← Questions

Flip a binary string and count zeros in a prefix

0
DatabricksCodingLast asked Aug 2024

A coding interview question asked in Databricks's online assessment, last asked Aug 2024. It tests prefix sums and strings.

You get a binary string and a list of requests. A flip request inverts every bit of the string. A count:i request asks how many zeros the string currently has from position 0 through position i, inclusive. Return the answers to the count requests, in order.

Interface

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

  • answer(binary: str, requests: list[str]) -> list[int] — requests are "flip" or "count:<i>" with a 0-based i.

Example

answer("1111010", ["count:4", "count:6", "flip", "count:4", "flip", "count:2"])
->  [1, 2, 4, 0]
# 11110 has one zero; 1111010 has two; after a flip 00001 has four; flipped back, 111 has none

Constraints

  • Every index is inside the string.
  • Flips can be frequent, so a flip should not rebuild the string.

Clarifying questions

  • Is the index 0-based and inclusive?
  • Can an index be out of range?
  • Could a later version flip only a range of the string?

What a strong answer covers

  • Prefix counts of zeros computed once.
  • A single "inverted" flag toggled by each flip, so a flip is O(1).
  • Answering count:i as zeros[i + 1] when not inverted, else (i + 1) − zeros[i + 1].
  • O(n + q) total time.
  • Tests: consecutive flips, index 0, the last index.

Follow-ups

  • flip:l:r inverts only a range. Use a segment tree with lazy propagation.
  • Add set:i:b that changes one bit.
  • Count zeros in any range [l, r].

Where it's asked

What it tests

prefix sums · strings

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