3 Sum Problem Solution with Two Pointers and Sorting

Day 12 of my Python learning journey Today I tried solving a problem that felt like an extension of Two Sum, but it was a bit more tricky. Problem: 3 Sum (using Two Pointers) Given an array, find all unique triplets such that their sum is equal to 0. Example: arr = [-1, 0, 1, 2, -1, -4] Output: [[-1, -1, 2], [-1, 0, 1]] What I learned today: Instead of checking all possible triplets (which is slow), we can: Sort the array first Fix one element Use Two Pointers to find the other two numbers How it works: Fix one number arr[i] Start left from i+1 Start right from the end Check the sum of three numbers • If sum is too small → move left pointer • If sum is too large → move right pointer • If sum is 0 → store the triplet Code I wrote: arr = [-1, 0, 1, 2, -1, -4] arr.sort() result = [] for i in range(len(arr) - 2):     if i > 0 and arr[i] == arr[i - 1]:         continue     left = i + 1     right = len(arr) - 1     while left < right:         s = arr[i] + arr[left] + arr[right]         if s == 0:             result.append([arr[i], arr[left], arr[right]])             while left < right and arr[left] == arr[left + 1]:                 left += 1             while left < right and arr[right] == arr[right - 1]:              right -= 1             left += 1             right -= 1         elif s < 0:             left += 1         else:           right -= 1 print(result) Problems I faced while coding this: At first I tried using three nested loops, but it became too slow. I did not understand why sorting is necessary. I got duplicate triplets and didn’t know how to remove them. The duplicate skipping logic with while loops confused me a lot. What I finally understood: Sorting helps us use the Two Pointer technique and also makes it easier to avoid duplicates. This approach reduces complexity from O(n³) to O(n²). Time and Space Complexity: Time Complexity: O(n²) → one loop + two pointer traversal Space Complexity: O(1) (excluding the output list) Question: Why do we skip duplicates using: if i > 0 and arr[i] == arr[i - 1]: Today’s realization: Some problems look like small extensions, but the logic becomes much deeper. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming

  • text

To view or add a comment, sign in

Explore content categories