Skip to content

Commit

Permalink
Merge pull request #53 from Rohit-Sharma-RS/main
Browse files Browse the repository at this point in the history
Solved daily leetcode problem #8 using python.
  • Loading branch information
arya2004 authored Oct 8, 2024
2 parents a5942fa + e499aeb commit 46be730
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
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

0 comments on commit 46be730

Please sign in to comment.