Ctrl K

Clear Tokens That Share a Line

Medium
Tokens sit on a grid; tokens[i] = [x, y] gives the position of token i, and no cell holds more than one token. In one move you may take a token off the board if at least one other token that is still on the board lies in the same row (same x) or the same column (same y). You choose the order of the moves. Return the largest number of tokens you can remove.
Example 1
tokens=[[0, 0], [0, 3], [2, 3], [5, 5]] → 2

Token (0, 0) shares a row with (0, 3), which shares a column with (2, 3). Remove (2, 3) (its column still has (0, 3)), then (0, 3) (its row still has (0, 0)). Tokens (0, 0) and (5, 5) are left alone, so the answer is 2.

Example 2
tokens=[[1, 1], [2, 2], [3, 3]] → 0

No two tokens share a row or a column, so nothing can be removed.

Example 3
tokens=[[4, 1], [4, 7], [9, 7], [9, 1]] → 3
Constraints
  • 1 ≤ len(tokens) ≤ 1000
  • 0 ≤ x, y ≤ 10⁴
  • All positions are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRooms Open from the Hall MediumGroups Linked by Shared Tags MediumWhich Machine to Cure HardWhich Machine to Unplug HardDo the Links Form a Tree Medium
loading Python…
Input
tokens=[[0, 0], [0, 3], [2, 3], [5, 5]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.