Skip to problem
←

Sort an Array with One Reversal

Medium 0 attempts

Given an integer array arr, determine whether it can be sorted in nondecreasing order by reversing at most one contiguous subarray. Duplicate values are allowed.

Return true for an already sorted array; no reversal is required.

Function contract

Implement canSortByReversing(arr), where arr is an integer array that may contain duplicates.

Output: true if reversing at most one contiguous interval makes arr nondecreasing; otherwise false. An already sorted array returns true.

Example 1

Input
arr = [1,2,5,4,3]
Output
true

Example 2

Input
arr = [1,2,3,4]
Output
true

Example 3

Input
arr = [1,3,2,2,4]
Output
true
Constraints
  • 1 <= arr.length <= 10^5
  • arr contains safe integers.

Compare with the Sorted Order

Find the first and last indices that differ from a sorted copy. If one reversal can sort the array, reversing that complete interval must produce the sorted order. This also handles duplicate values at the interval boundaries.

javascript
function canSortByReversing(arr) {
  const sorted = [...arr].sort((a,b)=>a-b);
  let left = 0, right = arr.length - 1;
  while (left < arr.length && arr[left] === sorted[left]) left++;
  while (right > left && arr[right] === sorted[right]) right--;
  for (let i = left; i <= right; i++) if (arr[left + right - i] !== sorted[i]) return false;
  return true;
}

Time: O(n log n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript