Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A trionic array has exactly three nonempty runs of comparisons: increasing, then decreasing, then increasing. Strict comparisons determine where each phase ends, so one forward scan can verify the required shape.
Approach
Advance through the initial strictly increasing run and reject if it contains no increasing step. Record its endpoint as the first turning point. Then advance through a strictly decreasing run and reject if this phase also contains no step.
Finally advance through another strictly increasing run. Accept only if this last phase contains at least one step and reaches the end of the array. Any equality stops the current phase and cannot be consumed by the next strict comparison, so equal adjacent values correctly cause rejection. Requiring all three phases to move ensures the turning points satisfy the problem's interior-position constraints.
class Solution:
def isTrionic(self, nums: List[int]) -> bool:
n = len(nums)
i = 1
while i < n and nums[i] > nums[i - 1]:
i += 1
p = i - 1
if p == 0:
return False
while i < n and nums[i] < nums[i - 1]:
i += 1
q = i - 1
if q == p:
return False
while i < n and nums[i] > nums[i - 1]:
i += 1
if i - 1 == q or i < n:
return False
return TrueComplexity analysis
Let n = nums.length. Time: O(n). Auxiliary space: O(1).
