LeetCode #3649 — MEDIUM

Number of Perfect Pairs

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums.

A pair of indices (i, j) is called perfect if the following conditions are satisfied:

  • i < j
  • Let a = nums[i], b = nums[j]. Then:
    • min(|a - b|, |a + b|) <= min(|a|, |b|)
    • max(|a - b|, |a + b|) >= max(|a|, |b|)

Return the number of distinct perfect pairs.

Note: The absolute value |x| refers to the non-negative value of x.

Example 1:

Input: nums = [0,1,2,3]

Output: 2

Explanation:

There are 2 perfect pairs:

(i, j) (a, b) min(|a − b|, |a + b|) min(|a|, |b|) max(|a − b|, |a + b|) max(|a|, |b|)
(1, 2) (1, 2) min(|1 − 2|, |1 + 2|) = 1 1 max(|1 − 2|, |1 + 2|) = 3 2
(2, 3) (2, 3) min(|2 − 3|, |2 + 3|) = 1 2 max(|2 − 3|, |2 + 3|) = 5 3

Example 2:

Input: nums = [-3,2,-1,4]

Output: 4

Explanation:

There are 4 perfect pairs:

(i, j) (a, b) min(|a − b|, |a + b|) min(|a|, |b|) max(|a − b|, |a + b|) max(|a|, |b|)
(0, 1) (-3, 2) min(|-3 - 2|, |-3 + 2|) = 1 2 max(|-3 - 2|, |-3 + 2|) = 5 3
(0, 3) (-3, 4) min(|-3 - 4|, |-3 + 4|) = 1 3 max(|-3 - 4|, |-3 + 4|) = 7 4
(1, 2) (2, -1) min(|2 - (-1)|, |2 + (-1)|) = 1 1 max(|2 - (-1)|, |2 + (-1)|) = 3 2
(1, 3) (2, 4) min(|2 - 4|, |2 + 4|) = 2 2 max(|2 - 4|, |2 + 4|) = 6 4

Example 3:

Input: nums = [1,10,100,1000]

Output: 0

Explanation:

There are no perfect pairs. Thus, the answer is 0.

Constraints:

  • 2 <= nums.length <= 105
  • -109 <= nums[i] <= 109
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums. A pair of indices (i, j) is called perfect if the following conditions are satisfied: i < j Let a = nums[i], b = nums[j]. Then: min(|a - b|, |a + b|) <= min(|a|, |b|) max(|a - b|, |a + b|) >= max(|a|, |b|) Return the number of distinct perfect pairs. Note: The absolute value |x| refers to the non-negative value of x.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Two Pointers

Example 1

[0,1,2,3]

Example 2

[-3,2,-1,4]

Example 3

[1,10,100,1000]
Step 02

Core Insight

What unlocks the optimal approach

  • For any pair (a, b), let <code>x = |a|</code> and <code>y = |b|</code> and assume <code>x <= y</code>; the two conditions simplify to <code>y <= 2*x</code>.
  • Sort the array by absolute value.
  • Maintain two pointers <code>i</code> and <code>j</code> (starting at 0 and 1): for each <code>i</code>, advance <code>j</code> while <code>abs(nums[j]) <= 2*abs(nums[i])</code>.
  • For each <code>i</code>, add <code>j - i - 1</code> to your answer.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3649: Number of Perfect Pairs
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3649: Number of Perfect Pairs
// package main
// 
// import "slices"
// 
// // https://space.bilibili.com/206214
// func perfectPairs1(nums []int) (ans int64) {
// 	slices.SortFunc(nums, func(a, b int) int { return abs(a) - abs(b) })
// 	left := 0
// 	for i, b := range nums {
// 		for abs(nums[left])*2 < abs(b) {
// 			left++
// 		}
// 		ans += int64(i - left)
// 	}
// 	return
// }
// 
// func abs(x int) int {
// 	if x < 0 {
// 		return -x
// 	}
// 	return x
// }
// 
// func perfectPairs(nums []int) (ans int64) {
// 	for i, x := range nums {
// 		if x < 0 {
// 			nums[i] *= -1
// 		}
// 	}
// 
// 	slices.Sort(nums)
// 	left := 0
// 	for j, b := range nums {
// 		for nums[left]*2 < b {
// 			left++
// 		}
// 		// a=nums[i],其中 i 最小是 left,最大是 j-1,一共有 j-left 个
// 		ans += int64(j - left)
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.