FastPrepCount Pairs of Overlapping Squares

Count Pairs of Overlapping Squares

Capital One logoCapital One● MediumFULLTIMEOA

Updated

Problem statement

Each entry centers[i] = [x, y] gives the integer coordinates of the center of one square. All squares have side length 2 and are aligned with the x and y axes, so the square centered at [x, y] covers every point from x - 1 to x + 1 horizontally and from y - 1 to y + 1 vertically, its border included.

Two squares overlap when some point lies in both of them. This includes squares that merely touch, whether along part of a side or at a single corner. Different entries may hold the same center. Such squares are identical, so any two of them overlap.

Return how many pairs of squares overlap. A pair is two different indices i < j, so each pair is counted once. The count can be larger than 2^31 - 1, so return it as a 64-bit integer.

Function

countOverlappingPairs(centers: int[][]) → long

Examples

Example 1

centers = [[1,1],[2,3],[4,1],[5,0],[8,0]]return = 3
  • [4,1] and [5,0] are 1 apart on each axis, so their squares share an area.
  • [1,1] and [2,3] are 1 apart on x and 2 apart on y: the top side of the first square and the bottom side of the second share the segment from (1, 2) to (2, 2). Touching counts.
  • [2,3] and [4,1] are 2 apart on each axis, so the squares meet at the single corner (3, 2). That counts too.
  • Every other pair is at least 3 apart on x, so there is a gap between the squares. The answer is 3.

Example 2

centers = [[3,-2],[3,-2],[3,-2],[3,1]]return = 3
  • The first three squares share one center, so they are the same square and each two of them overlap: 3 pairs.
  • The square at [3,1] is 3 above them, which leaves a gap. The answer is 3.

Example 3

centers = [[0,0],[2,2],[4,4],[-2,2],[0,3]]return = 5
  • Corner contacts: [0,0] with [2,2], [2,2] with [4,4], and [0,0] with [-2,2].
  • [0,3] is 2 apart on x and 1 apart on y from both [2,2] and [-2,2], so it touches each along a side.
  • [0,3] is 3 above [0,0] and 4 away on x from [4,4]; [-2,2] is 4 away from [2,2] on x. The answer is 5.

Constraints

  • 1 <= centers.length <= 8 * 10^4
  • centers[i].length == 2
  • -10^9 <= centers[i][0], centers[i][1] <= 10^9

More Capital One Online Assessment questions

Similar questions at other companies

Capital One interview experiences

All Capital One interview questionsSee Capital One hiring insights
Saved
class Solution {
    public long countOverlappingPairs(int[][] centers) {
        // Write your code here.
    }
}
Checking account…