51. Stack-4: implementation
1. Stock Span Problem-
2. max element from each k-sized sliding window-⭐
(Google)
Brute force-
--------------------------------
Optimal-
to reduce quadratic time complexity to linear, we need to get max element in a window & be able to delete last element and add new at the same time, so we must use a data structure to do so, we linear time is only consumed while traversing & not in any operation.
So, we need a deque-
we will store elements in monotonic decreasing order (starting from bottom to top of dequeue)
SUMMARY-
1. pehle first window se deque bhardo
2. ab har next element k liye is element ki window ke alawa faaltu elements hatado
3. aur har window mein <= wali condition ke according pop push ka dekhlo
-------------------------------------
if ( st.size()<k ) :-
1. while, [ curr > st.Top() ] => st.popTop()
2. if, [ curr < st.Top() or st.empty() ] => st.pushTop(curr)
store st.front() (largest of that window) in ans vector after every element analysis
when you are at an element & window is already full => pop out element from bottom & do above stuff
---------------------------------------
3. Celebrity Problem-(not stack ques)
Optimal- Use 2 pointer at 0 and n-1
if idx1 knows idx2 then idx1 can't be celebrity
using this concept we move pointers from top and bottom row & reach final row
to confirm if this row is our answer we can check its row & its corresponding column
-----------------------------------------------------------------------------------------------------------------------------
4. LRU cache-
Comments
Post a Comment