← Questions
Count arithmetic triples in a multiset under add and remove queries
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 hash maps, counting and math.
Start with an empty multiset of integers and a fixed difference d. Each query either adds one copy of x or removes every copy of x. After each query, report how many triples of elements (each copy counted separately) can be ordered as v, v + d, v + 2d.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
count_triples(queries: list[str], d: int) -> list[int]— queries are"+x"(add one copy) and"-x"(remove every copy;xis present). Return the count after each query.
Example
count_triples(["+4", "+5", "+6", "+4", "+3", "-4"], 1)
-> [0, 0, 1, 2, 4, 0]
# after +6: (4, 5, 6); a second 4 doubles it to 2; +3 adds two copies of (3, 4, 5); -4 removes every triple
Constraints
- A removed value is always present.
- Recounting every triple after each query is too slow once there are many queries.
-
d > 0.
Clarifying questions
- Is
dpositive? Can it be 0 (then a triple is three copies of one value)? - Does
-xremove every copy, or one copy? - Can the count overflow 64 bits?
What a strong answer covers
- A count per value,
c[v], and a running total. - When
c[x]changes, only three triples can change: those wherexis the first, middle or last value. Subtract their old contributionc[x-2d]·c[x-d]·c[x] + c[x-d]·c[x]·c[x+d] + c[x]·c[x+d]·c[x+2d], updatec[x], add the new one. - O(1) per query.
- Tests: duplicates, removing a value in the middle of a triple, values far apart.
Follow-ups
-
-xremoves only one copy. - Count arithmetic sequences of length 4 or
k. -
dchanges between queries.
Where it's asked
- Databricks · Online assessment · Last asked Aug 2024Timed online coding test
What it tests
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
