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
.
Example 1:
Input: nums = [1, 2, 3, 4]
Output: false
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: nums = [3, 1, 4, 2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: nums = [-1, 3, 2, 0]
Output: true
Explanation: There are several 132 patterns in the sequence: [-1, 3, 2] and [-1, 3, 0].
To solve this problem efficiently, an O(n) time complexity solution can be used via a stack-based approach. Here’s the strategy:
sec
(second highest):
nums[k]
(values which might be the middle one in the 132 pattern).sec
will help us ensure we have a valid candidate for nums[i]
.nums[i]
.sec
to see if nums[i] < nums[k]
where nums[k]
is a previously seen value.nums[k]
for a future nums[j]
).nums[j]
.Here’s the implementation in Python:
def find132pattern(nums):
if len(nums) < 3:
return False
stack = []
sec = float('-inf') # This will hold the second highest number in the 132 pattern
# Traverse backwards
for i in range(len(nums) - 1, -1, -1):
if nums[i] < sec:
return True
while stack and nums[i] > stack[-1]:
sec = stack.pop()
stack.append(nums[i])
return False
# Test cases
print(find132pattern([1, 2, 3, 4])) # Output: False
print(find132pattern([3, 1, 4, 2])) # Output: True
print(find132pattern([-1, 3, 2, 0])) # Output: True
nums[j]
values.This solution efficiently finds the 132 pattern using stack operations, ensuring optimal performance for larger inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?