1769. Minimum Number of Operations to Move All Balls to Each Box
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Minimum Number of Operations to Move All Balls to Each Box (Medium) asks you to solve a structured algorithmic task. This is a common Array / String pattern in coding interviews. Two-pass prefix scan (left-to-right then right-to-left) accumulating count and moves.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Two-pass prefix scan (left-to-right then right-to-left) accumulating count and moves.
Related patterns: Array, String, Prefix Sum
1769.cs
C#
// Approach: Two-pass prefix scan (left-to-right then right-to-left) accumulating count and moves.
// Time: O(n) Space: O(n)
public 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[i] == '1' ? 1 : 0;
moves += count;
}
for (int i = boxes.Length - 1, count = 0, moves = 0; i >= 0; --i)
{
ans[i] += moves;
count += boxes[i] == '1' ? 1 : 0;
moves += count;
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)