diff --git a/solutions/day08/README b/solutions/day08/README new file mode 100644 index 0000000..0a89dcd --- /dev/null +++ b/solutions/day08/README @@ -0,0 +1,27 @@ +# Minimum Swaps to Balance Brackets USING PYTHON + +## Overview +The algorithm counts the minimum number of swaps required to make a string of brackets balanced. + +## Explanation + +### Stack +- The stack is used to track unmatched `[` brackets. + +### Loop +We iterate over each character in the string: + +1. **If it's `[`**: + - Push it onto the stack. + +2. **If it's `]`**: + - **If the stack is not empty**: + - Pop the stack (indicating a match). + - **If the stack is empty**: + - Increment `ans` (indicating an unmatched `]`). + +### Return +Finally, we return the minimum number of swaps needed, calculated as: +\[ +\text{swaps} = \frac{(\text{ans} + 1)}{2} +\] diff --git a/solutions/day08/solution_python.py b/solutions/day08/solution_python.py new file mode 100644 index 0000000..b4b4d4e --- /dev/null +++ b/solutions/day08/solution_python.py @@ -0,0 +1,15 @@ +class Solution: + def minSwaps(self, s: str) -> int: + stack = [] + ans = 0 + + for char in s: + if char == '[': + stack.append(char) + else: # char == ']' + if stack: + stack.pop() + else: + ans += 1 + + return (ans + 1) // 2