Sort an array with rotate and flip operations

0
Sign in

You are given an array arr of n distinct integers. You may apply two operations, and each one counts as one step:

  • Rotate: remove the first element and append it to the end. [p, q, r, s] becomes [q, r, s, p].
  • Flip: reverse the whole array. [p, q, r, s] becomes [s, r, q, p].

Return the minimum number of steps needed to make arr strictly increasing. If no sequence of steps sorts it, return -1.

Implement min_ops(arr: list[int]) -> int.

Constraints

  • 1 <= n <= 10^5
  • All values are distinct and fit in a 32-bit signed integer.
  • Aim for O(n log n) time or better.

Example 1

Input:  arr = [30, 40, 10, 20]
Output: 2

Rotate twice: [40, 10, 20, 30], then [10, 20, 30, 40].

Example 2

Input:  arr = [20, 30, 40, 50, 10]
Output: 3

Four rotations work, but flip, rotate, flip is shorter: [10, 50, 40, 30, 20], [50, 40, 30, 20, 10], [10, 20, 30, 40, 50].

Example 3

Input:  arr = [5, 1, 3, 2]
Output: -1
AmazonCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.