Skip to content

Commit bd86731

Browse files
Optimized BalancedBrackets implementation with edge cases
1 parent 883a050 commit bd86731

File tree

1 file changed

+52
-59
lines changed

1 file changed

+52
-59
lines changed
Lines changed: 52 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,73 @@
11
package com.thealgorithms.stacks;
22

3-
import java.util.Stack;
3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
45

56
/**
6-
* The nested brackets problem is a problem that determines if a sequence of
7-
* brackets are properly nested. A sequence of brackets s is considered properly
8-
* nested if any of the following conditions are true: - s is empty - s has the
9-
* form (U) or [U] or {U} where U is a properly nested string - s has the form
10-
* VW where V and W are properly nested strings For example, the string
11-
* "()()[()]" is properly nested but "[(()]" is not. The function called
12-
* is_balanced takes as input a string S which is a sequence of brackets and
13-
* returns true if S is nested and false otherwise.
7+
* Optimized and robust Balanced Parenthesis (Valid Brackets) checker.
148
*
15-
* @author akshay sharma
16-
* @author <a href="https://github.com/khalil2535">khalil2535<a>
17-
* @author shellhub
9+
* Supports: (), [], {}, <>
10+
* Rules:
11+
* - Returns true if brackets are properly nested and matched.
12+
* - Returns false for any non-bracket character.
13+
* - Empty string is balanced.
14+
* - Null input throws IllegalArgumentException.
15+
*
16+
* Time complexity: O(n)
17+
* Space complexity: O(n) in worst case (stack contains all opening brackets).
1818
*/
19-
final class BalancedBrackets {
19+
public final class BalancedBrackets {
20+
2021
private BalancedBrackets() {
22+
// Utility class
2123
}
2224

2325
/**
24-
* Check if {@code leftBracket} and {@code rightBracket} is paired or not
25-
*
26-
* @param leftBracket left bracket
27-
* @param rightBracket right bracket
28-
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is
29-
* paired, otherwise {@code false}
26+
* Returns true if {@code opening} and {@code closing} are matching bracket pair.
3027
*/
31-
public static boolean isPaired(char leftBracket, char rightBracket) {
32-
char[][] pairedBrackets = {
33-
{'(', ')'},
34-
{'[', ']'},
35-
{'{', '}'},
36-
{'<', '>'},
37-
};
38-
for (char[] pairedBracket : pairedBrackets) {
39-
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
40-
return true;
41-
}
42-
}
43-
return false;
28+
public static boolean isPaired(char opening, char closing) {
29+
return (opening == '(' && closing == ')')
30+
|| (opening == '[' && closing == ']')
31+
|| (opening == '{' && closing == '}')
32+
|| (opening == '<' && closing == '>');
4433
}
4534

4635
/**
47-
* Check if {@code brackets} is balanced
36+
* Checks if the input string has balanced brackets.
4837
*
49-
* @param brackets the brackets
50-
* @return {@code true} if {@code brackets} is balanced, otherwise
51-
* {@code false}
38+
* @throws IllegalArgumentException when input is null
5239
*/
53-
public static boolean isBalanced(String brackets) {
54-
if (brackets == null) {
55-
throw new IllegalArgumentException("brackets is null");
40+
public static boolean isBalanced(String input) {
41+
if (input == null) {
42+
throw new IllegalArgumentException("Input cannot be null");
43+
}
44+
45+
if (input.isEmpty()) {
46+
return true;
5647
}
57-
Stack<Character> bracketsStack = new Stack<>();
58-
for (char bracket : brackets.toCharArray()) {
59-
switch (bracket) {
60-
case '(':
61-
case '[':
62-
case '<':
63-
case '{':
64-
bracketsStack.push(bracket);
65-
break;
66-
case ')':
67-
case ']':
68-
case '>':
69-
case '}':
70-
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
71-
return false;
48+
49+
// Odd-length strings cannot be fully balanced
50+
if ((input.length() & 1) == 1) {
51+
return false;
52+
}
53+
54+
Deque<Character> stack = new ArrayDeque<>();
55+
56+
for (char c : input.toCharArray()) {
57+
switch (c) {
58+
case '(', '[', '{', '<' -> stack.push(c);
59+
case ')', ']', '}', '>' -> {
60+
if (stack.isEmpty() || !isPaired(stack.pop(), c)) {
61+
return false;
62+
}
63+
}
64+
default -> {
65+
// Any non-bracket character makes string invalid
66+
return false;
7267
}
73-
break;
74-
default:
75-
return false;
7668
}
7769
}
78-
return bracketsStack.isEmpty();
70+
71+
return stack.isEmpty();
7972
}
80-
}
73+
}

0 commit comments

Comments
 (0)