Show problems as
Classic problem #3649MediumArrayMathTwo PointersSorting

Number of Perfect Pairs

Real-world version: Dial Settings That Agree
Tracked in this browser only
Read Number of Perfect Pairs on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A bench of dials has been trimmed, trims[i] being the trim on the i-th dial. A trim may be negative.

Two trims a and b agree when both of these hold:

  1. the smaller of |a - b| and |a + b| is no more than the smaller of |a| and |b|;
  2. the larger of |a - b| and |a + b| is no less than the larger of |a| and |b|.

Return the number of pairs of positions i < j whose trims agree.

Examples

Example 1

Input
trims = [4, 7, 9, 2]
Output
3

Magnitudes 2, 4, 7 and 9. The pairs that agree are 2 with 4, 4 with 7, and 7 with 9, since each larger magnitude is within double the smaller. 2 with 7, 2 with 9 and 4 with 9 all miss.

Example 2

Input
trims = [-8, 4, -4, 8]
Output
6

Signs fall away, leaving magnitudes 8, 4, 4 and 8. Since 8 is exactly double 4, and equal magnitudes always agree, all six pairs on the bench agree.

Example 3

Input
trims = [0, 3]
Output
0

The smaller of the two differences is 3 and the smaller magnitude is 0, so the first test fails and the only pair on the bench does not agree.

Constraints

  • 2 <= trims.length <= 10^5
  • -10^9 <= trims[i] <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def perfect_pairs(trims: list[int]) -> int:
Java
public long perfectPairs(int[] trims)