Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)

Back To Back SWE · Beginner ·⚡ Algorithms & Data Structures ·7y ago

Key Takeaways

The video demonstrates how to implement a Max Stack with a .max() API, utilizing two stacks and a max cache to achieve linear space and time complexity. The implementation involves pushing items to the item stack and max stack, caching max values with occurrences, and updating the max stack cache when the max value changes.

Full Transcript

weird flex but okay all right welcome back to the channel if you have not already subscribed to the channel subscribe to the channel my goal is to make this the premier resource the top resource for software engineering prep we've only done maybe 29 or 30 videos of like 250 videos that I want to get done so you're gonna need to know so many things for the interview and it's like all these subjects so that's why this is gonna take time to build up this library of videos so subscribe to stick with me I think in a year we're eventually going to complete this project anyway today we have a fascinating stack of question let's get straight into it right yeah alright so today we're gonna talk about the topic stack with dot max so whenever we say API I think of like web api's I used to think an API is like when we're interfacing with a web service or something so an API is called application programming interface all it is is a strict set of functions or properties behaviors we define from a certain system or a certain underneath set of logic that is going to provide us a certain behavior and this sets us the fundamental basis for what is called an abstract data type and ADT so a stack is an abstract data type so what does that mean it means we support an interface to the outside world we say hey I'm going to give you these behaviors I'm going to give you these properties you don't need to know how I do this it's you're interfacing with me I don't need to tell you how I'm doing it I'll do these things for you it's like we're signing it this is why they call it a contract and interfaces a contract we say I'm going to give you these services don't worry about how I do them just accept that I'll provide these to you in the way that I describe so it's like if you hire an electrician you don't worry about how he's fixing your lights you just worried that he's going to fix your lights you worry about the results the end behavior and not how it's done a stack it's an abstract data type we can implement it however we want but what it needs to support is two principal operations the push operation and the pop operation both of these operations operate in constant time no matter what the size of the stack is I know that what is going to happen is as input gets arbitrarily large or the size is arbitrarily large the time of pushing an item the time it takes to pop an item is not going to scale it's going to stay in a constant fashion it's going to stay constant so we need to support push and pop so that makes sense a stack is LIFO last in first out but this question says implement a max API that seems odd so now we need a max function we need a function that gives us the maximum item in a stack so that's that's an odd question to ask because a stack isn't really made for that and we would never even think this to appear on a stack but the whole point of this is to test how do you think test how you can work around these limitations that a stack gives us with this push and pop behavior now let's see the problem we run into and as always I want to walk you through the thought process the intuitions the the way that my brain goes solving this and then we'll slowly snake into the optimal solution now let's start with the problem that a stack provides us with this question whenever we are tackling these questions the key is figure out the problem before we even can figure out a solution so we need to see the barriers that our brain hits that we hit in this question that our structure limits us with before we even can solve it and continue with a solution I've given us a set of numbers that we're going to push and what we're gonna do is we're gonna just keep track of the maximum and what I want you to notice is the problem that we face so here's our strategy we're going to figure out how as we go along what I'm gonna do is I'm gonna push one so let's push one it does one be our maximum we initialize this with a negative infinity so does one be our maximum so we have nothing so one becomes the max okay that's cool so now let's push two so two gets pushed does to beat the maximum of course it does so now we put two as the maximum and push - all right great so now let's push three does three beat the maximum yes it does all right and now we push to there's to beat the maximum no it does not we push the two we did not change our max our max is still 3 so right now as it is if a caller was like hey I want the maximum from you stack we have no problem returning it in constant time we have it we know that now let's push the 0 to 0 B 3 no it doesn't just push it okay so our max is still 3 that makes sense and of course it is true we can see it is true so now push the 4 and we notice that our not changed for is the new maximum so everything is going right and we're doing fine constant time access bang we have the maximum our stack is behaving normally but the problem happens when we try to pop in Adam so let me pop the 4 so when we pop the 4 I realize for was my maximum so we need to adjust our maximum let's do that but wait this is a stack we we can't adjust our maximum because we don't know what the maximum is at this point in this state we don't know what the maximum was at this point we've lost it we over wrote the maximum because we overrode it we lose access when we pop this item so now we know our problem we have our problem so what is the solution to this problem did you just notice me saying state do you notice how we over wrote a state so the next mental leap I need you to make or that you would make in an interview solving this is you say hey I need to catch the maximum at each of these states at each of the pushes I'm going to see what was the maximum element as this item beat the maximum and I'm going to remember at every element what the maximum was so when I pop at this point the 0 needs to remember hey 3 was the maximum the 2 needs to remember 3 was the maximum 3 needs to remember well 3 itself is the maximum so 2 needs to remember that 2 is the maximum and one needs to remember that 1 is the maximum now let's do this new approach and again remember the problem is when we pop this we would have to do a linear time search then our max operation is not constant time our max must be constant time it cannot be linear in time we cannot search this in a linear fashion and it's a stack we would have to search it linearly we can't do any binary searches or anything because it's not sorted what we need to do is really the maximum hey I know the maximum I've cashed that state I already know it was so what we do is let's do our normal pushes so we push one we see we don't have a maximum one becomes a new maximum and one remembers that what is the maximum in the stack so forth okay cool so do you see this entry we have the normal one and then we see that one was the maximum so now we've completed that so now we push the two does oh I forgot to update the max by so now let's push the two does to beat the maximum yes to does beat the maximum and to is going to remember what the maximum was its itself it just beat the maximum so let's update our state okay so now that anything's going okay so if I pop this two then if I add this date I know that one is the maximum so let's continue so now let's push three does three beat the max yes and threes gonna remember the maximum which is itself alright so now we are at the two so let's push the two does two beats the maximum two does not beat the maximum three but what we do know is that we're going to catch this three we're going to know that the maximum when this item was pushed when the seven was pushed the maximum is three so we're gonna push the two and remember that and now let's push the zero again it does not be the maximum but we need to remember that our max below us is three so what we do is push the zero and now we see for four beats the maximum so we can push for and it's our new maximum it remembers itself as the max so for push so now I want you to see how this solves the problem that we're aiming to do you see how we're taking little jumps in our approach because we found our problem we gave it a little solution this is not the optimal solution in terms of space in terms of time yes but not in terms of space so we can pop this four so my caller says I want to top item give me the top item what's great is what's the max the max is three I know I remember I remember it and I did not lose it so I mean we won't even need this because we're going to remember this on the stack that was just for examples sake but we're going to remember this so what we do is we can pop again and again we're not lost anymore constant time access we remember it what is the max in the stack it's three what is the max in the stack it's two what is the max in the stack it is one this is a very good solution this is going to use linear space than linear time linear space is because for each of these nodes we're going to have to annotate with the maximum and that entails extra space so we know our worst case space is going to be all event but let me wonder can I improve the best case space when am I going to be able to opt to my space this is going to lead us into our optimal solution so what we do is as follows let me show you an example and then explain the intuition behind it okay so the optimal solution for this problem is going to be where we keep track of two stacks so this is going to be our item stack our actual value stack and this is going to be our maximum stack our cache of the maximum all right so now we have two stacks so wait why did I just make another stack so did you notice how when we did that we repeated three we cache the three we cache the three cache the three the problem is if I add an item like zero it will not be 30 it has no chance so the thing is we're going to be caching the same maximum on these nodes when they never had a chance to even beat the maximum so why not create a separate cache where I can say I've seen the maximum three three times if I pop a three I remove that maximum of three and then I've seen three two times so let's do a walk through this will not do you need to see this pictorially verbally it's not going to make sense so let's do this walk through very quickly all right so I have switched up the numbers so that we can actually see why this approves our space and why this is more optimal so what we're going to do is we're going to push - we don't have a maximal yet in our max cache so two is going to get an entry in the maximum cash and to is just going to be pushed to the actual stack so now we push to to the actual items and we've created a cache entry for this item in our max stack so we've seen the maximum - one time one occurrence of the maximum - so now we're gonna push another - and the reason this approach helps us is because we don't want to cache - as a maximum again we can just keep the occurrences over here so what we do is we're going to add the two and then we're going to increment this amounts because this is our DB maximum so this is going to become - and we're going to push that to okay so now this is the actual stack and this is the max stack so when we push the one we're going to peak the top of the max cache and we see that it does not be - so we're not even going to keep track of another - on this one we're about to push it will not even have a chance to be - beats the maximum so we just push the one and we don't even create an entry for it in the max cache do you notice how if a max operation was called we would have constant access to the maximum but the thing is this one contributes nothing to this so the one does not even influence this so so far we're fine so what we need to do now is push the for for is going to be a maximum because it beats this entry so we're going to create an entry for 4 and push it to the stack ok so we pushed for and now we again we know 4 is our maximum if we peek the max cache we're going to have our maximum item name costs in time so now we push a 5 we see 5 as a new maximum push it to the stack create a new cache entry okay we created a cache entry and together you see another 5 so all we do is we increment the amount of occurrences of the maximum 5 so now we see that this becomes 2 and we push another 5 and so now we push the 3 we see it doesn't beat the peak to maximum the maximum at the top so we just push 3 it contributes nothing and so now we're going to see what happens on pop so I know that this is the maximum 5 is the maximum so far so pop 3 is 3 in our max cache no it's not we do not need to adjust this just pop the 3 all right as 5 in our max cache is if the top entry yes it is deke remount to the - we only have one occurrence of 5 as a max and pop the five okay and now if we pop this five again we need to the commence a new one and we're going to do that now after we do that we notice that five does not have any more max entries so five gets popped off of the backs cache so now again if we were asked the maximum we have the answer for and that's correct so what we do now is we're going to pop four we are going to determine to the amount of occurrences of that in the max cache and that's what's going to happen so now we have zero occurrences of the four after doing that pop we noticed that so we pop this off of the backs cache and again constant time access to the maximum item it's - that's correct pop the one is the one going to be influencing this notes or knots because it doesn't even have an entry at the top so just pop the one so now we see a two and we know that's going to influence the max cache if it's popped this is going to take prevent and will pop and now finally we pop the tune we see it influences this this becomes zero this gets popped and after doing that popping we need to pop this item because there's no more occurrences so this is the approach that improves our best case space so as always I want to ask myself why why does this improve our best case space before was o of n every element would have to hold an item there we saw that it was roughly better but here is a case that really exemplifies why this approach is the best so let me push 5 and we see it's a new max entry and now let me push 0 we see that it does not influence the mass catch now let me push 0 now let me push 0 again it's not influencing our Max cash now let me push 0 and again let me push 0 and one more time let me push 0 do you notice that as our input can get arbitrarily large you give me 10 million zeroes the space is going to stay constant we're not going to scale the amount of space we use this is our best case if we get many items that do not influence this cache do you see why this approach is better instead of cashing a 5 on all of these zeros what we're going to do is that's it that's our maximum right there our best case for space can now be constant but we still bound in linear time because if we have to if the max changes frequently then we're going to have many entries on this max cache but this is this problem this is stack with the max API I don't even think we need to go over complexities because we know pushes constant time pop is constant time and Max is constant time and I've already discussed the space and how this improves our best keys so there's your complexities if you like this video like I like the video what I say if you like this video like the video oh my god I said it again if you like this video subscribe to the channel and like this video my goal is to make a great resource with clear explanations for these software engineering interview questions walking you through the thought process and how you can jump from what you know to what you don't know and seeing how you can work out of these difficult situations where you might not see the optimal solution going from problem to solution so that is my goal with this channel I want to create as much of an impact as possible and yeah that's what it's about [Music]

Original Description

Free 5-Day Mini-Course: https://backtobackswe.com Try Our Full Platform: https://backtobackswe.com/pricing 📹 Intuitive Video Explanations 🏃 Run Code As You Learn 💾 Save Progress ❓New Unseen Questions 🔎 Get All Solutions Question: Design a stack that includes a max operation, in addition to push and pop. The max method should return the maximum value stored in the stack. A stack is an abstract data type (ADT). An ADT is a data type is defined by its behavior from the point of view of a user of the data, we can implement it however we want as long as we give the user the interface they need to get what they expect from the ADT. Stack is LIFO since the last item to go in, is the first one to come out. Here we are asked to implement a stack with a max API which entails. push() Add an element pop() Get the top element max() Get the maximum element The reason this is a problem is because the stack ADT restricts how data is added and retrieved from the structure so to make the .max() function run optimally we will have to think a little harder than the first approach we think of. Approach 1 (No Optimizations & Obvious) To answer a call to .max() we can iterate through the whole structure supporting our stack underneath and return the maximum item whether it is implemented with an array, a lined list, etc. This will take O(n) "linear" time always and O(1) "constant" space Approach 2 (Use Auxiliary Data Structures) We can use a max heap or a Binary Search Tree in tandem with a hashtable for fast lookups. This idea is critical. Auxiliary structures with a hash table backing your ordered structures for quick lookups to get immediate reference to objects. The structure solves the problem. The hashtable let's you get into it fast. This can bring us to log(n) time, but worsens space to O(n) since we will store at max all items potentially. Approach 3 (Remember The Max At Each Element) Write the optimal code [in EPI], but walkthrough this fir
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Back To Back SWE · Back To Back SWE · 29 of 60

1 4 Tips To Learn Java Programming As Fast As Possible As A Beginner
4 Tips To Learn Java Programming As Fast As Possible As A Beginner
Back To Back SWE
2 3 Mistakes Beginners Make When First Learning Java and Android Development
3 Mistakes Beginners Make When First Learning Java and Android Development
Back To Back SWE
3 How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
Back To Back SWE
4 The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Back To Back SWE
5 Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Back To Back SWE
6 The N Queens Problem using Backtracking/Recursion - Explained
The N Queens Problem using Backtracking/Recursion - Explained
Back To Back SWE
7 Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Back To Back SWE
8 How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
Back To Back SWE
9 Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Back To Back SWE
10 The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
Back To Back SWE
11 The Dutch National Flag Problem (The Quicksort "Band-Aid")
The Dutch National Flag Problem (The Quicksort "Band-Aid")
Back To Back SWE
12 Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Back To Back SWE
13 The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
Back To Back SWE
14 How To Permute A String - Generate All Permutations Of A String
How To Permute A String - Generate All Permutations Of A String
Back To Back SWE
15 The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
Back To Back SWE
16 Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search -  First Occurrence Of Substring
Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search - First Occurrence Of Substring
Back To Back SWE
17 Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Back To Back SWE
18 Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Back To Back SWE
19 Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Back To Back SWE
20 Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Back To Back SWE
21 Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Back To Back SWE
22 Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Back To Back SWE
23 Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Back To Back SWE
24 Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Back To Back SWE
25 The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
Back To Back SWE
26 Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Back To Back SWE
27 Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Back To Back SWE
28 Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Back To Back SWE
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Back To Back SWE
30 The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
Back To Back SWE
31 Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Back To Back SWE
32 Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Back To Back SWE
33 Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Back To Back SWE
34 Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Back To Back SWE
35 Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Back To Back SWE
36 Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Back To Back SWE
37 Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Back To Back SWE
38 Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Back To Back SWE
39 Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Back To Back SWE
40 Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Back To Back SWE
41 Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Back To Back SWE
42 Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Back To Back SWE
43 What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
Back To Back SWE
44 An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
Back To Back SWE
45 Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Back To Back SWE
46 A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
Back To Back SWE
47 Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Back To Back SWE
48 Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Back To Back SWE
49 All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
Back To Back SWE
50 Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Back To Back SWE
51 Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Back To Back SWE
52 Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Back To Back SWE
53 Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Back To Back SWE
54 Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Back To Back SWE
55 The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
Back To Back SWE
56 Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Back To Back SWE
57 Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Back To Back SWE
58 The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
Back To Back SWE
59 Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Back To Back SWE
60 Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Back To Back SWE

This video teaches how to implement a Max Stack with a .max() API, which is essential for understanding data structures and algorithms. The implementation involves using two stacks and a max cache to achieve linear space and time complexity. By following the steps outlined in the video, viewers can learn how to design and implement a Max Stack.

Key Takeaways
  1. Push one onto the stack and initialize the maximum value to negative infinity
  2. Push elements and update max_stack when a new max is found
  3. Catch max at each state when pushing elements
  4. Use max_stack to return the max in constant time
  5. Push items to item stack and max stack
  6. Cache max values with occurrences
  7. Update max stack cache when max value changes
💡 The max cache is updated by incrementing the occurrence count of the maximum element when a new element is pushed, and decrementing the occurrence count when the maximum element is popped.

Related Reads

📰
The Run-Length Encoding Trick: How Simple Strings Get Compressed
Learn how Run-Length Encoding (RLE) compresses simple strings, a fundamental technique in programming and data compression, and apply it to optimize storage and transmission of data
Medium · Programming
📰
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Solve the Product of Array Except Self problem on LeetCode to improve coding skills and learn array manipulation techniques
Medium · AI
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Learn how the author implemented an algorithm that broke the sorting barrier and compare its performance with Dijkstra's algorithm
Medium · Programming
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Implementing an algorithm that breaks the sorting barrier still can't beat Dijkstra's algorithm in practice, highlighting the importance of real-world testing and optimization.
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →