← Questions

Count arithmetic triples in a multiset under add and remove queries

0
DatabricksCodingLast asked Aug 2024

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; x is 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 d positive? Can it be 0 (then a triple is three copies of one value)?
  • Does -x remove 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 where x is the first, middle or last value. Subtract their old contribution c[x-2d]·c[x-d]·c[x] + c[x-d]·c[x]·c[x+d] + c[x]·c[x+d]·c[x+2d], update c[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

  • -x removes only one copy.
  • Count arithmetic sequences of length 4 or k.
  • d changes between queries.

Where it's asked

What it tests

hash maps · counting · math

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