Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to remove duplicates from a sorted array. Given an integer array 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 the array. You must do this by modifying the input array in-place with O(1) extra memory.

Example 1
  • Input: nums = [1,1,2]
  • Output: 2, nums = [1,2,_]
  • Explanation: The function returns 2, with the first two elements of nums being 1 and 2 respectively. The "_" indicates the elements beyond the returned length are not important.
Example 2
  • Input: nums = [0,0,1,1,1,2,2,3,3,4]
  • Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
  • Explanation: The function returns 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. The "_" indicates the elements beyond the returned length are not important.
Constraints
  • 1 ≤ nums.length ≤ 3 * 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • nums is sorted in non-decreasing order
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysEYD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers: one for iterating through the array and one for placing unique elements
  • The first unique element (at index 0) is always part of the result
  • Compare each element with the previous unique element
  • If different, add it to the unique elements section and increment the unique count
  • Be careful with empty arrays and arrays with only one element
  • Remember to return the count of unique elements, not just modify the array

Steps to solve by this approach:

 Step 1: Handle the edge case of an empty array by returning 0.

 Step 2: Initialize a variable uniqueCount to 1, assuming the first element is always unique.
 Step 3: Iterate through the array starting from the second element (index 1).
 Step 4: For each element, compare it with the last unique element (nums[uniqueCount-1]).
 Step 5: If the current element is different from the last unique element, place it at position uniqueCount in the array.
 Step 6: Increment uniqueCount to prepare for the next unique element.
 Step 7: After processing all elements, return uniqueCount as the number of unique elements in the array.

Submitted Code :