# Algorithm Question: Remove Duplicates From Sorted Array

Problem Statement

This question had me a bit confused. I didn’t know where to start until I realized there was a specific technique and trick to this problem. In this algorithm journey, I’ll be taking on the “ Remove duplicates from sorted array ”question. In Leetcode the problem states, “ remove the duplicates in-place such that each unique element appears only once ”. As result, I would have to return the length of all unique integers displayed in the integer. For example, given the array [ 1, 1, 2, 2, 3] the outcome would be 3 unique values in the array.

Constraints and Challenges

I previously solved a problem similar to this question, therefore I approached it with the same mentality. However, my submission was thwarted due to Leetcode wanting a more dynamic approach. My previous strategy was to create an empty array to add unique numbers. Create a for loop and iterate through the current array. Furthermore, insert a conditional if the current index of the number is not found add it to the array. Once my unique elements were added I would then return the length of the array. Unfortunately running through submission tests in Leetcode my strategy failed.

After a few tries and failed attempts, I was able to find a unique solution that would satisfy the LeetCode submission. Here’s the pseudo-code below.

Solution

A unique strategy to solving this question is to add a placeholder for comparison. Therefore that’s exactly what I did in order to satisfy Leetcode submission. I started by creating a variable called length and set it to 1. I used a for loop to iterate through the array then I proceeded to add a conditional. One big giveaway was that the array was sorted, therefore I can add an easy condition to follow through with my for loop and return statement. The condition I added was if the current number is greater than the one before it set the current index of num to the value of length. Once I added num[length] I proceeded to make it equal to the current index. This made it easy to compare the integers in the array. Therefore each current number would check the integer before it. Once it goes through all the integers in the array, I would increment it. Therefore returning the actual length accrued throughout the entire array.

--

--

--

## More from Woodelin florveus

Love podcasts or audiobooks? Learn on the go with our new app.