From 342c6d49e0e8e3ddabb5c6b6046f1a571405d7bf Mon Sep 17 00:00:00 2001 From: Rohit Sharma Date: Tue, 8 Oct 2024 13:32:45 +0530 Subject: [PATCH 1/2] Day 8 python solution shared --- solutions/day08/solution_python.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 solutions/day08/solution_python.py 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 From e499aeb9bbf4588cc8c3441880ef36191d2adce9 Mon Sep 17 00:00:00 2001 From: Rohit Sharma Date: Tue, 8 Oct 2024 13:39:09 +0530 Subject: [PATCH 2/2] added readme --- solutions/day08/README | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 solutions/day08/README 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} +\]