|
| 1 | +// 2938. Separate Black and White Balls |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/separate-black-and-white-balls/ |
| 5 | +// |
| 6 | +// Tags: Two Pointers - String - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Iterate the string from the left keeping track of where the last white ball in placed, for |
| 11 | + /// each white ball found, move it to the furthest left spot possible and increment the index |
| 12 | + /// of the next white ball, add the number of moves done to the result. Once you have placed |
| 13 | + /// all the white balls on the left, all the black ones will be on the right. |
| 14 | + /// |
| 15 | + /// Time complexity: O(n) - O(1) work for each element in the input. |
| 16 | + /// Space complexity: O(1) |
| 17 | + /// |
| 18 | + /// Runtime 0 ms Beats 100% |
| 19 | + /// Memory 2.43 MB Beats 40% |
| 20 | + #[allow(dead_code)] |
| 21 | + pub fn minimum_steps_loop(s: String) -> i64 { |
| 22 | + let (mut res, mut next_white_idx) = (0, 0); |
| 23 | + for (i, b) in s.bytes().enumerate() { |
| 24 | + if b == b'0' { |
| 25 | + res += (i - next_white_idx) as i64; |
| 26 | + next_white_idx += 1; |
| 27 | + } |
| 28 | + } |
| 29 | + res |
| 30 | + } |
| 31 | + |
| 32 | + /// Same logic but using an iterator. |
| 33 | + /// |
| 34 | + /// Time complexity: O(n) - O(1) work for each element in the input. |
| 35 | + /// Space complexity: O(1) |
| 36 | + /// |
| 37 | + /// Runtime 0 ms Beats 100% |
| 38 | + /// Memory 2.34 MB Beats 100% |
| 39 | + pub fn minimum_steps(s: String) -> i64 { |
| 40 | + s.bytes() |
| 41 | + .enumerate() |
| 42 | + .fold((0, 0), |(res, idx), (i, b)| { |
| 43 | + if b == b'0' { |
| 44 | + (res + (i - idx) as i64, idx + 1) |
| 45 | + } else { |
| 46 | + (res, idx) |
| 47 | + } |
| 48 | + }) |
| 49 | + .0 |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// Tests. |
| 54 | +fn main() { |
| 55 | + let tests = [("101", 1), ("100", 2), ("0111", 0), ("0011000010", 11)]; |
| 56 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 57 | + let mut success = 0; |
| 58 | + for (i, t) in tests.iter().enumerate() { |
| 59 | + let res = Solution::minimum_steps(t.0.to_string()); |
| 60 | + if res == t.1 { |
| 61 | + success += 1; |
| 62 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 63 | + } else { |
| 64 | + println!( |
| 65 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 66 | + i, t.1, res |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | + println!(); |
| 71 | + if success == tests.len() { |
| 72 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 73 | + } else if success == 0 { |
| 74 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 75 | + } else { |
| 76 | + println!( |
| 77 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 78 | + tests.len() - success |
| 79 | + ) |
| 80 | + } |
| 81 | +} |
0 commit comments