How to remove duplicates from the sorted array and return the non-duplicated array using C#?


The array is already sorted, we can keep two pointers ii and jj, where ii is the slow-runner while jj is the fast-runner. As long as nums[i] = nums[j]nums[i]=nums[j], we increment jj to skip the duplicate.

When we encounter nums[j] != nums[i] the duplicate run has ended so we must copy its value to nums[i + 1]nums[i+1]. ii is then incremented and we repeat the same process again until jj reaches the end of array.Create an new array copy all the elements from the filtered array till the index and return the new array.

Time complexity − O(N)

Example

 Live Demo

using System;
namespace ConsoleApplication{
   public class Arrays{
      public int[] RemoveDuplicatesFromSortedArrayAndReturnArray(int[] arr){
         int index = 1;
         for (int i = 0; i < arr.Length - 1; i++){
            if (arr[i] != arr[i + 1]){
               arr[index] = arr[i + 1];
               index++;
            }
            else{
               continue;
            }
         }
         int[] newarr = new int[index];
         for (int i = 0; i < index; i++){
            newarr[i] = arr[i];
         }
         return newarr;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
         int[] res = a.RemoveDuplicatesFromSortedArrayAndReturnArray(arr);
         for (int i = 0; i < res.Length; i++){
            Console.WriteLine(res[i]);
         }
         Console.ReadLine();
      }
   }
}

Output

0 1 2 3 4

Updated on: 27-Aug-2021

939 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements