Three Sum
Hard Problems: N-Sum & Hashing DSA practice problem on Onlearn.
Difficulty: medium.
Topics: Find all unique triplets in an array that sum to zero, Arrays, Hashing, Sorting, Two Pointers, Set, Time Complexity, Space Complexity, Loops, Conditional Statements, complexity analysis, brute force, sorting algorithms, hashing, duplicate handling, two pointer technique, Duplicate Handling in Arrays.
Problem Statement Given an array nums of N integers, your task is to find all unique triplets [nums[a], nums[b], nums[c]] such that a != b, b != c, c != a, and their sum is equal to zero. You need to return an array of all such unique triplets. Input Specification The input will consist of a single array of integers, nums. Output Specification Return a list of lists, where each inner list represents a unique triplet [a, b, c] whose elements sum to zero. The order of the triplets or the elements within a triplet does not matter, but each unique triplet should appear only once. Examples Example 1: Input: nums = [ 1,0,1,2, 1, 4] Output: [[ 1, 1,2],[ 1,0,1]] Explanation: Out of all possible unique triplets, [ 1, 1,2] and [ 1,0,1] satisfy the condition of summing up to zero with distinct indices. Example 2: Input: nums = [ 1,0,1,0] Output: [[ 1,0,1]] Explanation: Out of all possible unique triplets, [ 1,0,1] sums to zero with distinct indices. Note that [ 1,1,0] is considered the same triplet as [ 1,0,1] when sorted.