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.

Algorithm Flow: Right to Left Processing Input: 1 0 1 1 1 1 0 1 1 Process Right to Left Output: 1 0 4 3 2 1 0 2 1 Counter resets to 0 when encountering 0 Counter increments for consecutive 1's from right Blue: 1's, Red: 0's, Green: Transformed values

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) and res (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.

Updated on: 2026-03-15T23:18:59+05:30

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements