Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Thread: Understanding the 132 Pattern Problem | Monotonic Stack | N^3 -> N Complexity
Mar 23, 2025
412 views
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
1. What Are We Talking About?
The 132 pattern is a problem where we need to find a subsequence of three numbers in an array (nums[i], nums[j], nums[k]) such that:
Example 1:
Example 2:
2. Real-World Applications
While the 132 pattern might seem abstract, it has real-world applications in:
3. Brute-Force Approach
The brute-force approach involves checking all possible triplets (i, j, k) in the array to see if they satisfy the 132 pattern.
for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { for (let k = j + 1; k < nums.length; k++) { if (nums[i] < nums[k] && nums[k] < nums[j]) { return true; // Found a 132 pattern } } } } return false;Complexity:
4. Thinking Process for the Optimised Approach
The brute-force approach is too slow for large arrays. To optimize, we need to:
Why the Monotonic Stack Works
5. Approach to Code:
var find132pattern = function(nums) { const stack = []; let nums_k = -Infinity; for (let j = nums.length - 1; j >= 0; j--) { if (nums[j] < nums_k) { return true; } while (stack.length > 0 && stack[stack.length - 1] < nums[j]) { nums_k = stack.pop(); } stack.push(nums[j]); } return false; };Example to Illustrate
Let’s take the array [5, 4, 3, 2, 1, 6] and analyze the operations:
Time Complexity:
So the time is for loop run N times i.e O(N), inner while loop total operation is O(N)
Space Complexity: