2938. Separate Black and White Balls Medium

@problem@discussion
#Two Pointers#String#Greedy



1/**
2 * [2938] Separate Black and White Balls
3 *
4 * There are n balls on a table, each ball has a color black or white.
5 * You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.
6 * In each step, you can choose two adjacent balls and swap them.
7 * Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.
8 *  
9 * <strong class="example">Example 1:
10 * 
11 * Input: s = "101"
12 * Output: 1
13 * Explanation: We can group all the black balls to the right in the following way:
14 * - Swap s[0] and s[1], s = "011".
15 * Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
16 * <strong class="example">Example 2:
17 * 
18 * Input: s = "100"
19 * Output: 2
20 * Explanation: We can group all the black balls to the right in the following way:
21 * - Swap s[0] and s[1], s = "010".
22 * - Swap s[1] and s[2], s = "001".
23 * It can be proven that the minimum number of steps needed is 2.
24 * 
25 * <strong class="example">Example 3:
26 * 
27 * Input: s = "0111"
28 * Output: 0
29 * Explanation: All the black balls are already grouped to the right.
30 * 
31 *  
32 * Constraints:
33 * 
34 * 	1 <= n == s.length <= 10^5
35 * 	s[i] is either '0' or '1'.
36 * 
37 */
38pub struct Solution {}
39
40// problem: https://leetcode.com/problems/separate-black-and-white-balls/
41// discuss: https://leetcode.com/problems/separate-black-and-white-balls/discuss/?currentPage=1&orderBy=most_votes&query=
42
43// submission codes start here
44
45impl Solution {
46    pub fn minimum_steps(s: String) -> i64 {
47        
48    }
49}
50
51// submission codes end
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_2938() {
59    }
60}
61


Back
© 2025 bowen.ge All Rights Reserved.