1244. Grid Aligned Pairs
A warehouse robot drives along grid lines, so it can travel in a straight run between two crates only when they share exactly one coordinate. You are given points, an array of [x, y] positions; positions may repeat.
Return, as a long, the number of index pairs i < j whose points have the same x but different y, or the same y but different x. Two identical points do not form such a pair, yet each of them still pairs with every other point that shares exactly one coordinate with it. Count with hash maps keyed by x, by y and by the full point. The intended solution runs in O(n) time and O(n) space, where n is the length of points.
Example 1
- Input:
- points = [[17,-4],[17,9],[-6,9],[-6,-4],[17,-4],[8,31]]
- Output:
- 6
- Explanation:
Pairs (0,1), (0,3), (1,2), (1,4), (2,3) and (3,4) share exactly one coordinate, while the identical points 0 and 4 do not count as a pair, giving 6.
Example 2
- Input:
- points = [[40,-7],[-3,12],[25,25],[0,-90],[61,3],[-18,44]]
- Output:
- 0
- Explanation:
All six x values and all six y values are different, so no two points share a coordinate and the answer is 0.
Example 3
- Input:
- points = [[7,70],[7,70],[7,70],[19,70],[7,-5],[19,-5],[42,-5],[3,3]]
- Output:
- 10
- Explanation:
Pairs (0,3), (0,4), (1,3), (1,4), (2,3), (2,4), (3,5), (4,5), (4,6) and (5,6) share exactly one coordinate; the three copies of the first point share both with each other and are skipped, giving 10.
Constraints
-
1 ≤ points.length ≤ 2 * 105 -
points[i].length == 2 -
-109 ≤ x, y ≤ 109 -
points may repeat
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 10,000 msC++ 2,500 msJava 5,000 msJavaScript 5,000 msTypeScript 5,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)