DEV Community

Fahad Khan
Fahad Khan

Posted on

DSA progress log- Day 1

Problem: Remove Duplicates from Sorted Array
Platform: LeetCode

*Problem statement: *
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Approach: Two Pointers
We initialize two pointers a and b with 0 and 1 values repectively, than we iterate over the array one time, increment pointer b on each iteration, and increment pointer a once only if nums[a] < nums[b], since the array is in non-decreasing order.

Complexities

Time - O(n)
Space - O(1)

Complete Guide Here:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/6901913/javascript-solution-by-fahad_khan1226-9sgn

var removeDuplicates = function(nums) {
let a = 0, b = 1;
while(b < nums.length) {
if(nums[a] < nums[b]) {
nums[++a] = nums[b];
}
b++;
}
return a + 1;
};

Top comments (0)