FastPrepCount Pairs with Absolute Difference K
Problems/Count Pairs with Absolute Difference K

Count Pairs with Absolute Difference K

Adobe logoAdobe● EasyFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interviewer asked: "Number of pairs with absolute difference as k." The candidate talked about hashing.

The report does not say whether pairs are counted by index, how repeated values count, or how large the input is. Here, each index pair is counted once, repeated values form separate pairs, and k is never negative.

The judged task matches the report at about 90%.

You are given an integer array nums and a non-negative integer k. Return the number of index pairs (i, j) with i < j such that |nums[i] - nums[j]| == k.

Each pair of indices is counted once. Equal values at different indices form different pairs.

Function

countPairsWithDifference(nums: int[], k: int) → long

Examples

Example 1

nums = [1,5,3,4,2]k = 2return = 3

The pairs with difference 2 are (1, 3), (5, 3), and (4, 2), at indices (0, 2), (1, 2), and (3, 4). The answer is 3.

Example 2

nums = [3,1,3,3]k = 0return = 3

With k = 0 we count pairs of equal values. The three 3s at indices 0, 2, and 3 form 3 pairs.

Example 3

nums = [-2,2,-2]k = 4return = 2

Index 1 holds 2, and both -2s differ from it by 4. That gives the pairs (0, 1) and (1, 2), so the answer is 2.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^9

More Adobe problems

  • Evaluate a Parenthesized Integer ExpressionPHONE SCREEN · Seen Oct 2026
  • All Elements of Two BSTs in OrderPHONE SCREEN · Seen Aug 2026
  • Rotate an Array In PlaceOA · PHONE SCREEN · Seen Aug 2026
All Adobe interview questionsSee Adobe hiring insights
Saved
public long countPairsWithDifference(int[] nums, int k) {
    // Write your code here.
}
Checking account…