-
Notifications
You must be signed in to change notification settings - Fork 243
Three Sum
Raymond Chen edited this page Aug 2, 2024
·
7 revisions
"TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Sorting, Two-Pointer Technique
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- The function
three_sum()
should return all unique triplets from the array nums such that the sum of the triplets equals zero.
HAPPY CASE
Input: [-1, 0, 1, 2, -1, -4]
Expected Output: [[-1, -1, 2], [-1, 0, 1]]
UNHAPPY CASE
Input: [0, 1, 1]
Expected Output: []
EDGE CASE
Input: [0, 0, 0]
Expected Output: [[0, 0, 0]]
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Sort the array, then use a loop with a two-pointer approach to find the triplets that sum to zero.
1. Sort the input array `nums`.
2. Initialize an empty list `result` to store the unique triplets.
3. Loop through the array with index `i` from 0 to len(nums) - 2:
a. Skip duplicates for the current `i`.
b. Initialize two pointers: `left` at `i + 1` and `right` at the end of the array.
c. While left is less than right:
i. Calculate the sum of nums[i], nums[left], and nums[right].
ii. If the sum is zero, add the triplet to `result`, then skip duplicates for `left` and `right`, and adjust both pointers.
iii. If the sum is less than zero, increment `left`.
iv. If the sum is greater than zero, decrement `right`.
4. Return the `result` list
- Not skipping duplicates correctly.
- Mismanaging pointer positions leading to incorrect results or infinite loops.
Implement the code to solve the algorithm.
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]: # Skip duplicate values for i
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]: # Skip duplicates for left
left += 1
while left < right and nums[right] == nums[right - 1]: # Skip duplicates for right
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result