Expression contains redundant bracket or not
Pattern: Balanced brackets
Push every character except ). On ), pop back to the matching ( and note whether an operator was inside. A pair with no operator inside, such as (a) or ((a+b)), is redundant.
The problem
Given a valid expression with letters, + - * / and brackets, return whether it has a redundant pair: brackets that
wrap a single value or another pair, so removing them changes nothing. "((a+b))" is true; "(a+(b)/c)" is true because
of (b); "(a+b*(c-d))" is false.
Think first
- What does a useful pair of brackets always contain?
- When ) arrives, what is between it and its (?
- Does an operator inside a nested pair count?
Hints
Brute force, and why it fails
For each pair, scan the text between its brackets for an operator outside inner brackets: O(n²).
The key insight
Popping each pair as it closes leaves only the current level's characters between ( and ), so one look finds an operator or not.
Dry run
s = "((a+b))". Push ( ( a + b.
The plan
for c in s:
if c != ')': push c; continue
hasOp = false
while top != '(': if pop() is an operator: hasOp = true
pop the '('
if not hasOp: return true
return false
Complexity
- Time
O(n)- Space
O(n)
Each character is pushed and popped once.
Edge cases
- No brackets: false.
(a): true.- Brackets around the whole expression, such as
(a+b): not redundant by this rule.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean checkRedundancy(String s) {
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c != ')') { st.push(c); continue; }
boolean hasOperator = false;
while (st.peek() != '(') { // look at everything inside this pair
char x = st.pop();
if (x == '+' || x == '-' || x == '*' || x == '/') hasOperator = true;
}
st.pop(); // remove the '('
if (!hasOperator) return true; // brackets around nothing, or around a single value
}
return false;
}
}C++
class Solution {
public:
bool checkRedundancy(string s) {
stack<char> st;
for (char c : s) {
if (c != ')') { st.push(c); continue; }
bool hasOperator = false;
while (st.top() != '(') { // look at everything inside this pair
char x = st.top();
st.pop();
if (x == '+' || x == '-' || x == '*' || x == '/') hasOperator = true;
}
st.pop(); // remove the '('
if (!hasOperator) return true; // brackets around nothing, or around a single value
}
return false;
}
};Python
class Solution:
def checkRedundancy(self, s: str) -> bool:
st = []
for c in s:
if c != ")":
st.append(c)
continue
has_operator = False
while st[-1] != "(": # look at everything inside this pair
if st.pop() in "+-*/":
has_operator = True
st.pop() # remove the '('
if not has_operator:
return True # brackets around nothing, or around a single value
return FalseCommon mistakes
- Counting operators in nested pairs, which hides
((a+b)). - Forgetting to pop the
(.