Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 8

Write a C# program to remove duplicates from a sorted array in-place. Return the length of the array after removing duplicates. Do not allocate extra space for another array.

Example 1
  • Input: nums = [1, 1, 2]
  • Output: 2, nums = [1, 2, ...]
  • Explanation:
    • The first two elements of nums are 1 and 2 respectively.
    • The function should return 2, the length of the array after removing duplicates.
    • It doesn't matter what values are set beyond the returned length.
Example 2
  • Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
  • Output: 5, nums = [0, 1, 2, 3, 4, ...]
  • Explanation:
    • The first five elements of nums should be 0, 1, 2, 3, and 4 respectively.
    • The function should return 5, and it doesn't matter what values are set beyond the returned length.
Constraints
  • 0 ≤ 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)
ArraysIBMArctwist
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 the two-pointer technique
  • Keep a pointer for the current position to place the next unique element
  • Iterate through the array, comparing adjacent elements
  • If a new unique element is found, place it at the position indicated by the first pointer
  • Return the length of the resulting array

Steps to solve by this approach:

 Step 1: Handle the edge case of an empty array.
 Step 2: Initialize a pointer (uniqueIndex) to keep track of the position for the next unique element.
 Step 3: Start from the second element (index 1) and compare it with the previous unique element.
 Step 4: If the current element is different from the element at uniqueIndex, increment uniqueIndex.
 Step 5: Assign the current element to the new uniqueIndex position.
 Step 6: Continue this process for all elements in the array.
 Step 7: Return uniqueIndex + 1, which represents the new length of the array without duplicates.

Submitted Code :