Clear Digits - Leetcode 3174 - Python

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

Key Takeaways

The video demonstrates a solution to the LeetCode problem 3174, 'Clear Digits', using Python and a stack-based approach, with a focus on systems design and string processing.

Full Transcript

Hey everyone, welcome back and let's write some more neat code today. So today let's solve the problem clear digits. In this problem we're given an input string S and what we want to do is remove every single digit from the input string and every time we end up removing a digit, we want to remove the closest non-digit character to the left of it. They also tell us that we want to do so by deleting the first digit. So in this example over here, we have two digits. The first one is three so they tell us that that's the one that we would want to delete, but I can tell you that it actually doesn't matter which order we do these. Given the constraints and the operation that we're doing, it's going to end up the same either way. So take a look at this example over here. We do not have any digits so actually there's nothing for us to remove. So we would just return the input string itself. In this second example though, we would go through the input string. Anytime we see a digit, I guess you could say that we would skip that digit. So in a sense you could say we're going character building the output. We see a character, we add it. We see a character, we add it. We see a digit, we skip that digit, but not only that, we would then remove the previous character that we've already actually added to the string. So we do not then have the B. The reason we add the B first is because we have no idea what's coming up ahead since we're going through this from left to right. Next, we see another character which happens to be a digit. It's four. We would skip it and we would also remove the previous character that already added to the input string or to the output string rather. So then we would end up with just an empty string. And so that is the correct output for this example here. Now you might be wondering what would happen if we had a case like this. Like maybe we have a character and then we have two digits that come after it. They don't really make that super clear with the problem description, but at the bottom they tell us that the inputs are generated such that it's always possible to delete all the digits. So I take that to mean that for every digit there's always going to be enough preceding characters so that anytime we do remove a digit, we are going to be removing a character. So I don't think an example like this is actually possible. So we don't really have to worry about that. Now if you are noticing in the dry run that I did earlier where we had a or rather C B 3 4 and we were adding characters to the string and then removing them from the end of the string, that's pretty much like a stack. So that is one valid way to solve this problem. Rather than creating a string, we actually create an array of characters which is pretty much a stack and then at the end we could just join those characters together to actually build the output string. Another solution, the first one that I actually coded up was this, just going through the input in reverse order because then anytime we see a character, we could yes skip that character, but instead of removing the upcoming non-digit characters immediately, we could just keep track of like a count, like our delete count and so after we see this, our delete count would be one. When we see this, our delete count would then be incremented to two. And then when we see a character, since our count is positive, we know that we can skip it and then we could just decrement the count and take it down to be one. Now we see another character, so we skip it, we take our count down to be zero. Now imagine we had additional characters here. Maybe we have an A. Now since our count is actually zero, we are not going to delete this character. So this one would actually stay and so we would add it to whatever data structure that we want, probably an array, and then I continue. I think this is also a valid way to do it. Since the solution is easy enough to code up both ways, I guess I'll show you the solution for both. It's going to be a linear time solution. In terms of space, since we are kind of using an intermediate array rather than building like the output string, I guess the output, like the extra space could be considered linear, but this is pretty much what we're returning. The reason we're putting it in the form of an array rather than a string is because in most languages, strings are immutable. So if we were to be updating that string, it would be less efficient in terms of time. Anyways, let's code it up now. So I'll show you the reverse order solution first. So what we're going to have is our result. It's going to be an array and we're going to have that delete count that I was talking about. Initially it'll be zero. We're going to go through the input in reverse order. So we can do this in Python, just reverse this iterator. And what we want to check is if the character at index I is a digit and thankfully that's actually a built-in function. So we could do this, S at index I {dot} is digit. If it is a digit, we will skip that character, but we want to increment our delete count. Now there's a couple other cases. One is if it's not a digit, but our delete count is positive. So this. Well in that case we also want to skip that character, but this time we want to actually decrement our delete count cuz we're basically deleting a character. The last case is going to be it wasn't a digit and our delete count was zero. So thus we can actually take the character and add it to our result. Notice that we are going through this in reverse order. So the result will also be built in reverse order. That's kind of a negative of the solution. So when you return, normally we could do something like this in Python, use the empty string as the delimiter and then join all the substrings together like this, but we actually want to go through the strings in reverse order. So we're actually going to reverse that like this in Python. So I'll run this to show you that it works and you can see that over here. If you didn't want to use this built-in function, it's actually pretty easy to implement it ourselves. So we could do something like this, is digit, passing in a character and what we would want is to get the ASCII value of that character which we can do like this in Python. We want to make sure it's in between the digit zero and the digit nine. Those are going to be in consecutive in ASCII. So whatever ASCII value belongs to zero, the one for one is going to be one more than that. The one for two is going to be one more than that all the way up until nine. So we can do something like this, take the ASCII value of nine, make sure that this is less than or equal to that. And in Python you can actually do inequalities like this, making sure that this is also greater than or equal to that. So we can just return the result of this boolean or this expression rather. So I'll run this as well. Well actually I should probably change this over here. So let me instead pass the character in to that function that we just created over here. So now let's run it. And here you can see that this works as well. I think it's about as efficient. It's just that on LeetCode like these kind of vary between whether it's 1 millisecond or 3. I think that's just random. If we wanted to treat the result more as a stack, what we could do is this. I guess we could keep this function, but then we could go through the string from left to right just like this and assuming we're building it from left to right, we probably wouldn't need to reverse the result over here. So we could get rid of that. But then in here, we could do something like this. If is digit, then we assume the stack is non-empty, the result is non-empty. So we could just pop from it. Otherwise, it's a non-digit character. So we could just add it to the result like this. Running this code, you can see here that it also works and I think it's about as efficient. If you found this helpful, check out neatcode.io 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/clear-digits/ 0:00 - Read the problem 0:30 - Drawing Explanation 4:10 - Coding Explanation leetcode 3174 #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 3174, 'Clear Digits', using a stack-based approach and Python, with a focus on systems design and string processing. The solution involves reversing the input string, checking for digits, and decrementing a delete count. The video also provides an optimized solution that builds the stack from left to right, eliminating the need to reverse the result.

Key Takeaways
  1. Create an array of characters to act as a stack
  2. Join characters together to build the output string
  3. Go through the input in reverse order
  4. Skip digits and decrement the count
  5. Add characters to the data structure
  6. Reverse the input string to build the result in reverse order
  7. Check if a character is a digit using the built-in function `is_digit()` or by comparing its ASCII value to the ASCII values of digits
  8. Decrement the delete count when a non-digit character is encountered and the delete count is positive
  9. Reverse the result string to get the final answer
  10. Go through the string from left to right
💡 The optimized solution builds the stack from left to right, eliminating the need to reverse the result, and provides a more efficient solution to the problem.

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
4:10 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →