DEV Community

Abubakar Sadiq Ismail
Abubakar Sadiq Ismail

Posted on

Removing duplicates from a sorted array 14G 10days code challenge

I am in the 14G community and currently learning data structures, algorithms and problems solving.I saw a mail about 10 days coding challenge sprint,
It came just in time as I need it, I am using Geeks4Geeks
I applied and was selected yay!!!!.

Today is the first day of the 10 days challenge and the problems was given a sorted array in ascending order you are to remove duplicates in the array and return it's length.
Category: Easy

The first thing that came to my mind after I started reading the problem and the category was to create a new set iterate through the array and add all the element, because I know sets only take unique values.
Hence I will return the length of the set.
Time Complexity O(n)
Space Complexity O(n)
I went straight to code the solution and submitted.
It failed because i'ts expected that I will use O(1) space complexity and also will modify the original array and remove all the duplicates as well.

Lesson, do not read half way of the question. There might be some detail that will give more information and guidance about a problem.

I then think since the numbers are sorted.
and in descending order, e.g [1,2,3,3,4,,4,4,5....]
The first unique value is at index 0;
I will create a pointer to the next value after unique which is index 1;
pointer = 1
Iterate through the sorted array
check if the unique value is not equal the iteration index
if it is not
assign last unique at the index of pointer
increment pointer

return pointer

Pseudocode
nums = [....]
pointer = 1
for num in nums
if num[pointer -1] != num
num[pointer] = num
pointer++

return pointer

Thanks

Link to leetcode problem

Link to solution in Js

Top comments (0)