-
Notifications
You must be signed in to change notification settings - Fork 48
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #53 from Rohit-Sharma-RS/main
Solved daily leetcode problem #8 using python.
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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} | ||
\] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |