Implement frequency + distance top‑K queries
GoogleSoftware Engineer · Technical ScreenLast updated
This pair of problems evaluates algorithmic and data-structure skills including frequency counting, multi-criteria ordering and selection for top-K results, geometric distance computation for tie-breaking, and time-indexed storage with nearest-timestamp retrieval.
You will implement solutions for two coding interview questions.
Question 1: Return the top‑K points by frequency (with distance tie‑break)
You are given an array points of 2D integer points, where each point is represented as [x, y]. The array may contain duplicates (the same [x, y] can appear multiple times).
Define:
freq(p)= number of times pointpappears in the array.dist(p)= squared Euclidean distance to the origin,x^2 + y^2.
Return k distinct points sorted by the following priority:
- Higher frequency first (
freqdescending) - If frequencies tie, smaller distance first (
distascending) - If still tied, sort by
xascending, thenyascending
Input
points: list of lengthn, each element[x, y]k: integer,1 <= k <= (# of distinct points)
Output
- A list of
kdistinct points following the ranking above.
Constraints (typical interview assumptions)
1 <= n <= 2 * 10^5-10^4 <= x, y <= 10^4
Question 2: Time-based key-value store with “closest timestamp” lookup
Design a data structure supporting the following operations:
set(key, value, timestamp): store the stringvaluefor stringkeyat integertimestamp.- Assume timestamps for the same
keyare inserted in non-decreasing order. getClosest(key, timestamp) -> value or "":- If
keyhas no stored values, return"". - Otherwise, return the
valuewhose stored timestamp is closest to the querytimestamp. - If there is a tie (equal distance to two timestamps), return the value with the smaller timestamp.
Example
If for key "a" you stored timestamps [2, 10, 15] with values ["x", "y", "z"]:
getClosest("a", 11)returns"y"(10 is closest)getClosest("a", 14)returns"z"(15 is closest)getClosest("a", 12)returns"y"(10 and 15 are equally far; choose smaller timestamp)
What to discuss
- Time and space complexity of your approach
- How you would improve a “naive” solution (e.g., linear scan) to a more optimal one
Constraints (typical interview assumptions)
- Up to
2 * 10^5total operations - Keys and values are strings; timestamps are integers within typical 32-bit range
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.