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 to insert an element into all positions in an array using recursion - JavaScript?
We are required to declare a function, let's say insertAllPositions, which takes two arguments ?
an element, x, and an array, arr. Functions must return an array of arrays, with each array corresponding to arr with x inserted in a possible position.
That is, if arr is the length N, then the result is an array with N + 1 arrays ?
For example, the result of insertAllPositions(10, [1,2,3]) should be ?
const output = [
[10,1,2,3],
[1,10,2,3],
[1,2,10,3],
[1,2,3,10]
];
We are required to write this function purely using recursion.
How Recursion Works
The recursive approach works by:
- Base case: If the array is empty, return the element in a new array
- Recursive case: Insert the element at the first position, then recursively insert it into all positions of the remaining array
Example
Following is the code ?
const arr = [1, 2, 3];
const num = 10;
const insertAllPositions = (num, arr) => {
return arr.length ?
[[num, ...arr]]
.concat(insertAllPositions(num, arr.slice(1))
.map(el => {
return [arr[0]].concat(el);
})) :
[[num]]
};
console.log(insertAllPositions(num, arr));
Output
This will produce the following output on console ?
[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
Step-by-Step Breakdown
Let's trace through how the recursion works with insertAllPositions(10, [1, 2, 3]):
// Step 1: Insert 10 at first position
console.log("Step 1:", [10, ...[1, 2, 3]]);
// Step 2: Recursively call with [2, 3]
const step2Result = insertAllPositions(10, [2, 3]);
console.log("Step 2 result:", step2Result);
// Step 3: Prepend 1 to each result from step 2
const finalMapped = step2Result.map(el => [1].concat(el));
console.log("Final mapped:", finalMapped);
Step 1: [ 10, 1, 2, 3 ] Step 2 result: [ [ 10, 2, 3 ], [ 2, 10, 3 ], [ 2, 3, 10 ] ] Final mapped: [ [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
Alternative Recursive Approach
Here's a more readable version of the same recursive logic:
const insertAllPositionsAlt = (element, array, index = 0) => {
if (index > array.length) {
return [];
}
// Insert element at current index
const newArray = [...array];
newArray.splice(index, 0, element);
// Recursively get results for next positions
return [newArray, ...insertAllPositionsAlt(element, array, index + 1)];
};
console.log(insertAllPositionsAlt(10, [1, 2, 3]));
[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
Conclusion
The recursive approach to inserting an element at all positions creates N+1 arrays for an array of length N. The key is using the base case of an empty array and recursively building combinations by prepending elements to smaller solutions.
