mediumStackPattern: Stack

Minimize Congestion Sequence Solution

Problem Statement

Given an array of integers representing road segments with their respective traffic congestion levels, determine the optimal sequence to traverse these segments while minimizing congestion.

Examples

Example 1:
Input:[5, 10, 8, 13, 20]
Output:[5, 8, 13, 10, 20]
Explanation: The optimal sequence is one where all segments are traversed in ascending order of congestion level.
Example 2:
Input:[3, 1, 4, 6, 2]
Output:[1, 2, 6, 3, 4]
Explanation: The optimal sequence is one where all segments are traversed in ascending order of congestion level.
Example 3:
Input:[100]
Output:[100]
Explanation: A single-element array has only one possible traversal order.

Constraints

  • The array contains unique integers.
  • The array has at least one element.
  • The sequence can only be traversed by moving forward or backward, and each segment must be visited exactly once.
  • The input array can be empty but this edge case is handled separately.
  • All congestion levels are non-negative integers.
Time: O(n log n) Space: O(n)
An optimized approach is to use a sorting algorithm to sort the array in ascending order, then use two pointers (one at the start and one at the end of the array) to traverse the segments in sequence.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.