Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 0 additions & 19 deletions Array/26. Remove Duplicates from Sorted Array.py

This file was deleted.

Empty file.
58 changes: 58 additions & 0 deletions problems/easy/remove_duplicates_from_sorted_array_26/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Tags: Array, Two Pointers
from typing import List


class Solution:
"""
Remove Duplicates from Sorted Array

Problem:
Given a sorted array nums, remove the duplicates in-place such that each
element appears only once. Return the number of unique elements.

Approach:
Since the array is sorted, duplicate elements are always adjacent.
We can use two pointers:
- read pointer: scans through the array
- write pointer: tracks where to place the next unique element

Complexity:
Time: O(n) - single pass through the array
Space: O(1) - in-place modification with no extra data structures
"""

def remove_duplicates(self, nums: List[int]) -> int:
"""
Removes duplicates from a sorted array in-place.

Args:
nums: A sorted list of integers (may contain duplicates)

Returns:
int: The number of unique elements (k). The first k elements
of nums will contain the unique elements in sorted order.

Example:
Input: nums = [1,1,2]
Output: k = 2, nums = [1,2,_]
"""
# Edge case: empty array
if not nums:
return 0

# Initialize write pointer to 1 (second position)
# The first element is always unique in a non-empty sorted array
write = 1

# Start read pointer from index 1 (compare with previous element)
for read in range(1, len(nums)):
# Since array is sorted, duplicates are always adjacent
# If current element is different from previous, it's a new unique element
if nums[read] != nums[read - 1]:
# Copy the unique element to the write position
nums[write] = nums[read]
# Move write pointer forward for the next unique element
write += 1

# Return the count of unique elements
return write
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from .solution import Solution


class TestSolution:
def setup_method(self):
self.solution = Solution()

def test_example_1(self):
"""Test from LeetCode example 1"""
nums = [1, 1, 2]
expected_k = 2
expected_nums = [1, 2]

k = self.solution.remove_duplicates(nums)

assert k == expected_k
assert nums[:k] == expected_nums

def test_example_2(self):
"""Test from LeetCode example 2"""
nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
expected_k = 5
expected_nums = [0, 1, 2, 3, 4]

k = self.solution.remove_duplicates(nums)

assert k == expected_k
assert nums[:k] == expected_nums
Loading