CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Remove Duplicates from Sorted Array
array
twopointers
# Remove Duplicates from Sorted Array ## Difficulty Easy ## Tags `array`, `two pointers` ## Problem Statement Given an integer array `nums` sorted in non-decreasing order, remove the duplicates **in-place** such that each unique element appears only once. Return the number of unique elements. The relative order of the elements should be kept the same. The first `k` elements of `nums` should hold the unique values in order. ## Constraints - 1 ≤ nums.length ≤ 3 × 10⁴ - -100 ≤ nums[i] ≤ 100 - `nums` is sorted in non-decreasing order. - Modify array in-place with O(1) extra memory. ## Signatures ### Python ```python def remove_duplicates(nums: List[int]) -> int: pass ``` ### Java ```java public class Solution { public int remove_duplicates(List<Integer> nums) { return null; } } ``` ### Csharp ```csharp public class Solution { public int remove_duplicates(IList<int> nums) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: int remove_duplicates(vector<int> nums) { } }; ``` ### C ```c int remove_duplicates(int* nums) { } ``` ### Ruby ```ruby def remove_duplicates(nums) end ``` ### Perl ```perl sub remove_duplicates { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def remove_duplicates(nums: List[Int]): Int = { } } ``` ### Haskell ```haskell remove_duplicates :: ... -> ... remove_duplicates args = undefined ``` ### Clojure ```clojure (defn remove_duplicates [nums] ) ``` ### Scheme ```scheme (define (remove_duplicates nums) ) ``` ## Examples ### Example 1 **Input:** ``` nums = [1, 1, 2] ``` **Output:** ``` 2 nums = [1, 2, _] ``` **Explanation:** Return 2, with the first two elements being 1 and 2. ### Example 2 **Input:** ``` nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] ``` **Output:** ``` 5 nums = [0, 1, 2, 3, 4, _, _, _, _, _] ``` **Explanation:** Return 5, with unique elements 0, 1, 2, 3, 4. ### Example 3 **Input:** ``` nums = [1] ``` **Output:** ``` 1 ``` ## Hints 1. Use two pointers: `write_index` for where to place unique elements, `read_index` for scanning. 2. Since array is sorted, duplicates are adjacent. 3. Only increment `write_index` when you find a new unique value. 4. Copy the unique value to `write_index` position.
Login required
Please log in to view the solution editor and submit code.
Login
Register