Maximum Nesting Depth of the Parentheses - Leetcode 1614 - Python

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

Key Takeaways

The video solves the Leetcode problem 1614, Maximum Nesting Depth of the Parentheses, using a simple iterative approach in Python, without needing a stack or any additional data structure, achieving constant space complexity.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum nesting depth of parentheses we're given a string and basically a really really long description here ain't nobody got time to read all of that so I'm going to quickly summarize it they Define something called a valid parentheses string which is pretty much what you would expect when you have parentheses You' expect every open parentheses to be matched with a closing parentheses now we could technically also just have like an empty string or we could have a string with a single character so they say these empty strings or just a single character are valid they don't explicitly tell you this here but if we had multiple characters a b c we intuitively know that this is valid now the way they told us that this is also valid is with a kind of an over complicated definition but I guess this is very mathematical in nature what they said is any valid strings concatenated with each other are also valid so when you think about it each of these is an individual valid string so if you add them all together they are also valid if you take any valid string like this and wrap it in parentheses it is also now valid now what we want to do is calculate the depth of this valid parentheses string we don't have to worry about validating it it's not like the problem leak code 20 valid parentheses it's actually much more simple than that because first of all we're only dealing with this type of parentheses we don't have brackets we don't have curly braces this is going to be very simple for us now in in terms of what the depth is again it's pretty much what you would expect so if we have like a string like this with just one open and one closing parentheses it has a depth of one if you have a string like this where open and close open and close this also has a depth of one you can think about how nested is the parentheses now if we were to move these such that it's kind of double nested this has a depth of two so just by kind of what I showed you right now you might have recogniz the pattern you might have recognized what the solution to this problem is basically how many consecutive open parentheses do we have before they are closed like if we go through this string from left to right we see open parentheses okay that's a one okay two open parentheses we have now two open parentheses that haven't been closed now we might see some contents in between here we might have seen some contents over here or here it really doesn't matter ignore every character that is not an open parentheses or is not a closing parenthesis at this point we see that okay this is a closing one so we had two now we decrement that by one now we see another one and it's a closing parentheses decrement that by one and we should always end up with zero because we're pretty much told that this is always going to be valid so again we're not worried about validating this we are just worried about as we scan from left to right we want to know what was the maximum number number of open parentheses that we were able to find before they ended up being closed quickly looking at this first example I've just gone ahead and blown it up but it's kind of meant to confuse you just like all of this it's more simple than it seems we see open parentheses here okay our count is one we see some characters we ignore them who cares what they are we already assume everything here is technically valid first of all this is valid so then we see another open parentheses okay now our count is at two we see some characters closing parentheses so count goes down to one and then we see an open parentheses and then another open parentheses so then our count goes up to three basically that means that at this point the depth of the nesting is three and that makes sense because these two parentheses kind of negate each other so we had one we're in one layer of nesting then we see two open parentheses so this is three layers in and then of course it gets closed by this one so then our count goes down to two closed again down to one closed again down to zero but the maximum among everything we saw was definitely three so three is what we return and you can see that's the correct return value here so straightforward problem we can just iterate in O of n time iterating over the string don't need a stack don't need any data structure this is constant space let's code it up so first I'm just going to initialize a couple variables one is going to be the result that's going to be what we end up returning that's going to store the max depth now we're going to have another variable we could call it Cur or count or whatever it's going to be the current depth of where we're at in the input string so the way I'm going to iterate over the string is actually very simple just for every character in the string we don't need to worry about the index of any of those characters we only care about two specific cases is it the open parentheses or is it the closing parentheses so like this and you can probably guess what I'm going to put in each each of these if it's open we increment the count by one if it's closing we decrement the count by one now regardless of what we ended up with we want to know among every position in the string which one led us to the maximum and what was that maximum we don't really care about the position but what the maximum depth was so down here we can always update the result like this always taking the max of itself with whatever the current depth happens to be and so this is the whole code let's run it to make sure that works as you can see it does and it is pretty efficient if you're preparing for coding interviews check out NE code. 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/maximum-nesting-depth-of-the-parentheses/description/ 0:00 - Read the problem 0:22 - Drawing Explanation 4:24 - Coding Explanation leetcode 1614 #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 Maximum Nesting Depth of the Parentheses problem using a simple iterative approach in Python, without needing additional data structures. This problem is relevant for coding interviews and demonstrates how to analyze algorithmic complexity and implement efficient solutions.

Key Takeaways
  1. Initialize variables to track the maximum depth and current depth
  2. Iterate over the input string, incrementing or decrementing the current depth based on open or close parentheses
  3. Update the maximum depth at each position in the string
  4. Return the maximum depth found
💡 The problem can be solved using a simple iterative approach, avoiding unnecessary complexity and achieving constant space complexity.

Related Reads

📰
The Minecraft anvil is a tree-cost optimization problem in disguise
Optimize tree costs in Minecraft using graph theory and algorithms, just like the anvil repair system
Dev.to · Mark
📰
KMP Algorithm (Knuth-Morris-Pratt): The Smart Way to Perform String Matching in O(N)
Learn the KMP algorithm for efficient string matching in O(N) time complexity and improve your coding skills
Dev.to · Jaspreet singh
📰
Every Backtracking Problem Is the Same Three Lines. I Just Couldn't See the Tree.
Master backtracking problems with a simple three-line approach to improve problem-solving skills in coding interviews and challenges
Dev.to · Alex Mateo
📰
DSA From Zero to Hero #3: Sliding Window (Fixed Size) Explained With a Java Example
Learn to solve subarray problems efficiently using the sliding window technique, a crucial skill for software engineers and data scientists
Medium · Programming

Chapters (3)

Read the problem
0:22 Drawing Explanation
4:24 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →