Problem · Array

Counting Pairs

Learn this problem
EasyAmazonOA
See Amazon hiring insights

Problem statement

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

countPairs(numbers: int[], k: int) → int

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! 🍅

Examples

Example 1

numbers = [1, 1, 1, 2]k = 1return = 1
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)

Example 2

numbers = [1, 2]k = 0return = 2
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

  • 2 <= n <= 2 * 10^5
  • 0 <= numbers[i] <= 10^9, where 0 <= i < n
  • 0 <= k <= 10^9
  • More Amazon problems

    drafts saved locally
    public int countPairs(int[] numbers, int k) {
      // write your code here
    }
    
    numbers[1, 1, 1, 2]
    k1
    expected1
    checking account