Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Validating Balanced Brackets

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Validating Balanced Brackets. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

AI-first Technology's prompt editor must reject prompts containing incorrectly matched brackets before they are sent for processing. Given a string representing a prompt, determine whether every bracket is correctly opened, closed, and nested.

The supported bracket pairs are (), [], and {}. All other characters, including letters, digits, whitespace, and operators, must be ignored. A prompt is balanced only when each closing bracket matches the most recently opened bracket and no brackets remain unclosed.

Formal Specification

Implement is_balanced(expression).

  • Input: expression, a string of length n containing printable characters.
  • Output: Return True if all brackets are balanced and properly nested; otherwise return False.

Constraints

  • 0 <= len(expression) <= 10^5
  • The string may contain any printable ASCII characters
  • Only (), [], and {} are bracket characters
  • An empty string is considered balanced

Function Signature

def is_balanced(expression):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output