LeetCode 26. Remove Duplicates from Sorted Array

Description

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

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

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Example 2:

Explanation

Since the array is already sorted, we can use two pointers technique, where i is the slow pointer while j is the fast pointer.

When nums[i] = nums[j], we increment faster pointer j to skip the duplicate.

When nums[j] != nums[i], we increment the slow pointer i and copy faster pointer place element value to slower pointer place.

Once j reaches the end of the array, all non duplicated elements were adjusted to the beginning of the array.

Video Tutorial

Java Solution

One thought

Leave a Reply

Your email address will not be published. Required fields are marked *