Leetcode Day 7: Remove Duplicated from Sorted Array Explained
Simona Cancian
Posted on July 8, 2024
The problem is as follows:
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 t_he number of unique elements in nums
_.
Consider the number of unique elements of nums
to be k
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the unique elements in the order they were present innums
initially. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Here is how I solved it:
- First, initialize a pointer
k
and set it to 0. This pointer will keep track of the position of the last unique element in the array.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# Initialize a pointer 'k' and set it to 0
k = 0
- Loop through
nums
array from the second element (index 1). The first element is always unique, so we can skip it for comparison purposes. - Check for duplicates: if the current element
nums[i]
is different from the last unique elementnums[k]
. - If it is, it means we have found a new unique element. Move to the next element and update
nums[k]
to current elementnums[i]
.
for i in range(1, len(nums)):
if nums and nums[i] != nums[k]:
k += 1
nums[k] = nums[i]
- After the loop,
k
will be the index of the last unique element, so the total number of unique elements isk + 1
. Returnk
+ 1 becausek
starts at 0'
return k + 1
Here is the completed solution:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k = 0
for i in range(1, len(nums)):
if nums and nums[i] != nums[k]:
k += 1
nums[k] = nums[i]
return k + 1
💖 💪 🙅 🚩
Simona Cancian
Posted on July 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.