Advertisement
Iam_Sandeep

456. 132 Pattern

Jul 25th, 2022
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. '''
  2. why we have to keep small variable why not just use min_so_far in
  3. stack tuple?
  4. Because min_so_far will just denote minimum till the tuple element
  5. is present.
  6. where as small will denote whole smallest till present ruunning index
  7. '''
  8. class Solution:
  9.     def find132pattern(self, a: List[int]) -> bool:
  10.         small=float('inf')
  11.         st=[] #store(val,min_so_far_before curr val)
  12.         for i in a:
  13.             while st and st[-1][0]<=i:
  14.                 st.pop()
  15.             if st and st[-1][1]<i:
  16.                 return True
  17.             st.append((i,small))
  18.             small=min(small,i)
  19.         return False
  20. '''
  21. we will keep a variable smallest to know the smallest number to the left (index i) of the current element (index j) so that there will be higher chance we find k which k > j > i and A[j] > A[k] > A[i] (because now we already have j > i and A[j] > A[i] the only thing we need to do is find if there is a element to the right of A[j] which smaller than A[j] and greater than A[i]), each time we will pop the stack until the last number of the last element in the stack greater than the current number, if Stack[-1][0] > current element it means we found 1 3 2 pattern (this step is exactly the same with finding previous greater element).
  22. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement