51. Stack-4: implementation

 1. Stock Span Problem-

for a stream of data we have to tell no. of elements before curr which are <= curr , including curr.

Method-1: storing price, span in stack

Method-2: storing price, index in stack


-----------------------------------------------------------------------------------------------------------------------------

 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)

------------------------------------------------------------------
Brute Force-
--------------------------------------------------------------
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

Popular posts from this blog

18. greedy algorithm

19. strings (LB)

17. BINARY SEARCH on 2d arrrays