Problem 247818 · medium · Phase 02 Linear Data Structures

Longest Zigzag Stretch

arrays · runs · neighbours

A stretch of nums is a zigzag if the direction between neighbours strictly alternates: up, down, up, ... or down, up, down, ... (equal neighbours break a zigzag). Return the length of the longest contiguous zigzag stretch. Any single element is a zigzag of length 1; return 0 for an empty list.

Examples

Input:  nums = [9, 4, 2, 10, 7, 8, 8, 1, 9]
Output: 5
Explanation: 4 > 2 < 10 > 7 < 8 is the longest zigzag.

Input:  nums = [4, 8, 12, 16]
Output: 2

Input:  nums = [100]
Output: 1

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space.

Goals

  • Track two run lengths that feed into each other
  • Reset on equal neighbours
Starting Python…