Count Pairs Whose Sum is Less than Target

Given a **0-indexed** integer array `nums` of length `n` and an integer `target`, return *the number of pairs* `(i, j)` *where* `0 <= i < j < n` *and* `nums[i] + nums[j] < target`.

30:00

Count Pairs Whose Sum is Less than Target
easy
Free written solution
Topics
Companies

Given a 0-indexed integer array nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.

Example 1:
Input: {"nums":[-1,1,2,3,1],"target":2}
Output: 3
Constraints:
  • 1≤nums.length==n≤501 \leq \text{nums.length} == n \leq 50

  • −50≤nums[i],target≤50-50 \leq \text{nums}[i], \text{target} \leq 50

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

Run code to see results.

Input
arr ={"nums":[-1,1,2,3,1],"target":2}

Count pairs i < j with nums[i] + nums[j] < 2. Pair order does not matter, so we can sort first and count whole groups of pairs at once.

nums, target = 2

0
-1
1
1
2
2
3
3
4
1

pair grid: row i, column j (i < j)

-1
1
2
3
1
-1
1
2
3
1

nums[lo]+nums[hi]

-

added now

-

count

0

pair (lo, hi) being tested
row counted at once
column ruled out
Variables
VariableValue
lo0
hi4
target2
count0
DepthFunction Call
Stack empty
0/6