1963. Minimum Number of Swaps to Make the String Balanced
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Minimum Number of Swaps to Make the String Balanced (Unknown) asks you to solve a structured algorithmic task. This is a common Two Pointers / String pattern in coding interviews. Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).
Related patterns: Two Pointers, String, Greedy
1963.cs
C#
// Approach: Count unmatched ']' after cancelling matched pairs; answer = ceil(unmatched / 2).
// Time: O(n) Space: O(1)
public class Solution
{
public int MinSwaps(string s)
{
// Cancel out all the matched pairs, then we'll be left with "]]]..[[[".
// The answer is ceil(the number of unmatched pairs / 2).
int unmatched = 0;
foreach (char c in s)
{
if (c == '[')
{
unmatched++;
}
else if (unmatched > 0)
{ // c == ']' and there's a match.
unmatched--;
}
}
return (unmatched + 1) / 2;
}
}Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)