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
2. Sliding window maximum⭐⭐
return max element from each of the k-sized sliding window
----------------------------------------------------
Brute- time: O(nk)
For each window, scan k elements and take max
--------------------------------------------------------
Optimal- time: O(n)
we need to do below operations as required :
- get max element in a window in O(1)
- delete last element & add new at the same time in O(1)
- traverse in O(n)
--------
So, we maintain a DEQUE storing indices, elements in monotonic decreasing order (from bottom to top) because if a new element is bigger than the previous one , then all previous ones can't be maximum ones in future...
---------
if ( st.size()<k ) :-
----------------------------------------------------
Brute- time: O(nk)
For each window, scan k elements and take max
--------------------------------------------------------
Optimal- time: O(n)
we need to do below operations as required :
- get max element in a window in O(1)
- delete last element & add new at the same time in O(1)
- traverse in O(n)
--------
So, we maintain a DEQUE storing indices, elements in monotonic decreasing order (from bottom to top) because if a new element is bigger than the previous one , then all previous ones can't be maximum ones in future...
---------
if ( st.size()<k ) :-
1. while ( st.top() < curr ) => remove top
2. if ( st.top() > curr ,or st.empty() ) => push curr at top
3. store st.front() 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-
a[i][j] = 1, means ith person knows jth person
Return index of celebrity ( known by all & knows none )
-----------------------------------------------------------
Brute- time: O(n^2) space: O(n)
Celebrity is the person who is known by exactly n-1 people & he knows 0 people
Better- time: O(n) space: O(n)
Using Stack
Comments
Post a Comment