← Questions
Flip a binary string and count zeros in a prefix
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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-basedi.
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:iaszeros[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:rinverts only a range. Use a segment tree with lazy propagation. - Add
set:i:bthat changes one bit. - Count zeros in any range
[l, r].
Where it's asked
- Databricks · Online assessment · Last asked Aug 2024Timed online coding test
What it tests
prefix sums · strings
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
