Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved daily leetcode problem #8 using python. #53

Merged
merged 2 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions solutions/day08/README
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}
\]
15 changes: 15 additions & 0 deletions solutions/day08/solution_python.py
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