Skip to content

Commit 8e70e2e

Browse files
zain-cspre-commit-ci[bot]MaximSmolskiy
authored
Add type hints and improve generate_parentheses_iterative (#14324)
* Add type hints and improve code quality for generate_parentheses_iterative * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix line length issue * Update generate_parentheses_iterative.py * Update generate_parentheses_iterative.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent f527d43 commit 8e70e2e

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

backtracking/generate_parentheses_iterative.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
def generate_parentheses_iterative(length: int) -> list:
1+
def generate_parentheses_iterative(length: int) -> list[str]:
22
"""
33
Generate all valid combinations of parentheses (Iterative Approach).
44
55
The algorithm works as follows:
66
1. Initialize an empty list to store the combinations.
77
2. Initialize a stack to keep track of partial combinations.
8-
3. Start with empty string and push it onstack along with the counts of '(' and ')'.
8+
3. Start with empty string and push it on stack along with
9+
the counts of '(' and ')'.
910
4. While the stack is not empty:
1011
a. Pop a partial combination and its open and close counts from the stack.
1112
b. If the combination length is equal to 2*length, add it to the result.
@@ -34,8 +35,11 @@ def generate_parentheses_iterative(length: int) -> list:
3435
>>> generate_parentheses_iterative(0)
3536
['']
3637
"""
37-
result = []
38-
stack = []
38+
if length == 0:
39+
return [""]
40+
41+
result: list[str] = []
42+
stack: list[tuple[str, int, int]] = []
3943

4044
# Each element in stack is a tuple (current_combination, open_count, close_count)
4145
stack.append(("", 0, 0))
@@ -45,6 +49,7 @@ def generate_parentheses_iterative(length: int) -> list:
4549

4650
if len(current_combination) == 2 * length:
4751
result.append(current_combination)
52+
continue
4853

4954
if open_count < length:
5055
stack.append((current_combination + "(", open_count + 1, close_count))

0 commit comments

Comments
 (0)