15. 3Sum Leetcode Solution

Ankita Kanchan
3 min readJan 15, 2024

--

The “3Sum” problem is a classic algorithmic challenge where the goal is to find all unique triplets in an array that sum up to a target value. In this blog post, we will delve into three Python solutions for the 3Sum problem. Each solution will be thoroughly explained, including its steps and a comprehensive analysis of time and space complexity.

Solution 1: Brute Force

def three_sum_bruteforce(nums):
result = []

for i in range(len(nums)):
for j in range(i + 1, len(nums)):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
triplet = [nums[i], nums[j], nums[k]]
triplet.sort()
if triplet not in result:
result.append(triplet)

return result

Explanation:

  1. Triple Nested Loop: The brute force solution utilizes three nested loops to iterate through all possible triplets in the array.
  2. Check and Append: For each triplet, it checks whether the sum is equal to zero, sorts the triplet, and appends it to the result list if it is not already present.

Time Complexity: O(n³)

  • The time complexity is cubic due to the triple nested loops, making it highly inefficient for large input arrays.

Space Complexity: O(1)

  • The space complexity is constant as the solution uses only a few variables regardless of the input size.

Solution 2: Two-Pointer Approach

def three_sum_two_pointer(nums):
nums.sort()
result = []

for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue

target = -nums[i]
left, right = i + 1, len(nums) - 1

while left < right:
current_sum = nums[left] + nums[right]

if current_sum == target:
result.append([nums[i], nums[left], nums[right]])

while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1

left += 1
right -= 1
elif current_sum < target:
left += 1
else:
right -= 1

return result

Explanation:

  1. Sorting: The array is sorted to facilitate the two-pointer approach.
  2. Two-Pointer Technique: The solution employs two pointers, left and right, moving towards each other to find triplets that sum to the target.

Time Complexity: O(n²)

  • The time complexity is quadratic, as the two-pointer approach involves a single loop through the array.

Space Complexity: O(1)

  • The space complexity is constant as the solution uses only a few variables regardless of the input size.

Solution 3: Hash Set

def three_sum_hash_set(nums):
nums.sort()
result = set()

for i in range(len(nums) - 2):
target = -nums[i]
seen = set()

for j in range(i + 1, len(nums)):
complement = target - nums[j]

if complement in seen:
result.add((nums[i], complement, nums[j]))

seen.add(nums[j])

return list(result)

Explanation:

  1. Sorting: Similar to the two-pointer approach, the array is sorted to simplify the search.
  2. Hash Set: A set (seen) is used to store the elements encountered during the iteration.

Time Complexity: O(n²)

  • The time complexity is quadratic, as the solution involves a nested loop through the array.

Space Complexity: O(n)

  • The space complexity is linear due to the use of the seen set, which can potentially store all elements in the array.

Conclusion:

In this blog post, we explored three Python solutions for the “3Sum” problem, each employing a distinct strategy. The brute force approach, while simple, suffers from cubic time complexity, making it impractical for larger datasets. The two-pointer approach and hash set solution offer more efficient alternatives with quadratic time complexity. Understanding these solutions provides valuable insights into algorithmic problem-solving, enabling the selection of the most appropriate approach based on the specific problem constraints.

--

--

Ankita Kanchan

A passionate software engineer and avid learner, I write insightful blogs to share my journey in mastering new technologies.