Minimum Add to Make Parentheses Valid - Leetcode 921 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

The video solves the LeetCode problem 'Minimum Add to Make Parentheses Valid' using a single variable to keep track of open parentheses, achieving constant space and linear time complexity. The problem is solved by iterating through the string and incrementing or decrementing the open count based on the type of parentheses encountered.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum add to make parentheses valid so they give us kind of an interesting way to define parentheses they basically say an empty string is valid and then if you take that empty string and then you wrap it in parentheses it is also valid and if you take two strings that are valid like these two and you concatenate them together that's also valid and now we could kind of keep doing that we could either wrap these or add additional strings that are also valid and just concatenate them so basically what that means is every open parentheses has to have a matching closing parentheses and the order matters the closing one has to come after the open one now if you're familiar with this kind of concept you probably know that the data structure that's commonly used for these types of scenarios is the stack let's see if that's actually going to be useful for us here or not what we want is given some string as suppose something like this we want to know what is the minimum number of parentheses we have to add to make this string valid we don't actually want to build the string just give me the number we only need a single one and that is going to look like this just add it at the beginning because as you can see if we were scanning from left to right we could look at this value and say okay we have an open parentheses we need to remembered that in some kind of way commonly you can use a stack I'll kind of draw that down here we have an open parentheses and then we come to a closing parentheses and what we usually do with that is this should close the previous open parentheses so anytime we see a closing parentheses it's actually not going to be pushed to the stack the stack is mainly going to keep track of the open parentheses so with this one we can actually pop it the fact that our stack is empty right now indicates that so far the string is balanced now when we get to the last parentheses open we notice that our stack is empty there is isn't a matching open parentheses so if we were maintaining our result the number of parentheses we have to add initially it would be zero well now clearly we would increment that guy by one so it would be one by the end of the string again this closing parenthese would not be added the fact that we incremented our result should assume that it was added in a position that makes this valid anyway so while this solution will definitely work is it actually necessary for us to use a stack let's consider a different example the second example down there has three consecutive open parentheses this might make you think you need a stack add those three open parentheses onto the stack because the idea is that we could have some closing parentheses that come after and each closing parentheses would end up popping one of these guys so we might have a chain of these we might need to remember that we have three open parentheses that's why we have a stack to have multiple characters added to it but that's actually not necessary why not just have a single variable which says open right the count of open parentheses initially it's zero as we scan through this we'll increment it every time we see an open one and it'll be set to three by the end if we don't see any closing parentheses well we're going to say that we have three open parentheses that were never closed so our result is going to be three suppose we did have like let's say one closing parentheses well then we would have decremented this count down to two suppose we had two more we would have decremented this guy down to zero maybe if we had one more a fourth one we would add that see that our count is already zero we don't have any open parentheses so this is kind of similar to the stack when our stack was empty remember what we did we took that result which is zero and we will increment it by one so now suppose we had like a couple more open parentheses one two we're going to end up incrementing this count to two and so now at the end what would we return remember this fourth parentheses we actually did close it when we incremented the result so this is like the only parentheses we added that open parentheses and then we ended with a surplus of open parentheses two of them so what should we return probably the sum of these two which would be three in this case that means that this is the one that we added and we would add two more closing parentheses here this actually indicates the number of closing parentheses that we have to add the result indicates the number of open parentheses that we did add and you accumulate them you get the result now this is better than the stack solution because because we have a variable rather than a data structure so constant space and linear time because we're just scanning through the input before I jump into coding this I want to quickly mention you might start to think well that really old classic leak code problem I think it's leak code 20 validate parenthesis don't ask me how I remember that but that one you can't solve without a stack you can't just keep track of the variables and remember that problem actually had three types of parentheses these square and then the curly ones that I'm bad at drawing they had three different types of parentheses that's why you could not just count the number of open parentheses in this problem because if you did let's say you had something like this and then this and then this and then you come across a closing parentheses if you just had the count you have two open parentheses and now one closing parentheses you might think that this can close that but no it doesn't work like that we have to close the curly ones first so not only do we have to keep the count of them but we have to maintain the order of them as well and that's why a stack is necessary for that problem but not for this one okay now let's code it up we'll keep it nice and short I'm going to keep track of the open count since this is a keyword I think it's like a built-in function I'm going to call it open count like that and what we're going to end up returning I'll have my result here as well this is kind of the good part of doing a drawing explanation because now we know exactly what we're going to do return the result as well as the open count then in between let's go through every character there's only two cases either the character is open or it is a closing parentheses if it's open that's the simple case all you got to do is take the open count and increment it by one in the other case we will take the open count and decrement it by one now what if it was already zero well maybe we should set it to the max of itself well itself minus one and zero because maybe decrementing it by one will make it negative so this is one way to handle this you could also do that with an if statement and then um maybe before we decrement the count we check if the open count is already equal to zero then we shouldn't decrement it and that's what this will do it won't really change the open count value but if it's zero and we just got a closing parentheses that means we don't have a matching open parentheses and therefore we're going to increment the result by one so this is the entire solution I'll run it just to show you that it works I promise you it's more efficient than this is indicating but but I wanted to code it a slightly different way if you're kind of a beginner or Noob it might make more sense to see the code written like this where we just decrement the count and then we check if it went negative if it's less than zero now what should we do probably reset it back to zero and increment the result by one because we need a matching open parentheses so this will also work and for whatever reason this time it's more efficient if you found this helpful check out n code. for a lot more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 5:34 - Coding Explanation leetcode 921 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

The video teaches how to solve the LeetCode problem 'Minimum Add to Make Parentheses Valid' using a single variable to keep track of open parentheses, achieving constant space and linear time complexity. This problem is relevant to system design and algorithmic thinking.

Key Takeaways
  1. Initialize a variable to keep track of open parentheses
  2. Iterate through the string and increment or decrement the open count based on the type of parentheses encountered
  3. Handle cases where the open count becomes negative
  4. Return the result and the open count
💡 Using a single variable to keep track of open parentheses can achieve constant space and linear time complexity for this problem, making it more efficient than using a stack.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
0:30 Drawing Explanation
5:34 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →