Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Balanced Parentheses With Stack

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

Your question is Balanced Parentheses With Stack. 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

ServiceNow Automated Test Framework (ATF) expressions may contain ordinary characters and parentheses. Write a function that determines whether every opening parenthesis has a matching closing parenthesis in the correct order.

Use a stack to track unmatched opening parentheses. Ignore all characters other than ( and ).

Formal Specification

Implement is_balanced_parentheses(s), where s is a string. Return True if the parentheses are balanced and properly nested, and False otherwise.

A string is balanced when:

  1. Each ( is eventually matched by a ).
  2. A ) cannot appear before its matching (.
  3. No unmatched ( remain after processing the string.

Example 1:

Input: s = "gsft.next() && (current.active)"
Output: True

The parentheses close in the reverse order in which they open.

Example 2:

Input: s = "(current.active && (current.priority == 1)"
Output: False

One opening parenthesis has no matching closing parenthesis.

Example 3:

Input: s = ")current.active("
Output: False

The first closing parenthesis has no preceding opening parenthesis.

Constraints

  • 0 <= len(s) <= 10^5
  • s contains printable ASCII characters
  • Only '(' and ')' affect the result
  • Return a Boolean value

Function Signature

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