Ctrl K

Fix the Middle of the Line

Medium
Students stand in a line, with their heights listed in heights. The teacher wants heights to never decrease from left to right, but will only rearrange people inside **one contiguous stretch** of the line: that stretch gets sorted in ascending order and everyone else stays put. Return the length of the shortest such stretch that makes the whole line ordered. If the line is already in order, return 0. Sorting in O(n log n) is the obvious route; try to do it in O(n).
Example 1
heights=[150, 158, 155, 162, 170, 165, 180] → 5

Reordering positions 1 to 5, [158, 155, 162, 170, 165] → [155, 158, 162, 165, 170], fixes the whole line. The length is 5.

Example 2
heights=[3, 3, 4, 9] → 0

The line is already in order, so nobody has to move.

Example 3
heights=[5, 1] → 2

Both people have to be reordered.

Constraints
  • 1 ≤ len(heights) ≤ 10⁴
  • -10⁵ ≤ heights[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Pieces Sorted Separately MediumOutclassed Heroes MediumLargest Number From Two Rows HardSorting Batches With Repeats HardStudios for Recording Sessions Medium
loading Python…
Input
heights=[150, 158, 155, 162, 170, 165, 180]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 161 tests on the server, hidden ones included.