710078. Expression contains redundant bracket or not

Medium

Expression contains redundant bracket or not

Summary

Given a string expression, determine whether it contains any redundant brackets or not. A bracket is considered redundant if there is an unmatched opening or closing bracket. This problem involves working with strings and using stack-based approach to solve the problem.

Detailed Explanation

To solve this problem, we can use a stack data structure. The idea is to iterate through the string expression from left to right. For every opening bracket, push it onto the stack. For every closing bracket, check if the top of the stack contains an opening bracket that matches the current closing bracket. If there's no match or the stack is empty (which means there are unmatched opening brackets), return false.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through the string expression from left to right.
  3. For every opening bracket, push it onto the stack.
  4. For every closing bracket:
    • Check if the top of the stack contains an opening bracket that matches the current closing bracket.
    • If there's no match or the stack is empty (which means there are unmatched opening brackets), return false.
  5. After iterating through the entire expression, check if the stack is empty. If it is not empty, there are unmatched opening brackets and the function should return false.

Time complexity: O(n) where n is the length of the input string. Space complexity: O(n) for storing the stack.

  +---+---+---+---+---+
  |   |   |   |   |
  +---+---+---+---+---+
  ^
  Stack

Optimized Solutions

Java

View on GeeksforGeeks
public boolean hasRedundantBrackets(String expression) {
    Stack<Character> stack = new Stack<>();
    for (char c : expression.toCharArray()) {
        if (c == '(') {
            stack.push(c);
        } else if (c == ')') {
            if (stack.isEmpty() || stack.pop() != '(') {
                return true;
            }
        }
    }
    return stack.isEmpty();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.