
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Duplicates from Sorted Array Using Chash
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
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
Advertisements