Maps app~25 min2s · 256 MBtarget O(n * k) time, O(n) spaceclassic twin: lc-2013map-design · hashing
A map app lets surveyors place markers on a city grid. A marker sits at a whole-number position (x, y). The same position can hold many markers, because several surveyors can mark the same corner.
A planner wants to know, before placing a new marker, how many squares it would complete. A square has sides parallel to the grid lines and an area above zero. Its four corners are the new marker and three markers already placed.
Write run_markers(commands, args).
commands[i] is "add" or "count", and args[i] is a list [x, y]. There are no markers at the start."add": place a marker at (x, y)."count": do not place anything. Count the squares that have (x, y) as one corner and three placed markers as the other three. Choose each corner from the placed markers, so two markers at the same position count as two different choices."count" commands, in order, as a list of numbers. An "add" records nothing.Input: commands = ["add", "add", "add", "count", "add", "count", "add", "count"], args = [[2, 2], [2, 5], [5, 2], [5, 5], [5, 5], [2, 2], [5, 5], [2, 2]]
Output: [1, 1, 2]A marker straight above or below the query gives the side of the square. The other two corners then lie that far to the left or to the right, at the heights of the query and of that marker.
| Step | Command | Markers placed | Answer |
|---|---|---|---|
| [2] | add (2, 2) | (2, 2) | |
| [2] | add (2, 5) | (2, 2), (2, 5) | |
| [2] | add (5, 2) | (2, 2), (2, 5), (5, 2) | |
| [3] | count (5, 5) | same | 1: the three markers form the other corners |
| [2] | add (5, 5) | the three, plus (5, 5) | |
| [3] | count (2, 2) | same | 1: the side to (2, 5) is 3, and the corners are (5, 2) and (5, 5) |
| [2] | add (5, 5) | the three, plus two at (5, 5) | |
| [3] | count (2, 2) | same | 2: the corner (5, 5) can be chosen two ways |
Input: commands = ["count"], args = [[4, 4]]
Output: [0]There are no markers, so no square.
Input: commands = ["add", "add", "add", "count"], args = [[0, 0], [0, 3], [2, 0], [2, 3]]
Output: [0]The three markers and the query make a rectangle of 2 by 3. It is not a square.
1 ≤ length of commands ≤ 10000, and commands and args have the same length"add" or "count", and every args[i] is [x, y] with 0 ≤ x, y ≤ 1000There can be 5,000 markers and 5,000 counts. Checking every group of three markers for every count is far too much. Even looking at every marker for each count, and then looking again for the other two corners, repeats a great deal of work.
Look at what fixes a square. Given the query and one marker in its column, the side is known, and the other two corners are at exact positions. Each of those positions can be found in a table.