Distinct Pairs with Difference K: Hash Map and Two-Pointer Approaches

Day 25 of 30-days Coding Sprint Today was about finding Distinct Pairs with Difference K, a problem that forces you to handle duplicates carefully to avoid overcounting. The Goal: Find unique pairs (a, b) such that b - a = k. The keyword here is distinct; if we have multiple [1, 5] pairs, we only count them once. Approach 1: The Hash Map (Frequency Logic) - The Strategy: Count the frequency of every number. - The Check: 1. If k > 0, check if map[element + k] exists. - If k = 0, check if map[element] > 1 (since a number minus itself is 0). Pros: Great for O(N) time, but requires extra space for the map. Approach 2: Two-Pointer (Sorted Space) The Strategy: Sort the array first to use the "Expand/Shrink" logic. The Decision Logic: If diff == k: Found a pair! Increment count and skip duplicates using a while loop to maintain uniqueness. If diff < k: Need a larger difference, so move the right pointer. If diff > k: Difference is too big, move the left pointer. Complexity: O(N log N) for sorting, but O(1) auxiliary space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #TwoPointers #Algorithms #ProblemSolving #Consistency

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories