Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Validating Balanced Brackets
00:00
5 left

Validating Balanced Brackets

EasyPython

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):
Interviewer

Your question is Validating Balanced Brackets. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.