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
What should be the correct Algorithm to Get Array B from Array A counting backwards from the last element in JavaScript?
Consider the following binary array (Array A) −
const arr = [1,0,1,1,1,1,0,1,1];
When this array is passed through the function, say sumRight(), it produces the following output array (Array B) −
const output = [1,0,4,3,2,1,0,2,1];
Understanding the Algorithm
Elements in array arr can be either 0 or 1. The function counts backward from the last element of array arr, if there are consecutive 1's in the array arr then the corresponding element in the output array will be 1 but for the 2nd consecutive 1 in array arr, it will be 2. For the 3rd one in input array the element in the output array will be 3, but for 0 in the array arr it will be 0 in the output array as well.
Implementation Using reduceRight()
So let's write the code for this function using the Array.prototype.reduceRight() method, which does the same work as the normal reduce method, it just starts from the right instead of left −
const arr = [1,0,1,1,1,1,0,1,1];
const sumRight = arr => {
return arr.reduceRight((acc, val) => {
const { prev, res } = acc;
if(val === 0){
return {
prev: 0,
res: res.concat(0)
};
};
return {
res: res.concat(val+prev),
prev: prev+1
};
}, {
prev: 0,
res: []
}).res.reverse();
};
console.log(sumRight(arr));
[
1, 0, 4, 3, 2,
1, 0, 2, 1
]
How It Works
The algorithm processes the array from right to left using reduceRight():
-
Accumulator: Contains
prev(consecutive 1's counter) andres(result array) - For 0: Resets counter to 0 and adds 0 to result
- For 1: Adds (1 + previous counter) to result and increments counter
- Final step: Reverses the result array to match original order
Alternative Implementation
Here's a more straightforward approach using a simple loop:
const arr = [1,0,1,1,1,1,0,1,1];
function sumRightSimple(arr) {
const result = new Array(arr.length);
let count = 0;
// Process from right to left
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === 0) {
count = 0;
result[i] = 0;
} else {
count++;
result[i] = count;
}
}
return result;
}
console.log(sumRightSimple(arr));
[
1, 0, 4, 3, 2,
1, 0, 2, 1
]
Conclusion
Both implementations achieve the same result by counting consecutive 1's from right to left. The reduceRight() approach is more functional, while the loop-based solution is more intuitive and efficient for this specific problem.
