Skip to main content
Back to problems
#2006
Easy Algorithms

Count number of pairs with absolute difference k

Array Hash Table Counting
85.3% acceptance
Feb 25, 2026
1793
49
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_k_difference(nums: Vec<i32>, k: i32) -> i32 {
    let mut freq = [0i32; 101];
    let mut ans = 0;
    for &x in &nums {
      if x - k >= 1 { ans += freq[(x - k) as usize]; }
      if x + k <= 100 { ans += freq[(x + k) as usize]; }
      freq[x as usize] += 1;
    }
    ans
  }
}