![]() |
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} These are the following approaches: Table of Content Using for loopIn this approach, The removeDup function removes duplicate elements from a sorted array. It iterates through the array, comparing each element with its adjacent element. If they are not equal, the current element is added to a new array uniqueArray. Finally, the function returns uniqueArray, which contains unique elements. The provided example removes duplicates from sortedArray and logs the result to the console. Example: This example shows the implementation of the above-explained approach.
Output Array with Duplicates Removed: [ 1, 2, 3, 4, 5 ] Using While loopThe removeDup function removes duplicate elements from a sorted array sortedArray. It uses a while loop with an index i to iterate through the array. Each element is compared with its adjacent element. If they’re not equal, the element is added to `unique Example: This example shows the implementation of the above-explained approach.
Output Array with Duplicates Removed: [ 1, 2, 3, 4, 5 ] Using the Set objectIn this approach we are using the Set object in JavaScript to remove duplicate elements from a sorted array. Here we convert the array into a Set. A Set is a collection of unique values, so any duplicate elements in the array will be automatically removed. Example: In this example we are using above-explained approach.
Output Array with duplicates removed: [ 1, 2, 3, 4, 5 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |