Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing duplicates from a sorted array of literals in JavaScript
When working with sorted arrays in JavaScript, removing duplicates is a common operation. Since the array is already sorted, duplicate elements appear consecutively, making the removal process more efficient.
What is a Sorted Array?
A sorted array is an array where elements are arranged in a specific order (ascending or descending). In JavaScript, this ordering makes it easier to identify and remove duplicate elements since identical values are grouped together.
const sortedArray = [1, 2, 2, 3, 4, 6, 6]; // After removing duplicates const uniqueArray = [1, 2, 3, 4, 6];
Method 1: Using Two Pointers (Optimal)
The most efficient approach for sorted arrays uses two pointers to track unique elements:
function removeDuplicates(sortedArray) {
if (sortedArray.length === 0) return [];
let writeIndex = 1; // Position to write next unique element
for (let readIndex = 1; readIndex
[1, 2, 3, 4, 5, 6, 7, 8]
Method 2: Using Set (Simple)
A simpler but less memory-efficient approach uses Set:
function removeDuplicatesWithSet(sortedArray) {
return [...new Set(sortedArray)];
}
const sortedArray2 = [1, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8];
console.log(removeDuplicatesWithSet(sortedArray2));
[1, 2, 3, 4, 5, 6, 7, 8]
Method 3: Using filter() with indexOf
function removeDuplicatesWithFilter(sortedArray) {
return sortedArray.filter((item, index) => sortedArray.indexOf(item) === index);
}
const sortedArray3 = [1, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8];
console.log(removeDuplicatesWithFilter(sortedArray3));
[1, 2, 3, 4, 5, 6, 7, 8]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Two Pointers | O(n) | O(1) | Sorted arrays - most efficient |
| Set | O(n) | O(n) | Simple implementation |
| filter() + indexOf | O(n²) | O(n) | Small arrays only |
Key Points
- For sorted arrays, the two-pointer technique is optimal with O(n) time and O(1) space complexity
- Set approach is simpler but uses extra memory
- Always consider whether you need to modify the original array or create a new one
Conclusion
The two-pointer approach is the most efficient method for removing duplicates from sorted arrays. It takes advantage of the sorted nature to achieve optimal time and space complexity while maintaining the original array structure.
