VOOZH about

URL: https://www.geeksforgeeks.org/dsa/track-the-trail/

⇱ Local Min and Max Sequence Ordering - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Local Min and Max Sequence Ordering

Last Updated : 23 Mar, 2026

Given an integer array arr[] representing a sequence of elevations, Return an array that includes:

  • The first and last elements of the array.
  • Every element where the trend of the sequence changes that is, where the direction of change switches from increasing to decreasing or from decreasing to increasing.

Note: Consecutive equal elements (flat segments) should be treated as a single elevation and ignored for detecting direction changes.

Input: arr[] = [6, 4, 2, -2, 5, 3, 2, 2, -1, -1, 4]
Output: [6, -2, 5, -1, 4]
Explanation: Starts from 6 goes down to -2, -2 is the breaking point then 5, 5 is the breaking point then from 5 goes down to -1, -1 is breaking point then 4.

👁 frame_8

Input: arr[] = [6, 10, 11, 13]
Output: [6, 13]
Explanation: 6 is the starting point and 13 is last point.

Input: arr[] = [1, 1]
Output: [1]
Explanation: Since we start from 1 but do not move further.

[Approach] Traversal with Turning Point Detection - O(n) Time and O(1) Space

The idea is to follow the changes in elevation as we move through the array. We start by adding the first point. Then, for each point, we check if it forms a peak or a valley—that means the direction of the trail is changing there. If it does, we include it. At the end, we add the last point if it’s not already there. This way, we keep only the important turning points and ignore the flat or straight parts.


Output
6 -2 5 -1 4 
Comment
Article Tags:
Article Tags: