0% found this document useful (0 votes)
10 views1 page

Validating Parentheses with Stack

The document describes a problem of validating parentheses in a string using a stack data structure. It outlines the conditions for a valid string and provides a sample test case with its expected output. The solution approach and code are presented, along with the time and space complexity of the algorithm.

Uploaded by

yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

Validating Parentheses with Stack

The document describes a problem of validating parentheses in a string using a stack data structure. It outlines the conditions for a valid string and provides a sample test case with its expected output. The solution approach and code are presented, along with the time and space complexity of the algorithm.

Uploaded by

yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Valid Parentheses

Description
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open
brackets must be closed in the correct order.

Sample Test Case


Input: s = "()[]{}"
Output: true

Solution Approach
We use a stack to keep track of opening brackets. For each closing bracket, check if the top of the
stack matches. If not, return false.

Solution Code
class Solution:
def isValid(self, s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top = [Link]() if stack else '#'
if mapping[char] != top:
return False
else:
[Link](char)
return not stack

Time Complexity
Time Complexity: O(n), Space Complexity: O(n)

You might also like