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.
Time complexity − O(N)
Example
using System;
namespace ConsoleApplication{
public class Arrays{
public int RemoveDuplicatesFromSortedArrayAndReturnLength(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;
}
}
return index;
}
}
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.RemoveDuplicatesFromSortedArrayAndReturnLength(arr);
Console.WriteLine(res);
Console.ReadLine();
}
}
}Output
5