All problems
1193MediumArrayMathTwo PointersSorting

Dial Settings That Agree

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3649Number of Perfect Pairs

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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