Count the Number of Fair Pairs

Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if 0 <= i < j < n and lower <= nums[i] + nums[j] <= upper. The answer can exceed 2^31, so it is returned as a 64-bit integer.

30:00

Count the Number of Fair Pairs
medium
Free written solution
Topics
Companies

Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if 0 <= i < j < n and lower <= nums[i] + nums[j] <= upper. The answer can exceed 2^31, so it is returned as a 64-bit integer.

Example 1:
Input: {"nums":[0,1,7,4,4,5],"lower":3,"upper":6}
Output: 6
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • nums.length=n\text{nums.length} = n

  • −109≤nums[i]≤109-10^9 \leq \text{nums}[i] \leq 10^9

  • −109≤lower≤upper≤109-10^9 \leq \text{lower} \leq \text{upper} \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[0,1,7,4,4,5],"lower":3,"upper":6}

Sort nums. A pair only cares about its two values, not their positions, so sorting keeps the answer and lets two pointers count whole blocks of pairs at once.

fair: 3 <= sum <= 6

Sorted nums

0
0
1
1
4
2
4
3
5
4
7
5

■ L

■ partners of L counted at once

■ R

sum <= 6

?

minus sum < 3

?

fair pairs

?

Variables
VariableValue
n6
lower3
upper6
DepthFunction Call
Stack empty
0/25