26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

Tags
C#
Leetcode
Coding
Competitive programming
Problem solving
Published
April 8, 2024
Author
Deegii

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. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Constraints:

  • The input array nums is sorted in non-decreasing order.
  • You must do this by modifying the input array in-place with O(1) extra memory.

Intuition:

Since the array is already sorted, duplicates will be adjacent to each other. We need to iterate through the array, keeping track of the last element encountered. If the current element is different from the last one, it is unique and should be kept. By maintaining an index pointing to the next position where a unique element should be placed, we can modify the array in-place.

Approach:

  1. Initialize index to 0, which will track the position where unique elements will be placed.
  1. Initialize last to an arbitrary large number to ensure it's not equal to any number in nums.
  1. Iterate through the elements of nums.
  1. If the current element (i) is different from the last element encountered, copy it to nums[index] and increment index.
  1. Update last to the current element i.
  1. Finally, return index, which represents the count of unique elements.

Complexity Analysis:

  • Time Complexity: Since we iterate through the array once, the time complexity is O(n), where n is the length of the input array nums.
  • Space Complexity: The algorithm operates in-place, using only a constant amount of extra space, hence the space complexity is O(1).

Code Implementation:

public class Solution { public int RemoveDuplicates(int[] nums) { int index = 0; int last = 1000; // An arbitrary large number foreach(int i in nums) { if(last != i) { nums[index] = i; index++; } last = i; } return index; } }

Blog Posts