TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
nums
.Q: What is the expected output of the function?
[nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.Q: How should the function handle duplicates?
Q: What if the array is empty or contains fewer than three elements?
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
⚠️ Common Mistakes
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