|
| 1 | +// 1963. Minimum Number of Swaps to Make the String Balanced |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/ |
| 5 | +// |
| 6 | +// Tags: Two Pointers - String - Stack - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Iterate the string, when the number of closing brackets is greater |
| 11 | + /// than the number of opening brackets, we swap one with the furthest right opening bracket in |
| 12 | + /// the string. We can do that using and updating counts rather than actually updating the |
| 13 | + /// input string. |
| 14 | + /// |
| 15 | + /// Time complexity: O(n) - We visit each character in the input and do constant time work for |
| 16 | + /// each. |
| 17 | + /// Space complexity: O(1) |
| 18 | + /// |
| 19 | + /// Runtime 8 ms Beats 76% |
| 20 | + /// Memory 4.70 MB Beats 75% |
| 21 | + pub fn min_swaps(s: String) -> i32 { |
| 22 | + // Not needed but helps with early break. |
| 23 | + let mut remaining_opening = s.len() / 2; |
| 24 | + let mut swaps = 0; |
| 25 | + let (mut opening, mut closing) = (0, 0); |
| 26 | + for c in s.chars() { |
| 27 | + match c { |
| 28 | + '[' => { |
| 29 | + opening += 1; |
| 30 | + remaining_opening -= 1; |
| 31 | + } |
| 32 | + _ => closing += 1, |
| 33 | + } |
| 34 | + if closing > opening { |
| 35 | + swaps += 1; |
| 36 | + remaining_opening -= 1; |
| 37 | + opening += 1; |
| 38 | + closing -= 1; |
| 39 | + } |
| 40 | + if remaining_opening == 0 { |
| 41 | + break; |
| 42 | + } |
| 43 | + } |
| 44 | + swaps |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// Tests. |
| 49 | +fn main() { |
| 50 | + let tests = [("][][", 1), ("]]][[[", 2), ("[]", 0)]; |
| 51 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 52 | + let mut success = 0; |
| 53 | + for (i, t) in tests.iter().enumerate() { |
| 54 | + let res = Solution::min_swaps(t.0.to_string()); |
| 55 | + if res == t.1 { |
| 56 | + success += 1; |
| 57 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 58 | + } else { |
| 59 | + println!( |
| 60 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 61 | + i, t.1, res |
| 62 | + ); |
| 63 | + } |
| 64 | + } |
| 65 | + println!(); |
| 66 | + if success == tests.len() { |
| 67 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 68 | + } else if success == 0 { |
| 69 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 70 | + } else { |
| 71 | + println!( |
| 72 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 73 | + tests.len() - success |
| 74 | + ) |
| 75 | + } |
| 76 | +} |
0 commit comments