FastPrepFastPrep
Problem Brief

Counting Pairs

OA
See Amazon online assessment and hiring insights

Given an integer k and a list of integers, count the number of distinct valid pairs of integers (a, b) in the list for which a + k = b. Two pairs of integers (a, b) and (c, d) are considered distinct if at least one element of (a, b) does not also belong to (c, d). Note that the elements in a pair might be the same element in the array. An instance of this is below where k = 0.

Function Description

Complete the function countPairs in the editor.

countPairs has the following parameter(s):

  1. int numbers[n]: array of integers
  2. int k: target difference

Returns

int: number of valid (a, b) pairs in the numbers array that have a difference of k

๐ŸŠ 1001 thanks to spike for carring! ๐Ÿ…

1Example 1

Input
numbers = [1, 1, 1, 2], k = 1
Output
1
Explanation
This arr has 3 different valid pairs: (1, 1), (1, 2), and (2, 2,). For k = 1, there is only 1 valid pair which satisfies a + k = b: the pair (a, b) = (1, 2)

2Example 2

Input
numbers = [1, 2], k = 0
Output
2
Explanation
This arr has 3 different valid pairs: (1, 1), (1, 2), and (2, 2,). For k = 0, there is only 2 valid pair which satisfies a + k = b: 1 + 0 = 1 and 2 + 0 = 2.

Constraints

Limits and guarantees your solution can rely on.

  • 2 <= n <= 2 * 10^5
  • 0 <= numbers[i] <= 10^9, where 0 <= i < n
  • 0 <= k <= 10^9
  • public int countPairs(int[] numbers, int k) {
      // write your code here
    }
    
    Input

    numbers

    [1, 1, 1, 2]

    k

    1

    Output

    1

    Sign in to submit your solution.