Unique Pairs Summing to Target in Array

🔥 DSA Series | Day 11 We all have seen the classic Two Sum / Pair Sum problem everywhere — even trending on LinkedIn. But today, a small twist struck my mind… 🤔 👉 What if we need to find ALL UNIQUE pairs that sum to a target? 💡 Problem Input: arr = [1,1,2,2,3,3] target = 4 👉 Expected Output: [[1,3], [2,2]] 🚀 Approach (Two Pointers + Sorting) Instead of brute force ❌ (O(n²)), we: Sort the array Use two pointers (i, j) Move intelligently based on sum Skip duplicates to ensure uniqueness 🧠 Code class Solution: def uniquePairs(self, arr: list[int], target: int) -> list[list[int]]: arr.sort() n = len(arr) i = 0 j = n - 1 res = [] while i < j: total = arr[i] + arr[j] if total == target: res.append([arr[i], arr[j]]) i += 1 j -= 1 # 🔁 Skip duplicates while i < j and arr[i] == arr[i - 1]: i += 1 while i < j and arr[j] == arr[j + 1]: j -= 1 elif total < target: i += 1 else: j -= 1 return res if res else [[-1, -1]] ⚡ Complexity ⏱️ Time → O(n log n) (sorting dominates) 📦 Space → O(1) (excluding output) 🔥 Key Insight 💡 Removing duplicates smartly during traversal is more efficient than removing them beforehand. 🧠 Takeaway Sometimes a small twist in a common problem → turns it into a great interview question What would you choose? 🤔 🔹 Hashing (O(n)) 🔹 Two Pointers (O(n log n), cleaner) Let’s discuss 👇 #DSA #Coding #Python #InterviewPrep #ProblemSolving #100DaysOfCode #Tech #Learning

  • text

To view or add a comment, sign in

Explore content categories