Quick Overview

This question evaluates proficiency in stack-based parsing, string manipulation, and algorithmic reasoning for correctly matching and nesting multiple bracket types, and belongs to the Coding & Algorithms domain.

Check balanced parentheses with multiple bracket types

Company: Snowflake

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

Given a string containing only parentheses '()', determine whether it is balanced. Follow-up: extend the solution to also support '[]' and '{}' with correct nesting and ordering. Describe the algorithm, the data structures you would use (e.g., a stack), time and space complexity, and how you would handle edge cases such as empty strings or unexpected characters.

Quick Answer: This question evaluates proficiency in stack-based parsing, string manipulation, and algorithmic reasoning for correctly matching and nesting multiple bracket types, and belongs to the Coding & Algorithms domain.

Given a string `s` containing bracket characters, determine whether the brackets are balanced. A string is balanced when every opening bracket has a corresponding closing bracket of the same type, brackets are closed in the correct (LIFO) order, and there are no stray closing brackets. Start with only round parentheses `()`, then extend the same approach to also support square `[]` and curly `{}` brackets with correct nesting and ordering. For this challenge, treat ANY character that is not one of the six bracket characters `()[]{}` as invalid input, so the string is considered NOT balanced if it contains one. The empty string is considered balanced. Return `true` if the string is balanced, otherwise `false`. Examples: - `"()"` -> true - `"()[]{}"` -> true - `"(]"` -> false (mismatched types) - `"([)]"` -> false (wrong closing order) - `"{[]}"` -> true (correctly nested) - `""` -> true (empty) - `"a(b)c"` -> false (unexpected character)

Constraints

  • 0 <= len(s) <= 10^4
  • s may contain the characters ()[]{} and possibly other characters
  • Any character outside the six bracket characters makes the string invalid (not balanced)
  • The empty string is balanced

Examples

Input: ("()",)

Expected Output: True

Explanation: A single matched pair of round parentheses is balanced.

Input: ("()[]{}",)

Expected Output: True

Explanation: Three independent matched pairs of different types, each opened and closed correctly.

Hints

  1. Use a stack: push every opening bracket as you scan left to right.
  2. When you hit a closing bracket, the top of the stack must be the matching opening bracket of the same type; otherwise the string is unbalanced.
  3. After scanning the whole string, the stack must be empty — leftover opening brackets mean it is unbalanced. Also reject any character that is not one of ()[]{}.

Loading coding console...