Skip to content

1769. Minimum Number of Operations to Move All Balls to Each Box 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<int> minOperations(string boxes) {
    vector<int> ans(boxes.length());

    for (int i = 0, count = 0, moves = 0; i < boxes.length(); ++i) {
      ans[i] += moves;
      count += boxes[i] - '0';
      moves += count;
    }

    for (int i = boxes.length() - 1, count = 0, moves = 0; i >= 0; --i) {
      ans[i] += moves;
      count += boxes[i] - '0';
      moves += count;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] minOperations(String boxes) {
    int[] ans = new int[boxes.length()];

    for (int i = 0, count = 0, moves = 0; i < boxes.length(); ++i) {
      ans[i] += moves;
      count += boxes.charAt(i) == '1' ? 1 : 0;
      moves += count;
    }

    for (int i = boxes.length() - 1, count = 0, moves = 0; i >= 0; --i) {
      ans[i] += moves;
      count += boxes.charAt(i) == '1' ? 1 : 0;
      moves += count;
    }

    return ans;
  }
}