AlgoMaster Logo

132 Pattern

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach involves checking every possible triplet to see if it forms a 132 pattern. The 132 pattern means finding three indices i, j, k such that i < j < k and nums[i] < nums[k] < nums[j].

Steps:

  1. Loop over the array and fix i.
  2. For every fixed i, fix j and ensure j > i.
  3. For every fixed j, loop over the array to find an element k, where k > j and nums[i] < nums[k] < nums[j].
  4. If such a triplet is found, return true.
  5. If after checking all possibilities, no triplet is found, return false.

Code:

2. Using Stacks

Intuition:

To optimize, we can use a stack to maintain candidates for the second largest number (nums[j]) in the pattern 132 by iterating from the right. We will also maintain a variable nums[k] as the second number in the 132 pattern.

Steps:

  1. Traverse the array from the right.
  2. Keep a variable third to track the maximum number less than nums[j] which can be a candidate for nums[k].
  3. Use a stack to maintain the numbers which can potentially be nums[j].
  4. For each element nums[i], check:
    • If nums[i] is less than third, a valid 132 pattern is found.
  5. If no 132 pattern is found by the end of the loop, return false.

Code: