Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Parentheses Validation With Nesting

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

Your question is Parentheses Validation With Nesting. 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

Parsons configuration text may contain parentheses inside labels, expressions, or annotations. Implement a validator that determines whether every opening parenthesis has a correctly ordered closing parenthesis, allowing arbitrary nesting.

Characters other than ( and ) must be ignored. A string is valid when scanning from left to right never encounters a closing parenthesis without a matching opening parenthesis, and all opening parentheses are closed by the end of the string.

Formal Specification

Implement is_valid_parentheses(text), which accepts a string text and returns a Boolean:

  • Return True if the parentheses are balanced and correctly nested.
  • Return False otherwise.
  • Ignore all characters except ( and ).

Constraints

  • 0 <= len(text) <= 10^5
  • text contains printable characters
  • Only '(' and ')' affect validity
  • The function should stop early when an invalid closing parenthesis is found

Function Signature

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