One Pager Cheat Sheet
- We can develop a program to remove duplicate elements from a sorted array and return the length of the array, as well as the resultant array containing single instances of each element present.
- By comparing elements at consecutive indices, the output of the array
[1,2,2,3,6,6,9,10,10]after removing duplicates is[1, 2, 3, 6, 9, 10]. - Bringing an optimized solution to the problem of removing duplicates from a
sorted arrayusing atwo-pointersapproach, after discussing the slowerbrute forceapproach. Brute Forceis the more efficient and optimized approach to the two discussed strategies.- The brute force approach to removing duplicates from a sorted array involves iterating through the array, copying one instance of each value from the original array to a temporary array, and then copying each single instance from the temporary array to the original array.
- The total space complexity of the brute force approach is O(n), requiring
additional memoryequal to the size of the input arrayarr. - The brute force approach has an
O(n)time and space complexity, wherenis the array's length. - Using the two pointers approach, we can scan the given sorted array, identify duplicates and unique elements, and copy the unique elements to replace duplicates, in order to have a filtered array without duplicates.
- This approach has a Space complexity of
O(n)as it only utilizes two pointers,iandj. - The time complexity of this approach is
O(n), wherenis the number of elements in the array, and the space complexity isO(1)as no additional memory is required.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx76
tests();var ob1;​class TwoPointers{ removeDuplicates(nums,N) { if (N === 0 || N === 1) { return N; }​ let i = 0; for (let j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } let a = i+1; var newarr = new Array(a); for (let z=0;z<a;z++){ newarr[z]=nums[z]; } return newarr }}​function tests() { var assert = require('assert').strict; let pass = 0;​ ob1 = new TwoPointers(); nums1=[2,3,4,4,5,6,6,6,7,8,8]; nums2=[1,1,2,3,4,4,5,6,6,7,8,9,9]; nums3=[2,4,4,6,8,10,10];OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


