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
How do I recursively remove consecutive duplicate elements from an array?
Suppose, we have an array of Number literals that contains some consecutive redundant entries like this:
const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
We are supposed to write a function compress that takes in this array and removes all redundant consecutive entries in place. So that the output looks like this:
const output = [1, 2, 3, 1];
Let's write the code for this function using recursion to remove consecutive duplicate elements.
Recursive Approach
The recursive function works by traversing the array and comparing each element with the next one. When consecutive duplicates are found, it removes the current element and continues.
const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const compress = (arr, len = 0, canDelete = false) => {
if(len
[ 1, 2, 3, 1 ]
How It Works
The function uses three parameters:
- arr: The array to process
- len: Current index position
- canDelete: Boolean flag indicating if current element should be deleted
On each recursive call, it checks if the current element equals the next element. If they match, the next call will delete the current element using splice().
Alternative Non-Recursive Approach
For comparison, here's a simpler iterative solution:
const testArr2 = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const compressSimple = (arr) => {
for (let i = 0; i
[ 1, 2, 3, 1 ]
Key Points
- Both methods modify the original array in-place
- The recursive approach uses a flag-based system to determine when to delete
- Array indices must be adjusted after each
splice()operation - The algorithm preserves the order of unique consecutive groups
Conclusion
The recursive approach demonstrates how to solve array manipulation problems using recursion. While more complex than iterative solutions, it showcases the power of recursive thinking for array processing tasks.
