15. 3Sum
Intuition
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Naive Solution: Traverse the given array \(O(n^3)\) times.
Approach
- Step 1: Sort the array so that we can use sliding window approach. (Sorting the array takes \(O(N\log N)\) times)
 - Step 2: Creat a hash map 
listand add all elements. - Step 3: For each element in the hash map, apply Two Sum approach!
- Outer Loop: Selects the first element 
nums[i]and ensures it is not greater than0. - Inner Loop: Selects the second element 
nums[j]and calculates the required third element astarget = 0 - nums[i] - nums[j]. - Hash Map Lookup: Uses the hash map to check if the third element exists and its index is greater than 
jto ensure the triplet is unique. - Update Loop Variables: Uses the hash map to update 
jandito skip over duplicate elements. 
 - Outer Loop: Selects the first element 
 
Complexity
- Time complexity: \(T(N) = O(N^2 + N\log N) = O(N^2)\)
 - Space complexity: \(O(N)\) as we implement a hash map. To optimize, we can use two pointer approach.