# Remove duplicates from Sorted Array

Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array.

Examples:

Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
Explanation: All the elements are 2, So only keep one instance of 2.

Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[] = {1, 2, 3, 4, 5}

Naive Approach (Using extra space):

The idea to solve the problem is to

Create a new array and store the unique elements in the new array. For checking duplicate elements, just check two adjacent elements are equal or not because the array is sorted.

Follow the steps mentioned below to implement the idea:

• Create an auxiliary array temp[] to store unique elements.
• Traverse input array and one by one copy unique elements of arr[] to temp[]
• Also, keep track of the count of unique elements. Let this count be j.
• Copy j elements from temp[] to arr[] and return j.

Below is the implementation of the above approach.

## C++

 `// C++ program to remove duplicates` `#include ` `using` `namespace` `std;`   `// Function to remove duplicate elements This function` `// returns new size of modified array.` `int` `removeDuplicates(``int` `arr[], ``int` `n)` `{` `    ``// Return, if array is empty or ` `    ``// contains a single element` `    ``if` `(n == 0 || n == 1)` `        ``return` `n;`   `    ``int` `temp[n];`   `    ``// Start traversing elements` `    ``int` `j = 0;` `  `  `    ``// If current element is not equal to next element` `    ``// then store that current element` `    ``for` `(``int` `i = 0; i < n - 1; i++)` `        ``if` `(arr[i] != arr[i + 1])` `            ``temp[j++] = arr[i];`   `    ``// Store the last element as whether it is unique or` `    ``// repeated, it hasn't stored previously` `    ``temp[j++] = arr[n - 1];`   `    ``// Modify original array` `    ``for` `(``int` `i = 0; i < j; i++)` `        ``arr[i] = temp[i];`   `    ``return` `j;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// removeDuplicates() returns new size of array.` `    ``n = removeDuplicates(arr, n);`   `    ``// Print updated array` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``cout << arr[i] << ``" "``;`   `    ``return` `0;` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## C

 `// C program to remove duplicates` `#include `   `// Function to remove duplicate elements This function` `// returns new size of modified array.` `int` `removeDuplicates(``int` `arr[], ``int` `n)` `{` `    ``// Return, if array is empty or ` `    ``// contains a single element` `    ``if` `(n == 0 || n == 1)` `        ``return` `n;`   `    ``int` `temp[n];`   `    ``// Start traversing elements` `    ``int` `j = 0;` `  `  `    ``// If current element is not equal to next element` `    ``// then store that current element` `    ``for` `(``int` `i = 0; i < n - 1; i++)` `        ``if` `(arr[i] != arr[i + 1])` `            ``temp[j++] = arr[i];`   `    ``// Store the last element as whether it is unique or` `    ``// repeated, it hasn't stored previously` `    ``temp[j++] = arr[n - 1];`   `    ``// Modify original array` `    ``for` `(``int` `i = 0; i < j; i++)` `        ``arr[i] = temp[i];`   `    ``return` `j;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// removeDuplicates() returns new size of array.` `    ``n = removeDuplicates(arr, n);`   `    ``// Print updated array` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``printf``(``"%d "``, arr[i]);` `    ``return` `0;` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `// Java program to remove duplicates`   `class` `Main {` `  `  `    ``// Function to remove duplicate elements This function` `    ``// returns new size of modified array.` `    ``static` `int` `removeDuplicates(``int` `arr[], ``int` `n)` `    ``{` `        ``// Return, if array is empty or ` `        ``// contains a single element` `        ``if` `(n == ``0` `|| n == ``1``)` `            ``return` `n;`   `        ``int``[] temp = ``new` `int``[n];`   `        ``// Start traversing elements` `        ``int` `j = ``0``;` `        ``for` `(``int` `i = ``0``; i < n - ``1``; i++)` `            `  `            ``// If current element is not equal to next` `            ``// element then store that current element` `            ``if` `(arr[i] != arr[i + ``1``])` `                ``temp[j++] = arr[i];`   `        ``// Store the last element as whether it is unique or` `        ``// repeated, it hasn't stored previously` `        ``temp[j++] = arr[n - ``1``];`   `        ``// Modify original array` `        ``for` `(``int` `i = ``0``; i < j; i++)` `            ``arr[i] = temp[i];`   `        ``return` `j;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { ``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5` `};` `        ``int` `n = arr.length;`   `        ``// removeDuplicates() returns new size of array` `        ``n = removeDuplicates(arr, n);`   `        ``// Print updated array` `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``System.out.print(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Python3

 `# Python3 program to` `# remove duplicates` `# Function to remove` `# duplicate elements`     `# This function returns new size of modified array` `def` `removeDuplicates(arr, n):`   `    ``# Return, if array is empty or contains` `    ``# a single element` `    ``if` `n ``=``=` `0` `or` `n ``=``=` `1``:` `        ``return` `n`   `    ``temp ``=` `list``(``range``(n))`   `    ``# Start traversing elements` `    ``j ``=` `0` `    ``for` `i ``in` `range``(``0``, n``-``1``):`   `        ``# If current element is not equal to next` `        ``# then store that current element` `        ``if` `arr[i] !``=` `arr[i``+``1``]:` `            ``temp[j] ``=` `arr[i]` `            ``j ``+``=` `1`   `    ``# Store the last element as whether it is unique` `    ``# or repeated, it isn't stored previously` `    ``temp[j] ``=` `arr[n``-``1``]` `    ``j ``+``=` `1`   `    ``# Modify original array` `    ``for` `i ``in` `range``(``0``, j):` `        ``arr[i] ``=` `temp[i]`   `    ``return` `j`     `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``]` `    ``n ``=` `len``(arr)`   `    ``# removeDuplicates() returns new size of array.` `    ``n ``=` `removeDuplicates(arr, n)`   `    ``# Print updated array` `    ``for` `i ``in` `range``(n):` `        ``print``(``"%d"` `%` `(arr[i]), end``=``" "``)`     `# This code is contributed by aadityaburukwale.`

## C#

 `// Simple C# program to remove` `// duplicates` `using` `System;`   `class` `GFG {` `    `  `    ``// Function to remove duplicate` `    ``// elements This function returns` `    ``// new size of modified array.` `    ``static` `int` `removeDuplicates(``int` `[]arr, ``int` `n)` `    ``{` `        `  `        ``// Return, if array is empty` `        ``// or contains a single element` `        ``if` `(n == 0 || n == 1)` `            ``return` `n;` `    `  `        ``int` `[]temp = ``new` `int``[n];` `        `  `        ``// Start traversing elements` `        ``int` `j = 0;` `        `  `        ``for` `(``int` `i = 0; i < n - 1; i++)` `        `  `            ``// If current element is not equal` `            ``// to next element then store that` `            ``// current element` `            ``if` `(arr[i] != arr[i+1])` `                ``temp[j++] = arr[i];` `        `  `        ``// Store the last element as` `        ``// whether it is unique or ` `        ``// repeated, it hasn't` `        ``// stored previously` `        ``temp[j++] = arr[n-1]; ` `        `  `        ``// Modify original array` `        ``for` `(``int` `i = 0; i < j; i++)` `            ``arr[i] = temp[i];` `    `  `        ``return` `j;` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `Main () ` `    ``{` `        ``int` `[]arr = {1, 2, 2, 3, 4, 4, 4, 5, 5};` `        ``int` `n = arr.Length;` `        `  `        ``n = removeDuplicates(arr, n);`   `        ``// Print updated array` `        ``for` `(``int` `i = 0; i < n; i++)` `            ``Console.Write(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by nitin mittal.`

## Javascript

 ``

Output

```1 2 3 4 5

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Approach using Set :

By using set to remove duplicates from an input array and update the array with unique elements and finally return the count of unique elements.

• Use set to collect unique elements from the array.
• Updates the array with unique elements, modifying the size.
• Prints the modified array, now containing only unique elements.

## C++

 `#include ` `using` `namespace` `std;`   `int` `removeDuplicates(``int` `arr[], ``int` `n) {` `    ``if` `(n <= 1)` `        ``return` `n;`   `    ``set<``int``> uniqueElements;`   `    ``for` `(``int` `i = 0; i < n; ++i) {` `        ``uniqueElements.insert(arr[i]);` `    ``}`   `    ``int` `index = 0;` `    ``for` `(``auto` `it = uniqueElements.begin(); it != uniqueElements.end(); ++it) {` `        ``arr[index++] = *it;` `    ``}`   `    ``return` `uniqueElements.size();` `}`   `int` `main() {` `    ``int` `arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``n = removeDuplicates(arr, n);`   `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``cout << arr[i] << ``" "``;` `    ``}`   `    ``return` `0;` `}`

## Java

 `import` `java.util.HashSet;` `import` `java.util.Set;`   `public` `class` `RemoveDuplicates {`   `    ``// Function to remove duplicates from the array and return the count of unique elements` `    ``static` `int` `removeDuplicates(``int``[] arr, ``int` `n) {` `        ``if` `(n <= ``1``)` `            ``return` `n;`   `        ``// Use a Set to store unique elements` `        ``Set uniqueElements = ``new` `HashSet<>();`   `        ``// Traverse the array and add elements to the Set` `        ``for` `(``int` `i = ``0``; i < n; ++i) {` `            ``uniqueElements.add(arr[i]);` `        ``}`   `        ``int` `index = ``0``;` `        ``// Iterate through unique elements and update the original array` `        ``for` `(``int` `element : uniqueElements) {` `            ``arr[index++] = element;` `        ``}`   `        ``// Return the count of unique elements` `        ``return` `uniqueElements.size();` `    ``}`   `    ``public` `static` `void` `main(String[] args) {` `        ``int``[] arr = {``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``};` `        ``int` `n = arr.length;`   `        ``// Remove duplicates and get the count of unique elements` `        ``n = removeDuplicates(arr, n);`   `        ``// Print the modified array containing unique elements` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``System.out.print(arr[i] + ``" "``);` `        ``}` `    ``}` `}`

Time Complexity: O(N)

Auxiliary Space: O(N)

Efficient Approach:

This problem can be solved efficiently just by maintaining a separate index for the same array as maintained for different array in the previous method and replacing that element with the unique element.

Follow the steps mentioned below to implement the idea:

• Traverse input array from i = 0 to N:
• Keep track of the count of unique elements. Let this count be j.
• Swap arr[j] with arr[i].
• At last, return j.

Below is the implementation of the above approach.

## C++

 `// C++ program to remove duplicates in-place` `#include` `using` `namespace` `std;`   `// Function to remove duplicate elements` `// This function returns new size of modified array.` `int` `removeDuplicates(``int` `arr[], ``int` `n)` `{` `    ``if` `(n==0 || n==1)` `        ``return` `n;`   `    ``// To store index of next unique element` `    ``int` `j = 0;`   `    ``// Doing same as done in Method 1` `    ``// Just maintaining another updated index i.e. j` `    ``for` `(``int` `i=0; i < n-1; i++)` `        ``if` `(arr[i] != arr[i+1])` `            ``arr[j++] = arr[i];`   `    ``arr[j++] = arr[n-1];`   `    ``return` `j;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// removeDuplicates() returns new size of array.` `    ``n = removeDuplicates(arr, n);`   `    ``// Print updated array` `    ``for` `(``int` `i=0; i

## Java

 `// Java program to remove duplicates`   `class` `Main` `{` `    ``// Function to remove duplicate elements` `    ``// This function returns new size of modified` `    ``// array.` `    ``static` `int` `removeDuplicates(``int` `arr[], ``int` `n)` `    ``{` `        ``if` `(n == ``0` `|| n == ``1``)` `            ``return` `n;` `     `  `        ``// To store index of next unique element` `        ``int` `j = ``0``;` `     `  `        ``// Doing same as done in Method 1` `        ``// Just maintaining another updated index i.e. j` `        ``for` `(``int` `i = ``0``; i < n-``1``; i++)` `            ``if` `(arr[i] != arr[i+``1``])` `                ``arr[j++] = arr[i];` `     `  `        ``arr[j++] = arr[n-``1``];` `     `  `        ``return` `j;` `    ``}` `    `  `    ``public` `static` `void` `main (String[] args) ` `    ``{` `        ``int` `arr[] = {``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``};` `        ``int` `n = arr.length;` `        `  `        ``n = removeDuplicates(arr, n);` ` `  `        ``// Print updated array` `        ``for` `(``int` `i=``0``; i

## Python3

 `def` `remove_duplicates(arr):` `    ``n ``=` `len``(arr)` `    ``if` `n ``=``=` `0` `or` `n ``=``=` `1``:` `        ``return` `n`   `    ``# To store index of next unique element` `    ``j ``=` `0`   `    ``# Doing same as done in Method 1` `    ``# Just maintaining another updated index i.e. j` `    ``for` `i ``in` `range``(n ``-` `1``):` `        ``if` `arr[i] !``=` `arr[i ``+` `1``]:` `            ``arr[j] ``=` `arr[i]` `            ``j ``+``=` `1`   `    ``arr[j] ``=` `arr[n ``-` `1``]`   `    ``return` `j ``+` `1`     `# Driver code` `if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``]` `    ``n ``=` `len``(arr)`   `    ``# remove_duplicates() returns new size of array.` `    ``n ``=` `remove_duplicates(arr)`   `    ``# Print updated array` `    ``for` `i ``in` `range``(n):` `        ``print``(arr[i], end``=``" "``)`

## C#

 `// simple C# program to remove` `// duplicates` `using` `System;`   `class` `GfG {` `    `  `    ``// Function to remove duplicate` `    ``// elements This function returns ` `    ``// new size of modified array.` `    ``static` `int` `removeDuplicates(``int` `[]arr, ``int` `n)` `    ``{` `        `  `        ``if` `(n == 0 || n == 1)` `            ``return` `n;` `    `  `        ``// To store index of next` `        ``// unique element` `        ``int` `j = 0;` `    `  `        ``// Doing same as done in Method 1` `        ``// Just maintaining another updated` `        ``// index i.e. j` `        ``for` `(``int` `i = 0; i < n - 1; i++)` `            ``if` `(arr[i] != arr[i + 1])` `                ``arr[j++] = arr[i];` `    `  `        ``arr[j++] = arr[n - 1];` `    `  `        ``return` `j;` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `Main () ` `    ``{` `        ``int` `[]arr = {1, 2, 2, 3, 4, 4,` `                                 ``4, 5, 5};` `        ``int` `n = arr.Length;` `        `  `        ``n = removeDuplicates(arr, n);`   `        ``// Print updated array` `        ``for` `(``int` `i = 0; i < n; i++)` `            ``Console.Write(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by parashar.`

## Javascript

 ``

Output

```1 2 3 4 5

```

Time Complexity: O(N)
Auxiliary Space: O(1)

#### Fastest Efficient Approach: Using Binary Search

The problem requires us to remove duplicate elements from a sorted array, i.e., we need to keep only one copy of each element in the array. Since the array is sorted, all duplicate elements will be adjacent to each other, so we can easily remove them by shifting the subsequent elements of the array to the left.

We can use two pointers i and j, where i points to the last unique element found so far, and j points to the current element being examined. If nums[i] and nums[j] are equal, we just increment j. Otherwise, we increment i and copy nums[j] to nums[i]. At the end, we return i+1, which represents the length of the modified array.

We Would be using Binary Search to solve the particular problem in the fastest way.

Implementation of the above approach:

## C++

 `// C++ program to remove duplicates in-place` `#include` `using` `namespace` `std;`   `// Function to remove duplicate elements` `// This function returns new size of modified array.` `//Using Binarey Search to solve the particular problem efficiently` `int` `binarySearch(vector<``int``> &nums, ``int` `low, ``int` `high, ``int` `val){` `        ``int` `n = nums.size();` `        ``int` `res = -1;` `        ``while``(low<=high){` `            ``int` `mid = low + (high-low)/2;` `            ``//Check for lower limit` `            ``if``(nums[mid] <= val) low = mid+1;` `            ``//check for higher limit` `            ``else``{` `              ``//move to higher limit` `                ``res = mid;` `                ``high = mid-1;` `            ``}` `        ``}` `        ``//check if not found` `        ``if``(res == -1) ``return` `n;` `        `  `        ``return` `res;` `    ``}` `    `  `    ``int` `removeDuplicates(vector<``int``>& nums) {` `        ``int` `n = nums.size();` `        ``int` `idx = 0;  ``// It store indexing of unique elements.`   `        ``while``(idx != n){` `            ``int` `i = binarySearch(nums,idx+1,n-1,nums[idx]); ``// It finds upper bound of elememt.` `            `  `            ``if``(i == n) ``return` `idx+1;  ``// Means that we are not able to upper bound of element.` `            ``idx++;` `            ``nums[idx] = nums[i];` `        ``}` `        ``return` `idx+1;` `    ``}` `// Driver code` `int` `main()` `{` `    ``vector<``int``> arr{1, 2, 2, 3, 4, 4, 4, 5, 5};`   `    ``// removeDuplicates() returns new size of array.` `    ``int` `n = removeDuplicates(arr);`   `    ``// Print updated array` `    ``for` `(``int` `i=0; i

## Java

 `import` `java.util.Arrays;`   `public` `class` `GFG {`   `    ``// Function to remove duplicate elements` `    ``// This function returns new size of modified array.` `    ``// Using Binary Search to solve the particular problem efficiently` `    ``public` `static` `int` `binarySearch(``int``[] nums, ``int` `low, ``int` `high, ``int` `val) {` `        ``int` `n = nums.length;` `        ``int` `res = -``1``;` `        ``while` `(low <= high) {` `            ``int` `mid = low + (high - low) / ``2``;` `            ``// Check for lower limit` `            ``if` `(nums[mid] <= val)` `                ``low = mid + ``1``;` `            ``// Check for higher limit` `            ``else` `{` `                ``// Move to higher limit` `                ``res = mid;` `                ``high = mid - ``1``;` `            ``}` `        ``}` `        ``// Check if not found` `        ``if` `(res == -``1``)` `            ``return` `n;`   `        ``return` `res;` `    ``}`   `    ``public` `static` `int` `removeDuplicates(``int``[] nums) {` `        ``int` `n = nums.length;` `        ``int` `idx = ``0``; ``// It store indexing of unique elements.`   `        ``while` `(idx != n) {` `            ``int` `i = binarySearch(nums, idx + ``1``, n - ``1``, nums[idx]); ``// It finds upper bound of element.`   `            ``if` `(i == n)` `                ``return` `idx + ``1``; ``// Means that we are not able to find the upper bound of the element.` `            ``idx++;` `            ``nums[idx] = nums[i];` `        ``}` `        ``return` `idx + ``1``;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args) {` `        ``int``[] arr = {``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``};`   `        ``// removeDuplicates() returns new size of array.` `        ``int` `n = removeDuplicates(arr);`   `        ``// Print updated array` `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``System.out.print(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by akshitaguprzj3`

## Python3

 `def` `binary_search(nums, low, high, val):` `    ``n ``=` `len``(nums)` `    ``res ``=` `-``1` `    ``while` `low <``=` `high:` `        ``mid ``=` `low ``+` `(high ``-` `low) ``/``/` `2` `        ``if` `nums[mid] <``=` `val:` `            ``low ``=` `mid ``+` `1` `        ``else``:` `            ``res ``=` `mid` `            ``high ``=` `mid ``-` `1` `    ``if` `res ``=``=` `-``1``:` `        ``return` `n` `    ``return` `res`   `def` `remove_duplicates(nums):` `    ``n ``=` `len``(nums)` `    ``idx ``=` `0`  `# It stores the indexing of unique elements.`   `    ``while` `idx !``=` `n:` `        ``i ``=` `binary_search(nums, idx ``+` `1``, n ``-` `1``, nums[idx])  ``# It finds the upper bound of the element.`   `        ``if` `i ``=``=` `n:  ``# Means we are not able to find the upper bound of the element.` `            ``return` `idx ``+` `1` `        ``idx ``+``=` `1` `        ``nums[idx] ``=` `nums[i]` `    `  `    ``return` `idx ``+` `1`   `# Driver code` `if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``1``, ``2``, ``2``, ``3``, ``4``, ``4``, ``4``, ``5``, ``5``]`   `    ``# remove_duplicates() returns the new size of the array.` `    ``n ``=` `remove_duplicates(arr)`   `    ``# Print the updated array` `    ``for` `i ``in` `range``(n):` `        ``print``(arr[i], end``=``" "``)` `        `  `# This code is contributed by rambabuguphka`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `Program` `{` `    ``// Function to remove duplicate elements` `    ``// This function returns the new size of the modified array.` `    ``// Using Binary Search to solve the particular problem efficiently` `    ``static` `int` `BinarySearch(List<``int``> nums, ``int` `low, ``int` `high, ``int` `val)` `    ``{` `        ``int` `n = nums.Count;` `        ``int` `res = -1;` `        ``while` `(low <= high)` `        ``{` `            ``int` `mid = low + (high - low) / 2;` `            ``// Check for lower limit` `            ``if` `(nums[mid] <= val)` `                ``low = mid + 1;` `            ``// Check for higher limit` `            ``else` `            ``{` `                ``// Move to the higher limit` `                ``res = mid;` `                ``high = mid - 1;` `            ``}` `        ``}` `        ``// Check if not found` `        ``if` `(res == -1)` `            ``return` `n;`   `        ``return` `res;` `    ``}`   `    ``static` `int` `RemoveDuplicates(List<``int``> nums)` `    ``{` `        ``int` `n = nums.Count;` `        ``int` `idx = 0; ``// It stores the indexing of unique elements.`   `        ``while` `(idx != n)` `        ``{` `            ``int` `i = BinarySearch(nums, idx + 1, n - 1, nums[idx]); ``// It finds the upper bound ` `                                                                   ``// of the element.`   `            ``if` `(i == n)` `                ``return` `idx + 1; ``// Means that we are not able to find the upper` `                                ``// bound of the element.` `            ``idx++;` `            ``nums[idx] = nums[i];` `        ``}` `        ``return` `idx + 1;` `    ``}`   `    ``static` `void` `Main()` `    ``{` `        ``List<``int``> arr = ``new` `List<``int``> { 1, 2, 2, 3, 4, 4, 4, 5, 5 };`   `        ``// RemoveDuplicates() returns the new size of the array.` `        ``int` `n = RemoveDuplicates(arr);`   `        ``// Print the updated array` `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``Console.Write(arr[i] + ``" "``);` `        ``}`   `        ``Console.WriteLine();` `    ``}` `}`   `// This code is contributed by shivamgupta0987654321`

## Javascript

 `// Function to remove duplicate elements` `// This function returns the new size of the modified array.` `// Using Binary Search to solve the problem efficiently` `function` `binarySearch(nums, low, high, val) {` `    ``let res = -1;` `    ``while` `(low <= high) {` `        ``let mid = Math.floor(low + (high - low) / 2);` `        ``// Check for lower limit` `        ``if` `(nums[mid] <= val) low = mid + 1;` `        ``// Check for higher limit` `        ``else` `{` `            ``// Move to higher limit` `            ``res = mid;` `            ``high = mid - 1;` `        ``}` `    ``}` `    ``// Check if not found` `    ``if` `(res === -1) ``return` `nums.length;`   `    ``return` `res;` `}`   `function` `removeDuplicates(nums) {` `    ``let n = nums.length;` `    ``let idx = 0; ``// It stores the index of unique elements.`   `    ``while` `(idx !== n) {` `        ``let i = binarySearch(nums, idx + 1, n - 1, nums[idx]); ``// Find the upper bound of the element.`   `        ``if` `(i === n) ``return` `idx + 1; ``// Means that we are not able to find the upper bound of the element.` `        ``idx++;` `        ``nums[idx] = nums[i];` `    ``}` `    ``return` `idx + 1;` `}`   `// Driver code` `let arr = [1, 2, 2, 3, 4, 4, 4, 5, 5];`   `// removeDuplicates() returns the new size of the array.` `let n = removeDuplicates(arr);`   `// Print the updated array` `for` `(let i = 0; i < n; i++) {` `    ``console.log(arr[i]);` `}`   `// This code is contributed by shivamgupta0987654321`

Output:

1 2 3 4 5

Time Complexity: O(N) , in the worst case we will traverse whole array when each element of array is unique.
Auxiliary Space: O(1),No extra space is used

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next