Skip to content
Onsite

Sort by Reversing One Subarray

MediumP3Coding

You are given an array nums of distinct integers. Return true if the array is already sorted in ascending order, or if reversing exactly one contiguous subarray makes it sorted. Otherwise return false.

Example 1

Input
nums = [1,3,2,4]
Output
true
Why
Reverse [3,2] to get [1,2,3,4].

Example 2

Input
nums = [1,2,3]
Output
true

Example 3

Input
nums = [3,1,2]
Output
false

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • All values are distinct

Hints

Run checks the 3 visible tests, Submit all 10.