Data Structures & Algorithms Two Pointers
💡
Exercise 39

Remove Duplicates Sorted 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a sorted array nums, remove the duplicates in-place such that each element appears only once. Return the new length.

Use the slow/fast pointer pattern. The slow pointer marks where to write the next unique element. The fast pointer scans ahead.

nums = [1, 1, 2] # After: nums = [1, 2, _] → return 2 nums = [0,0,1,1,1,2,2,3,3,4] # After: nums = [0,1,2,3,4,...] → return 5

This is O(n) time, O(1) space — no extra array needed!

📋 Instructions
Implement `remove_duplicates(nums)` that removes duplicates in-place and returns the new length. Test with `nums = [0,0,1,1,1,2,2,3,3,4]`. Print the new length and the modified array up to that length.
Slow pointer starts at index 0 (first element is always unique). Fast pointer scans from index 1. When nums[fast] != nums[slow], increment slow and copy the value.
🧪 Test Cases
Input
k
Expected
5
Test case 1
Input
nums[:k]
Expected
[0, 1, 2, 3, 4]
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.