FastPrepCyclic Shift to a Reverse-Sorted Array

Cyclic Shift to a Reverse-Sorted Array

TikTok logoTikTok● EasyFULLTIMEOA
Learn

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[]) → int

Examples

Example 1

nums = [3,2,1,5,4]return = 2

Moving 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 = 0

The array already equals [5,4,3,2,1], so no shift is needed.

Example 3

nums = [1,2,3]return = -1

No 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.

More TikTok problems

See TikTok hiring insights
public int solution(int[] nums) {
    // Write your code here.
}
nums[3,2,1,5,4]
expected2
Checking account…