Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
Follow up: The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution?
Example 1:
Input: [1, 2, 3, 4]
Output: False
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [-1, 3, 2, 0]
Output: True
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
The basic idea is that, for a particular number nums[j], we can find the smallest nums[i] where i<j, to maximize the interval [nums[i], nums[j]], so that it is more likely to find a required nums[k].
We first maintain all the smallest nums[i] in a min array, where requires mins[i]=min(nums[:i-1]). Then we traverse nums in a descending order and use a stack to keep track of all potential nums[k]. In the loop, we continue to check i-1 if mins[i] ≥ nums[i]. We always push to nums[i] the stack when a loop ends. When the stack is not empty, we keep on popping elements from the stack until stack[top] ≤ min[k]. Then check that if the statement stack[top] < nums[i] is satisfied we can return a true value. In the end, we return a false value due to no elements in the stack satisfing the 132 pattern.
Complexity
Time complexity: O(n). You may notice there is a nested for-loop in the second part. But we can note that atmost n elements can be pushed and popped off the stack in total. Thus the second traversal requires only O(2n)=O(n) time.