456. 132 Pattern

naive

O(n^3)

O(1)

class Solution {
    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if (nums[i] < nums[k] && nums[k] < nums[j]) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

optimized naive 2

T: O(n^2)

T: O(1)

mono stack

this one is kind of like next greater, but this one is to find next smaller, from end

T: O(n)

S: O(n)

Last updated

Was this helpful?