LeetCode Solutions: Remove Duplicates from Sorted Array (With a Twist)
Problem statement: Remove Duplicates from Sorted Array
The twist is to change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially.
Intuition
We tackle this problem with an approach with 2 pointers: 'i' and 'j'(they also point to indices in the 'nums' array). The idea is to sweep through the array and place unique elements at their correct positions.
领英推荐
Code
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
unique_count = 0 # Counter for unique numbers
n = len(nums)
# Loop through the array
for i in range(n):
# If the current number is different from the previous unique number
if i == 0 or nums[i] != nums[unique_count - 1]:
# Update the next position with the unique number
nums[unique_count] = nums[i]
# Increment the count of unique numbers
unique_count += 1
# The nums array should have unique_count unique values in the first unique_count positions
return unique_count