Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stack-Based Approach to Detect 132 Pattern #345

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

gautamjag7
Copy link

Intuition

We are looking for a subsequence in the array that follows the 132 pattern: a sequence where there exists indices i < j < k such that nums[i] < nums[k] < nums[j]. The key is to track the largest '2' in the 132 pattern using a stack.

Approach

  1. Traverse the array in reverse (starting from the rightmost element).
  2. Use a stack to keep track of potential '3' values in the 132 pattern.
  3. Maintain a variable prev to store the most recent valid '2' found in the sequence.
  4. For each element nums[i], check if it is less than the current prev ('2'). If yes, we've found a valid 132 pattern.
  5. Update prev by popping from the stack, ensuring we always have the largest possible '2'.
  6. Push the current element into the stack as a potential '3'.

Complexity

  • Time complexity:
    The time complexity is ( O(n) ), where ( n ) is the size of the input array. Each element is pushed and popped from the stack at most once.

  • Space complexity:
    The space complexity is ( O(n) ) in the worst case, due to the space used by the stack.

@HarshwardhanPatil07
Copy link
Owner

Follow the rules make sure to star and follow for Hacktoberfest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants