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.
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 ).
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:
( is eventually matched by a ).) cannot appear before its matching (.( 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.
def is_balanced_parentheses(s):