potd - Minimum Add to Make Parentheses Valid #24
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
In this contribution, I solved the problem of Minimum Add to Make Parentheses Valid.
Problem statement:
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
Return the minimum number of moves required to make s valid.
Fixes:
My code beats 100% in time complexity.
Type of Change
How to Test
Run the code for the different test cases
Checklist
Additional Notes
Alternative solution to the problem is using a stack which increases the space complexity to O(n) . When we encounter an open bracket, we push it onto the stack. When we encounter a close bracket we pop the open if the stack is not empty. But if its empty we increment our moves. In the end after iterating though the string if some open brackets still remain on the stack we add that count to moves. That gives our final answer