March 1, 2021 Andrey

Moving boxes to one spot – Leetcode coding problem (Medium)

Another fun problem that was pretty easy solve is moving boxes to one spot: https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/

It can be solved by iterating over an array and summing difference in distance between elements.

Solution in Javascript:

var minOperations = function(boxes) {
  
     var number = [];
    
    for (var i = 0; i < boxes.length; i++) {
        number.push(boxes.charAt(i));
    }
    
    var result = [];
    for (var i = 0; i < boxes.length; i++) {
        var distance = 0;
        for (var j = 0; j < boxes.length; j++) {
            if (i != j) {
                if ( boxes.charAt(j) == 1) {
                    distance +=  Math.abs(i-j);
                }
            }
        }
        result.push(distance);
    }
    
    return result;
};
, ,