Two pointers

Input: [2, 3, 3, 3, 6, 9, 9]
Output: 4
        [2, 3, 3, 3, 6, 9, 9]
[fast]: [1, 2, 3, 4, 5, 6, 7]
[slow]: [1, 2, 2, 2, 3, 4, 4]
function remove_duplicates(arr) {
let slow = 1;
let fast = 1;
while (fast < arr.length) {
if (arr[fast] !== arr[fast-1]) {
slow++;
}
fast++;
}
return slow;
}

15. 3Sum Given an array of unsorted numbers, find all unique triplets in it that add up to zero.

Input: [-3, 0, 1, 2, -1, 1, -2]
Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]
Explanation: There are four unique triplets whose sum is equal to zero.
function threeSum(arr) {
arr.sort((a,b) => a - b);
const triplets = [];
for (let i = 0; i < arr.length; i++) {
searchPair(arr, -arr[i], i+1, triplets);
}
return triplets;
}
 function searchPair(arr, targetSum, left, triplets) {
let right = arr.length - 1;
while (left < right) {
const currentSum = arr[left] + arr[right];
if (currentSum === targetSum) {
triplets.push([-targetSum, arr[left], arr[right]]);
left++;
right--;
} else if (targetSum > currentSum) {
left++;
} else {
right--;
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store