Remove Duplicates from Sorted Array

For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:

In other words, the question is asking us to create a function that takes in an array nums and returns the length of a new array where the duplicate is removed. The examples on the picture above do a great job showing what the inputs and outputs should be for this problem. Example #1 is showing how the output should be an integer which in this case is the array length.

I always plan before I code, but for this blog I’ll show my pseudo code to show my thought process:

Now that there’s a plan, I’ll be solving this problem step by step! Since the problem wants us to return an array length, we need to create a variable that represents that integer. We also know that we have to create a for loop statement that iterates over the nums array. This is what the code looks like so far:

Inside of this for loop, we need to create a conditional that’s going to compare the current number being iterated nums[i] with the previous current number nums[i — 1]. If they’re not equal to each other, then we need to only include the numbers that are not duplicates. Here’s what the code looks like:

The last steps are just about returning array lengths. I decided to create a conditional that will return the length of the array nums only if the length is less than or equal to 1. Since I created arrayLength to represent the length of the array that doesn’t contain the duplicates, I also have to return it! Here’s the full solution:

Here are the outputs for the examples on lines 22 and 23:

I hope this blog was helpful in any way! For more info on for loops, checkout the resource section below!