Balanced brackets

strings

Balanced brackets

Salesforce Python Interview Question

Salesforce lets admins write formulas with round, square and curly brackets. Before saving a formula, the editor checks that every bracket is closed by the right kind of bracket, in the right order.

Write a function is_balanced(formula) that returns True if the brackets in the string are balanced and False otherwise. The string contains only the characters ( ) [ ] { }.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

formula = "({[]})()"

Output

True

Example 2

Input

formula = "([)]"

Output

False

Explanation

In the first example, every opening bracket is closed by its matching bracket, and inner pairs close before outer ones. In the second example, the square bracket is closed by a round bracket, so the formula is not balanced.

Submit also runs 5 hidden test cases that check edge cases.