LeetCode 0456. 132 Pattern Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0456. 132 Pattern

Description

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 three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

 

Constraints:

  • n == nums.length
  • 1 <= n <= 2 * 105
  • -109 <= nums[i] <= 109

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
class Solution: def find132pattern(self, nums: List[int]) -> bool: vk = -inf stk = [] for x in nums[::-1]: if x < vk: return True while stk and stk[-1] < x: vk = stk.pop() stk.append(x) return False(code-box)

Solution 2

PythonJavaC++GoTypeScript
class BinaryIndexedTree: def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x, delta): while x <= self.n: self.c[x] += delta x += x & -x def query(self, x): s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def find132pattern(self, nums: List[int]) -> bool: s = sorted(set(nums)) n = len(nums) left = [inf] * (n + 1) for i, x in enumerate(nums): left[i + 1] = min(left[i], x) tree = BinaryIndexedTree(len(s)) for i in range(n - 1, -1, -1): x = bisect_left(s, nums[i]) + 1 y = bisect_left(s, left[i]) + 1 if x > y and tree.query(x - 1) > tree.query(y): return True tree.update(x, 1) return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !