Sort in Linear Time an Array Where At Most One Element Was Moved Out of Place
Company: Glean
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given an array that was sorted until one element was moved to another position, return it sorted again in linear time without a full sort. Tests locating the displaced element in either direction, handling duplicates and already-sorted input, and reasoning about O(n) time with constant extra space.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums is either already sorted in non-decreasing order, or obtainable from a non-decreasing array by moving exactly one element to a different position (toward the front or the back, by any distance)
- Values may repeat
Examples
Input: ([1, 2, 9, 3, 4, 5],)
Expected Output: [1, 2, 3, 4, 5, 9]
Explanation: Source Example 1: the 9 was moved from the end toward the front to index 2.
Input: ([3, 5, 7, 1, 9],)
Expected Output: [1, 3, 5, 7, 9]
Explanation: Source Example 2: the 1 was moved from the front toward the back to index 3.
Hints
- If you removed the one displaced element, the remaining elements would already be in non-decreasing order.
- The displaced element may have moved toward the front or toward the back, by any distance, so consider both directions.
- Values may repeat, so check how your comparisons treat equal neighbors.