← Questions

Sort an array with rotate and flip operations

0
AmazonCodingLast asked May 2026

A coding interview question asked in Amazon's online assessment, last asked May 2026. It tests arrays, bfs and math.

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

Clarifying questions

  • Is a rotation always to the left, by one position?
  • Does a flip followed by a flip count as two steps? (Yes, so it is never useful.)
  • Should an array that is already sorted return 0?
  • Do we need the steps themselves?

What a strong answer covers

  • Notes that rotations and flips can only produce rotations of the array and rotations of its reverse. So the array can be sorted only if it is a rotation of the sorted order, or of the reverse sorted order. Otherwise the answer is -1.
  • Models each reachable arrangement as a state (rotation offset, flipped or not): only 2n states, each with two moves.
  • Finds the shortest path to the sorted state with BFS over those states, or with a short formula over the few useful move patterns. That is O(n).
  • Checks "is a rotation of sorted" in O(n) by finding the minimum and walking once.
  • Tests all three examples, n = 1, n = 2, a sorted array, and a reverse-sorted array (one flip).

Follow-ups

  • Return the sequence of steps.
  • Rotations in both directions are allowed.
  • Only a prefix can be flipped (pancake sorting).
  • Values can repeat.

Where it's asked

  • Amazon · Online assessment · Last asked May 2026Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

arrays · bfs · math

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding