MediumNo. 2116

Check if a Parentheses String Can Be Valid — LeetCode 2116 Python Solution

Pattern
Stack
Topics
Stack, Greedy, String
Reading time
4 min

The problem

A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is ().

Example

Input
s = "))()))", locked = "010100"
Output
true
Explanation
locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].

Python solution

PythonSolution
class Solution:
    def canBeValid(self, s: str, locked: str) -> bool:
        n = len(s)
        if n & 1:
            return False
        x = 0
        for i in range(n):
            if s[i] == '(' or locked[i] == '0':
                x += 1
            elif x:
                x -= 1
            else:
                return False
        x = 0
        for i in range(n - 1, -1, -1):
            if s[i] == ')' or locked[i] == '0':
                x += 1
            elif x:
                x -= 1
            else:
                return False
        return True

Complexity

Time
O(n)where n is the length of the string s
Space · auxiliary
O(1)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2116. Check if a Parentheses String Can Be Valid is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2116. Check if a Parentheses String Can Be Valid?

LeetCode 2116. Check if a Parentheses String Can Be Valid is rated Medium on LeetCode.

What is the time complexity of LeetCode 2116. Check if a Parentheses String Can Be Valid?

The Python solution on this page runs in O(n), where n is the length of the string s.

What is the space complexity of LeetCode 2116. Check if a Parentheses String Can Be Valid?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2116. Check if a Parentheses String Can Be Valid cover?

LeetCode 2116. Check if a Parentheses String Can Be Valid is tagged Stack, Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.