Count Number of Pairs With Absolute Difference K

Given an integer array nums and an integer k, return the number of pairs (i, j) with i < j such that |nums[i] - nums[j]| == k.

30:00

Count Number of Pairs With Absolute Difference K
easy
Free written solution
Topics
Companies

Given an integer array nums and an integer k, return the number of pairs (i, j) with i < j such that |nums[i] - nums[j]| == k.

Example 1:
Input: {"nums":[1,2,2,1],"k":1}
Output: 4
Constraints:
  • 1≤nums.length≤2001 \leq \text{nums.length} \leq 200

  • 1≤nums[i]≤1001 \leq \text{nums}[i] \leq 100

  • 1≤k≤991 \leq k \leq 99

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

Run code to see results.

Input
arr ={"nums":[1,2,2,1],"k":1}

Lay the values out on a number line with a tally for each. A new value x pairs with every earlier x - 1 and x + 1, so only those two tallies matter.

nums · k = 1

1

0

2

1

2

2

1

3

number line · tally of values seen so far

1
2

Bars above a value count its earlier copies. Blue is x - k, pink is x + k, amber is the current value.

pairs

0

Variables
VariableValue
k1
pairs0
n4
DepthFunction Call
Stack empty
0/9