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

  Рет қаралды 24,069

Back To Back SWE

Back To Back SWE

Күн бұрын

Пікірлер: 113
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Table of Contents: A Quick Message 0:00 - 0:40 The Problem Introduction 0:40 - 0:53 What Is An API? 0:53 - 1:13 What Is An ADT? 1:13 - 2:03 The Stack ADT 2:03 - 2:42 Our Implementation Goal: A .max() Operation 2:42 - 3:25 The Problem We Face Using A Stack For This 3:25 - 6:41 The Epiphany: Cache Previous Max States 6:41 - 9:35 Improving Our Best Case Space Complexity To O(1) 9:35 - 14:06 How Did The Best Approach Help Us? Here Is How. 14:06 - 15:35 Please Subscribe To Me and Feed My Ego 15:35 - 16:16 The code for this question is in the description. Fully commented for learning purposes.
@Leo-lb6uj
@Leo-lb6uj 5 жыл бұрын
very good! thank you!
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
sure
@poojamadhavan9229
@poojamadhavan9229 4 жыл бұрын
Hi Ben, could you help understand the maximum frequency stack question on LC.?
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
@@poojamadhavan9229 Yeah, but not right now, we are busy building a new platform. Comes out in 3-4 weeks.
@Official-tk3nc
@Official-tk3nc 4 жыл бұрын
if you are watching this in lockdown believe me you are one of the rare species on the earth who is working hard to achieve something in life. Many students are wasting their time watching movies, playing pubg, watching netflix , etc, ALL THE BEST nitjstudenthere
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
lol - nice
@Jaffy.
@Jaffy. 4 жыл бұрын
Thx for the compliment lol
@大盗江南
@大盗江南 3 жыл бұрын
Thanks for the compliment too lol
@dmytroivanovv
@dmytroivanovv 3 жыл бұрын
Totally agree.
@BasharAlkhalili
@BasharAlkhalili 5 жыл бұрын
The state tracking trick blew my mind, and when I thought we were done, you came up with the optimized space trick. So much complexity for such a seemingly innocuous problem. But it's now all clear thanks to you, Ben.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
I didn't come up with this myself, found it reading elements of programming interviews
@juliesong2253
@juliesong2253 4 жыл бұрын
I usually never comment but I’ve been watching your videos religiously for the past month. I watched this video when I woke up this morning and got the exact same question that night during my interview. Just thought it was super cool and wanted to say thanks!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
great to hear
@zewang625
@zewang625 5 жыл бұрын
Great work! the most important thing is to recognize the problem. I like this idea.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
thanks
@James-le2hc
@James-le2hc 5 жыл бұрын
it's so simple once you realize you can treat each element as a node. the part of using a separate stack to reduce the layers of caching is a little tricky tho. it's because we think in definitions instead of creatively.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Yeah haha, first jump to caching is straight-forward, but the final jump to an O(1) best case space is trickier.
@zhenliu4779
@zhenliu4779 3 жыл бұрын
Trust me, this is the BEST explanation
@sushmithasnataraj5122
@sushmithasnataraj5122 4 жыл бұрын
You guys deserve more subscribers. Keep up the good work :)
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Thx and thx
@Anveshana837
@Anveshana837 3 жыл бұрын
One of the best educator, don't know why you stopped making videos😭
@Nirvana4u-n4w
@Nirvana4u-n4w 5 жыл бұрын
So many times, candidates get mental block. Good you mention that and how this is overcome. By the way, you don't need to maintain 2 stacks. Just have one stack, and have additional max entry, when the pop is equal to max entry, do it twice and get the previously stored cache max.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Thanks. And I'm not sure what you mean. Are you referring to the O(1) best case space approach? Could you elaborate
@Nirvana4u-n4w
@Nirvana4u-n4w 5 жыл бұрын
@@BackToBackSWE its similar to approach mentioned here - leetcode.com/explore/learn/card/queue-stack/230/usage-stack/1360/discuss/49031/Share-my-Java-solution-with-ONLY-ONE-stack
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
@@Nirvana4u-n4w Yeah, I've seen this. To me it's not so much that only one stack is used for that solution, but more importantly the solution is clever and always has O(1) additional space (since all min information is tracked on the items themselves) which makes it even more clever. I feel it is harder to understand though, but still just as valid of a solution. Thanks for sharing.
@nikhil.pandey
@nikhil.pandey 4 жыл бұрын
In love with your explanation.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
no luv u
@MiddleEasternInAmerica
@MiddleEasternInAmerica 4 жыл бұрын
Benyam Ephrem, you changed my life, thanks man
@MiddleEasternInAmerica
@MiddleEasternInAmerica 4 жыл бұрын
hope you make a follow up video using Double Linked List + TreeMap ( solution #2 on leetcode )
@tannerbarcelos6880
@tannerbarcelos6880 3 жыл бұрын
Got asked this (but min stack) yesterday in an interview. Luckily, they accepted my O(N) solution to getting the min() and told me I passed the technical round however , after I left the call, I realized I could use a second stack, or store an object ok value and current max at every push and keep O(1) Great video!
@walterwhite6499
@walterwhite6499 5 жыл бұрын
Use a tuple as (value, current_max_value) and store it in the stack. This way one can keep a track of max at every level of the stack. class MaxStack: def __init__(self): self.stack = [] self.cur_max = None def push(self, val): if not self.cur_max: self.cur_max = val else: self.cur_max = max(self.cur_max, val) self.stack.append((val, self.cur_max)) def pop(self): self.stack.pop() def max(self): return self.stack[len(self.stack)-1][1]
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
dope
@MoaazAhmad
@MoaazAhmad 5 жыл бұрын
@Walter White: This works but isn't optimized for space. At each push, you're storing the value and the max at that level. The second approach in the video (optimizing for best case) would require modifications to your code. Not really sure if interviewers would ask the best case optimization, but good to know nevertheless.
@walterwhite6499
@walterwhite6499 5 жыл бұрын
Mohammad Ahmad I don't how understand how is it not optimized for space?
@MoaazAhmad
@MoaazAhmad 5 жыл бұрын
@@walterwhite6499 Suppose you need to push [5,5,5,5,5,5,5,5,5,5] (ten 5's). Using your way, your stack contains *twenty* numbers. The 2nd method in the video only stores *twelve* numbers (ten 5's of the list, one 5 to represent the max value, and a 10 to represent how many times 10 is in the stack). This is for the best case though (when you have the same number appearing consecutively). Your method is optimized for the worst case.
@walterwhite6499
@walterwhite6499 5 жыл бұрын
Mohammad Ahmad at any given point of time the stack will have at most 2n elements which is same as O(n).
@dark4o90
@dark4o90 4 жыл бұрын
you don't need to store key/value pairs in stack. You can just push the maximum number to the maxCache every time you push to the main stack. This way the space will be O(2n). Keeping the key/value pairs is more than that. And in java for example it's cumbersome to create key/value pairs because you don't have tuples. You have to use arrays of two elements or from java 11 and above Pair object. When pushing a new element to the main stack check the last max from the maxCache and if the number is greater than the max push it to the maxCache as well otherwise push the last max.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
I cant read all of this im fast replying i love you
@karthikmucheli7930
@karthikmucheli7930 5 жыл бұрын
Do you have a patreon page? I just don't want you to stop making these amazing videos. I wish I could contribute more than just my view count.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
hahahaha, thank you, I am going to make a large video course/community with Chris Jereza soon
@ritwik121
@ritwik121 3 жыл бұрын
awesomeee thought process.... Good job
@mahmoudm451
@mahmoudm451 4 жыл бұрын
I only fail to see how we can create the max count annotation programmatically. Great video btw!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
With a wrapper class. you wrap entities then augment them with more fields
@SharatS
@SharatS 4 жыл бұрын
For C++, for instance, you could create a stack of pair of integers, then use that for the max cache.
@mo337
@mo337 4 жыл бұрын
This guy is my hero.👍
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
no u r
@kzu8976
@kzu8976 5 жыл бұрын
at 1:00 I'm totallly lost lol . the API definition is so hard to understand But! great video ! I like it. keep going
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
An API is simply a behavior set we define that clients to our code can depend on. It is a programming term. It is not the point of the video, just know we need to implement the .max() function for a stack object we are making. I mentioned it to give the bigger picture setup before we answered the question, but yeah. It is a simple concept, you will ease into it so don't worry.
@Franczinator
@Franczinator 5 жыл бұрын
An API is a way that someone can interact with your code. Pretend you wrote the "String" class. Examples of the "String" api would be something like the function that returns you the size of a string.
@loyyeeko1231
@loyyeeko1231 10 ай бұрын
this is great! thank you!
@rahulranjan7567
@rahulranjan7567 4 жыл бұрын
The solution uses O(N) of space . If the entries are in millions with random entries then we would need a huge cache. Can we do this in constant space and time? Moreover, instead of the spare stack you used to keep the track of max/min element, can't we use the hash table with each push being compared to the max variable and then updating the hash? maxEle = -sys.maxsize hashMap = {} i = 1 def push(x): if i == 1: stack.append(x) maxEle = x hashmap.update({i:maxEle}) else: if x>maxEle: stack.append(x) maxEle = x hashmap.update({i:maxEle) else: stack.append(x) hashmap.update({i:maxEle) i = i+1 Here, i keeps the track of the push operations we are performing. Hash table gives constant access.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
ok, I can't read all of this (I'm speed replying to comments). I hope you are right and that this helps someone
@hritwiksom3032
@hritwiksom3032 4 жыл бұрын
Why are you complicating it so much with a hash table? Just use an ArrayList/Array to keep track of the max element per push, the indices of the list keep track of the push operations; use a length var or i in your case to keep track of length of stack, increment/decrement it as per push/pop operations and get the location of the ArrayList element with its index being the current length of the stack. It has also O(1) access.
@grizzlycougar
@grizzlycougar 3 жыл бұрын
Came to check my solution and it was about the same except instead of caching the number of occurrences I cached the index at which that max number was at. So when popping elements off the stack you check the length of the stack and the top cached index, if those are the same you also pop off the cached stack. Basically the same run time and space complexity but different ways of thinking about it, IDK if this is that unique or not (probably not) but just an alternative.
@guptapaaras
@guptapaaras 4 жыл бұрын
Best ever explanation Bro.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
sure
@אוריישראל-ד3נ
@אוריישראל-ד3נ 4 жыл бұрын
hi it was very helpful thank you very much. also, can you explain how can i prove that all the implementations of delete max will be in omega of log(n)?
@lipishah474
@lipishah474 4 жыл бұрын
Excellent Video. I have question, in the second stack how can we store occurrence of max value? Thanks in advance.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
In an augmented structure like an extra object u make and append the field to cache the value
@Raj_Patel21
@Raj_Patel21 5 жыл бұрын
The second approach was nice.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
ye
@大盗江南
@大盗江南 3 жыл бұрын
U r amazing buddy, we love you.
@arindrajitseal4577
@arindrajitseal4577 4 жыл бұрын
awesome explanation
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@algorithmimplementer415
@algorithmimplementer415 4 жыл бұрын
Great video!!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@ArielVolovik
@ArielVolovik 3 жыл бұрын
How would we get the .max though? Say for the last example we want to get the `.max()` value which is 5. Isn't the only way to access it is by using `.pop()`? But then our max cache would be empty, and yet 5 would still be *in* the stack.
@sdevaney89
@sdevaney89 3 жыл бұрын
Stacks can have a .peek() method that will return the value on the top of the stack without removing it. So if you are you using his second example you would use a return the .peek() value of the max cache.
@mfkman
@mfkman 4 жыл бұрын
Instead of occurrences in the max stack, I would store the pointers of the elements leading to a new max. When I pop, I check, is the top of the stack pointing to the element I am popping? If yes, pop, else: don't.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Interesting, this brings on the cost of pointer dereferencing
@mfkman
@mfkman 4 жыл бұрын
@@BackToBackSWE actually during a pop I wouldn't be dereferencing anything - just checking if the addresses match. Only during a push (in order to valide if I have a new max) I would have to dereference the pointer at the top which would point to a location inside the actual element stack. Yes, this may impose the penalty of a cache miss if the last element was pushed quite some time ago.
@XChen-zj1ek
@XChen-zj1ek 5 жыл бұрын
This solution is brilliant, however, I don't think this can provide popMax() API which LeeCode also requires.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
ok
@spendingmarrow6914
@spendingmarrow6914 5 жыл бұрын
I believe we can actually do this in O(n) time. We use peak to get the max entry. Then we create a temporary stack and begin to pop and add items from the original stack to this temporary stack. Once we find the largest item we remove but do not add into the temporary stack. Finally, add the items back into the original stack and then return max item.
@joydeeprony89
@joydeeprony89 3 жыл бұрын
maxPop() could you implement.
@emilyhuang2759
@emilyhuang2759 4 жыл бұрын
Why can't I understand what is the goal of the problem??? The max is found but then the max is going back down again? Why is that not being returned? EDIT: I see now. This video is for getting the whole picture of whats happening. But why is having two stacks optimum? Instead of just using one variable to hold the state?
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Nice and I don't remmeber the approaches - been a while since I recorded this. Are you confused about the complexities?
@ankitgoyal8556
@ankitgoyal8556 4 жыл бұрын
Brother, there is a solution to find min() in O(1) time and O(1) space, do actually interviewer expect that from us? Or we can O(1) time and O(n) space like your solution. Thank you
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
im not sure
@ankitgoyal8556
@ankitgoyal8556 4 жыл бұрын
@@BackToBackSWE Thank you for replying brother, love from India 🔥
@ShaliniNegi24
@ShaliniNegi24 4 жыл бұрын
Thank you and god bless you :)
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Thanks
@guowanqi9004
@guowanqi9004 5 жыл бұрын
Thank you so much sir.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
sure
@minhhnh_in_jp
@minhhnh_in_jp 5 жыл бұрын
Thanks you so muchhhhhh ♥
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
sure
@srihariathiyarath9722
@srihariathiyarath9722 4 жыл бұрын
Is there any way we can sort the stack initially so that we can just pop off the maximum ?!
@pointerish
@pointerish 4 жыл бұрын
You could, but sorting it's another whole thing to study. Depending on how big the array/stack is, if they are partially sorted already, if they are integers or objects. You could use merge sort, quicksort, radio sort depending on what you're sorting.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
@@pointerish yes
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Sorting would violate the insertion order unless copies of items were made with references back to the original items. This may be a solution that works with more space (but not asymptotically more, still linear).
@Eyenn_n
@Eyenn_n 4 жыл бұрын
AWESOME!!!!!!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@RuslanSkiraUkraine
@RuslanSkiraUkraine 3 жыл бұрын
In don't understand with 2 stack How we will increment the maximum?
@ianzhang7048
@ianzhang7048 5 жыл бұрын
NICE!
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
hi
@db-wk8xb
@db-wk8xb 5 жыл бұрын
how can it be done using just one stack
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
7:08
@chrisy.703
@chrisy.703 2 жыл бұрын
how about poping max value? ur solution not includes this case AT ALL
@hritwiksom3032
@hritwiksom3032 4 жыл бұрын
This is not a constant space solution as the number of elements added to max stack is not fixed. P. S. This still is the optimal solution as there can't be O(1) space solution unless number of pop operations are known, which is kinda idiotic if it's provided lol 😉
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
rapid replying to comments I cant I love u tho
@raremajor
@raremajor 5 жыл бұрын
How do you land up with an Intern in twitter?(If that's where you got your tshirt from)
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
what lol
@raremajor
@raremajor 5 жыл бұрын
How to get an intern/FTE at Twitter?
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
@@raremajor I can't teach that. No one can teach that. Just because someone worked somewhere doesn't mean that they know anything about teaching someone how to work there. It really just happens by luck & part skill (mostly luck & good fortune). Ex: Google employees can't teach one how to get a job at Google. They know how their interviews were, but are not certified in projecting what your specific team will ask, gauging your abilities, etc.
@Naveen-luffy56
@Naveen-luffy56 4 жыл бұрын
I cant find the code
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
The repository is deprecated - we only maintain backtobackswe.com now.
@PankajKP
@PankajKP 5 жыл бұрын
i guess you have too many t-shirts hahaha
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
yeah haha
Чистка воды совком от денег
00:32
FD Vasya
Рет қаралды 2,7 МЛН
Hoodie gets wicked makeover! 😲
00:47
Justin Flom
Рет қаралды 138 МЛН
Кто круче, как думаешь?
00:44
МЯТНАЯ ФАНТА
Рет қаралды 6 МЛН
Муж внезапно вернулся домой @Oscar_elteacher
00:43
История одного вокалиста
Рет қаралды 7 МЛН
The Fix For Your Database Performance Issues in .NET
9:12
Nick Chapsas
Рет қаралды 27 М.
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
14:25
Implement Min Stack | O(2N) and O(N) Space Complexity
22:44
take U forward
Рет қаралды 91 М.
L4. Implement Min Stack | Stack and Queue Playlist
20:55
take U forward
Рет қаралды 46 М.
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
29:31
Back To Back SWE
Рет қаралды 51 М.
Max Stack: 716 - leetcode premium LinkedIn interview question
12:38
Destination FAANG
Рет қаралды 1,1 М.
Чистка воды совком от денег
00:32
FD Vasya
Рет қаралды 2,7 МЛН