Cyclic Shift to a Reverse-Sorted Array
Problem statement
You are given an integer array nums of length n.
For an integer t with 0 <= t < n, a cyclic t-shift moves the last t elements of nums to the beginning while preserving their order.
Return the value of t that transforms nums into the reverse-sorted array [n, n - 1, ..., 1]. If no such shift exists, return -1.
Function
solution(nums: int[]) → intExamples
Example 1
nums = [3,2,1,5,4]return = 2Moving the last two elements to the front produces [5,4,3,2,1], so t = 2.
Example 2
nums = [5,4,3,2,1]return = 0The array already equals [5,4,3,2,1], so no shift is needed.
Example 3
nums = [1,2,3]return = -1No cyclic shift produces [3,2,1], so the result is -1.
Constraints
- For this exercise, assume
1 <= nums.length <= 100000. - For this exercise, assume
-10^9 <= nums[i] <= 10^9.