3 Sum

Arrays FAQs(Medium) Medium
  • Fun Fact: The concept underlying this problem is commonly used in data analysis and machine learning
  • For instance, it can be used to identify clusters or groups (triplets in this case) in larger datasets to which certain constraints apply such as their sum equaling zero
  • In finance, it can be used to identify combinations of transactions or investments that counterbalance each other, resulting in a net effect of zero
  • It's an interesting application of array traversal, hash-map utilization, and the two-pointer technique in real-world scenarios

Given an integer array nums.Return all triplets such that:

  • i != j, i != k, and j != k
  • nums[i] + nums[j] + nums[k] == 0.


Notice that the solution set must not contain duplicate triplets. One element can be a part of multiple triplets. The output and the triplets can be returned in any order.

Examples:

Input: nums = [2, -2, 0, 3, -3, 5]

Output: [[-2, 0, 2], [-3, -2, 5], [-3, 0, 3]]

Explanation: nums[1] + nums[2] + nums[0] = 0

nums[4] + nums[1] + nums[5] = 0

nums[4] + nums[2] + nums[3] = 0

Input: nums = [2, -1, -1, 3, -1]

Output: [[-1, -1, 2]]

Explanation: nums[1] + nums[2] + nums[0] = 0

Note that we have used two -1s as they are separate elements with different indexes

But we have not used the -1 at index 4 as that would create a duplicate triplet

Input: nums = [8, -6, 5, 4]

(Give answer with the output and triplets sorted in ascending order)

Constraints

  • 1 <= nums.length <= 3000
  • -104 <= nums[i] <= 104

Hints

  • Begin by sorting the input array to simplify the process of finding triplets and managing duplicates. Sorting ensures that duplicates are adjacent and allows the use of a two-pointer technique.
  • Iterate through the array, fixing one element at a time. For each fixed element, look for a pair of numbers in the remaining array that sum to the negative of the fixed element. Use two pointers, one starting from the next element after the fixed element and the other from the end of the array.

Company Tags

Teladoc Health Oracle DoorDash Nutanix Epic Games ARM Wayfair Robinhood Cloudflare Mastercard Optum Stripe Goldman Sachs Bain & Company Visa Deloitte MongoDB Airbnb Rakuten KPMG AMD Johnson & Johnson Byju's Flipkart NVIDIA Google Microsoft Amazon Meta Apple Netflix Adobe