Trionic Array I Problem
#3637
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3637.
You are given an integer array nums of length n.
An array is trionic if there exist indices 0 < p < q < n − 1 such that:
nums[0...p]is strictly increasing,nums[p...q]is strictly decreasing,nums[q...n − 1]is strictly increasing.
Return true if nums is trionic, otherwise return false.
Example 1:
Input: nums = [1,3,5,4,2,6]
Output: true
Explanation:
Pick p = 2, q = 4:
- nums[0...2] = [1, 3, 5] is strictly increasing (1 < 3 < 5).
- nums[2...4] = [5, 4, 2] is strictly decreasing (5 > 4 > 2).
- nums[4...5] = [2, 6] is strictly increasing (2 < 6).
Example 2:
Input: nums = [2,1,3]
Output: false
Explanation:
There is no way to pick p and q to form the required three segments.
Constraints:
3 <= n <= 100-1000 <= nums[i] <= 1000
Solution
Approach: Single Pass
Walk through the three parts with two pointers.
Move p right while the values strictly increase. If p never moved (p = 0), there is no increasing prefix, so return false.
Start q at p and move it right while the values strictly decrease. If q = p (nothing decreasing) or q = n - 1 (no room for a third part), return false.
Finally move q right while the values strictly increase. The array is trionic exactly when q reaches the last index.
Complexity: O(n) time and O(1) space, where n is the length of the array.
class Solution:
def isTrionic(self, nums: List[int]) -> bool:
n = len(nums)
p = 0
while p < n - 2 and nums[p] < nums[p + 1]:
p += 1
if p == 0:
return False
q = p
while q < n - 1 and nums[q] > nums[q + 1]:
q += 1
if q == p or q == n - 1:
return False
while q < n - 1 and nums[q] < nums[q + 1]:
q += 1
return q == n - 1