Bird
Raised Fist0
Interview Preptwo-pointerseasyAmazonGoogle

Count Pairs With Absolute Difference at Most K

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a sorted list of product prices and want to find how many pairs of products have prices close enough to each other, within a certain budget difference.

Given a sorted array of integers nums and an integer K, count the number of pairs (i, j) such that i < j and the absolute difference between nums[i] and nums[j] is at most K. Return the count of such pairs.

1 ≤ n ≤ 10^5-10^9 ≤ nums[i] ≤ 10^90 ≤ K ≤ 10^9nums is sorted in non-decreasing order
Edge cases: All elements are the same → output is n*(n-1)/2K = 0 → count pairs with equal elements onlyArray with only one element → output 0
</>
IDE
def count_pairs(nums: list[int], K: int) -> int:public int countPairs(int[] nums, int K)int countPairs(const vector<int>& nums, int K)function countPairs(nums, K)
def count_pairs(nums, K):
    # Write your solution here
    pass
class Solution {
    public int countPairs(int[] nums, int K) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int countPairs(const vector<int>& nums, int K) {
    // Write your solution here
    return 0;
}
function countPairs(nums, K) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for all inputs due to missing counting logic or early return.✅ Implement two-pointer counting logic: for each right pointer, add right - left to count when difference ≤ K.
Wrong: n*(n-1)Counting pairs as n*(n-1) instead of n*(n-1)/2, double counting pairs.✅ Count pairs only once by ensuring i < j and adding right - left, not twice.
Wrong: Incorrect count ignoring duplicatesNot counting all pairs involving duplicates or counting only unique pairs.✅ Use two pointers to count all pairs including duplicates by adding right - left for each right.
Wrong: TLEUsing brute force O(n^2) nested loops for large inputs.✅ Implement two-pointer O(n) approach to count pairs efficiently.
✓
Test Cases
t1_01basic
Input{"nums":[1,3,4,6,8],"K":3}
Expected6

Pairs with difference ≤ 3 are (1,3), (1,4), (3,4), (3,6), (4,6), (6,8). Total 6 pairs.

t1_02basic
Input{"nums":[2,2,5,9,10],"K":3}
Expected4

Pairs with difference ≤ 3 are (2,2), (2,5), (9,10). Total 3 pairs.

t2_01edge
Input{"nums":[],"K":5}
Expected0

Empty array has no pairs.

t2_02edge
Input{"nums":[7],"K":10}
Expected0

Single element array has no pairs.

t2_03edge
Input{"nums":[5,5,5,5],"K":0}
Expected6

Pairs with difference 0 are all pairs of equal elements: 4 elements → 4*3/2=6 pairs.

t3_01corner
Input{"nums":[1,2,3,4,5],"K":1}
Expected4

Pairs with difference ≤1 are (1,2), (2,3), (3,4), (4,5). Total 4 pairs.

t3_02corner
Input{"nums":[1,1,1,1,1],"K":2}
Expected10

All pairs have difference 0 ≤ 2, total pairs = 5*4/2 = 10.

t3_03corner
Input{"nums":[1,2,2,3,4],"K":1}
Expected6

Pairs with difference ≤1: (1,2), (1,2), (2,2), (2,3), (2,3), (3,4), (2,4) is 3 difference 2 so excluded. Total 7 pairs.

t4_01performance
Input{"nums":[-1000000000,-999999999,-999999998,-999999997,-999999996,-999999995,-999999994,-999999993,-999999992,-999999991,-999999990,-999999989,-999999988,-999999987,-999999986,-999999985,-999999984,-999999983,-999999982,-999999981,-999999980,-999999979,-999999978,-999999977,-999999976,-999999975,-999999974,-999999973,-999999972,-999999971,-999999970,-999999969,-999999968,-999999967,-999999966,-999999965,-999999964,-999999963,-999999962,-999999961,-999999960,-999999959,-999999958,-999999957,-999999956,-999999955,-999999954,-999999953,-999999952,-999999951,-999999950,-999999949,-999999948,-999999947,-999999946,-999999945,-999999944,-999999943,-999999942,-999999941,-999999940,-999999939,-999999938,-999999937,-999999936,-999999935,-999999934,-999999933,-999999932,-999999931,-999999930,-999999929,-999999928,-999999927,-999999926,-999999925,-999999924,-999999923,-999999922,-999999921,-999999920,-999999919,-999999918,-999999917,-999999916,-999999915,-999999914,-999999913,-999999912,-999999911,-999999910,-999999909,-999999908,-999999907,-999999906,-999999905,-999999904,-999999903,-999999902,-999999901],"K":1000000000}
⏱ Performance - must finish in 2000ms

n=100, large K covers entire range, O(n) two-pointer solution must complete within 2s.

Practice

(1/5)
1. Consider the following Python code that reverses a list of characters recursively using two pointers. What will be the final output printed by the program?
def reverseString(s):
    def helper(left, right):
        if left >= right:
            return
        s[left], s[right] = s[right], s[left]
        helper(left + 1, right - 1)

if __name__ == "__main__":
    s = ['a', 'b', 'c', 'd']
    reverseString(s)
    print(s)
easy
A. ['d', 'b', 'c', 'a']
B. ['d', 'c', 'b', 'a']
C. ['a', 'b', 'c', 'd']
D. ['c', 'b', 'a', 'd']

Solution

  1. Step 1: Trace helper calls and swaps

    Initial call helper(0,3): swap s[0] and s[3] -> ['d','b','c','a'] Next call helper(1,2): swap s[1] and s[2] -> ['d','c','b','a'] Next call helper(2,1): left >= right, stop recursion.
  2. Step 2: Final array state

    The array after all swaps is ['d','c','b','a'], which is the reversed input.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    All pairs swapped correctly, final reversed array matches ['d', 'c', 'b', 'a'] [OK]
Hint: Recursive swaps from ends reverse array correctly [OK]
Common Mistakes:
  • Off-by-one errors in recursion base case
  • Swapping wrong indices
  • Not swapping at all
2. Given the following code for trapping rain water, what is the value of the variable water returned by trap([2,0,2])?
easy
A. 4
B. 0
C. 2
D. 1

Solution

  1. Step 1: Initialize variables

    left=0, right=2, left_max=0, right_max=0, water=0
  2. Step 2: Trace iterations

    Iteration 1: height[left]=2, height[right]=2, height[left] not less than height[right], so process right pointer. right_max updated to 2, right moves to 1.
    Iteration 2: left=0, right=1, height[left]=2, height[right]=0, height[left] > height[right], process right pointer.
    height[right]=0 < right_max=2, water += 2 - 0 = 2, right moves to 0.
    Loop ends as left == right.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Water trapped between two height 2 bars with 0 in middle is 2 units [OK]
Hint: Trace pointers and water increments carefully [OK]
Common Mistakes:
  • Off-by-one errors in pointer movement
  • Confusing which pointer to move
  • Incorrectly updating max heights
3. Suppose the 3Sum problem is modified so that elements can be reused multiple times in a triplet (e.g., triplet [0,0,0] is valid if zeros exist). Which modification to the optimal hash set approach correctly handles this variant?
hard
A. Remove the duplicate skipping for fixed element i and inner pointer j, allowing repeated elements.
B. Use three nested loops to allow repeated indices and check sums directly.
C. Keep the same code but remove the sorting step to allow duplicates naturally.
D. Modify the hash set approach to not skip duplicates and allow complement to be equal to nums[j].

Solution

  1. Step 1: Understand reuse means duplicates allowed in triplets

    Allowing reuse means complement can be equal to nums[j], so skipping duplicates must be adjusted.
  2. Step 2: Modify hash set approach accordingly

    Do not skip duplicates; allow complement == nums[j]; sorting still needed to avoid unordered duplicates.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Allowing complement == nums[j] and no skipping duplicates handles reuse correctly [OK]
Hint: Allow complement == nums[j] and no skipping duplicates for reuse [OK]
Common Mistakes:
  • Removing sorting breaks uniqueness
  • Using triple loops is inefficient
  • Removing duplicate skipping blindly causes duplicates
4. Suppose the input array can contain negative integers and zeros, and you want to partition the array so that all even numbers (including negative evens and zero) come before all odd numbers. Which modification to the original two-pointer algorithm is necessary to handle this correctly?
hard
A. Change the parity check to use abs(nums[i]) % 2 == 0 to handle negative numbers
B. Use a sorting-based approach since parity is ambiguous with negative numbers
C. No change needed; the original parity check nums[i] % 2 == 0 works correctly for negatives and zero
D. Add a separate pass to move zeros to the front before partitioning evens and odds

Solution

  1. Step 1: Understand parity with negatives and zero

    In Python, num % 2 == 0 correctly identifies even numbers including negatives and zero.
  2. Step 2: Confirm no algorithm change needed

    The original two-pointer approach works unchanged since parity check is valid for all integers.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Modulo operator handles negative evens and zero correctly [OK]
Hint: Modulo operator works for negative evens and zero [OK]
Common Mistakes:
  • Thinking abs() is needed for parity check
  • Assuming zeros need special handling
  • Believing sorting is required for negatives
5. If the problem changes so that the same element can be used multiple times to reach the target sum (i.e., elements can be reused), which approach correctly solves the problem?
hard
A. Use the two pointers approach moving inward, but allow pointers to stay if sum < target to reuse elements.
B. Use a modified binary search that allows searching from the current index (not i+1) to reuse elements.
C. Use a dynamic programming approach to find combinations allowing repeated elements.
D. Use the brute force nested loops but break early when sum exceeds target.

Solution

  1. Step 1: Understand reuse requirement

    Allowing reuse means pairs can include the same element multiple times, which breaks two-pointer and binary search assumptions.
  2. Step 2: Identify suitable approach

    Dynamic programming can handle combinations with repeated elements efficiently, unlike two pointers or binary search.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DP handles repeated elements and target sums correctly [OK]
Hint: Reuse -> DP for combinations, not two pointers or binary search [OK]
Common Mistakes:
  • Trying to reuse pointers incorrectly
  • Modifying binary search without correctness
  • Assuming brute force is efficient
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard