Sort Array Using Prefix Reversals - Solution & Explanation
Problem Statement
You are given an integer array nums of length n, where nums is a permutation of the integers in the range [0, n - 1].
You are also given an integer array pre, where each pre[i] is a valid prefix length.
In one operation, you may choose any length x from pre and reverse the first x elements of nums.
For example, applying a prefix reversal of length 3 on [4, 1, 2, 3] results in [2, 1, 4, 3].
Return the minimum number of operations required to sort nums in ascending order. If it is impossible to sort nums, return -1.
Example 1:
Input: nums = [2,0,1], pre = [2,3]
Output: 2
Explanation:
- Reverse
pre[1] = 3elements to getnums = [1, 0, 2]. - Then reverse
pre[0] = 2elements to getnums = [0, 1, 2]. - Thus, the minimum number of prefix reversal required is 2.
Example 2:
Input: nums = [1,0,2], pre = [1,3]
Output: -1
Explanation:
It is impossible to sort the array using the given prefix lengths, so the answer is -1.
Example 3:
Input: nums = [0,1], pre = [2]
Output: 0
Explanation:
Since nums is already sorted, no prefix reversals are needed. Thus, the answer is 0.
Constraints:
1 <= n == nums.length <= 80 <= nums[i] <= n - 11 <= pre.length <= n1 <= pre[i] <= nnumsis a permutation of integers from 0 ton - 1.preconsists of unique integers.
Approach Overview
Problem Overview: You need to sort an array using only prefix reversals. A prefix reversal flips the first k elements of the array. The challenge is finding a sequence of flips that produces a sorted array efficiently.
Approach 1: Brute Force Simulation (O(n³) time, O(1) space)
The brute force idea tries multiple prefix reversals at each position until the array becomes sorted. You repeatedly scan the array, identify misplaced elements, and test flips that move values closer to their target positions. This works for small inputs but wastes time because every flip may require another full scan to validate ordering. Use this approach only to understand how prefix reversals affect array state.
Approach 2: Greedy Pancake Sort (O(n²) time, O(1) space)
This is the standard and expected solution. Iterate from the end of the array toward the beginning. For each index, locate the maximum element in the unsorted portion, reverse its prefix to bring it to the front, then reverse the larger prefix to move it into its final sorted position. Each iteration fixes exactly one element, which keeps the logic simple and deterministic. This approach is commonly categorized under greedy and array problems because every operation greedily places the next largest value.
Approach 3: Optimized Greedy with Early Skip (O(n²) time, O(1) space)
You can reduce unnecessary reversals by skipping elements already positioned correctly. Before performing any flip, check whether the current maximum already sits at its target index. If it does, continue immediately to the next iteration. This does not improve worst-case complexity, but it reduces operations significantly on partially sorted arrays. Interviewers often appreciate this refinement because it shows attention to practical optimization instead of only asymptotic analysis.
Recommended for interviews: Interviewers expect the greedy pancake sort solution because it directly matches the constraints of prefix reversals. Showing the brute force idea first demonstrates problem exploration, but the greedy method proves you can identify the invariant: after every two reversals, one element reaches its final position. Understanding prefix operations and in-place manipulation also overlaps with sorting interview patterns.
Solution
Since n \le 8, the number of permutations is at most 8! = 40320, so we can use BFS to find the minimum number of operations.
Treat the current array as a state, and the target state is [0, 1, ldots, n - 1]. If the initial state is already the target, return 0. Otherwise, start BFS from the initial state: each time take a state from the queue, enumerate every prefix length x in pre, and reverse the first x elements to obtain a new state. If the new state equals the target, return the current number of steps; otherwise, if it has not been visited, enqueue it. If the search finishes without reaching the target, return -1.
For convenience of deduplication, encode each permutation as an integer in base 8 (every element lies in [0, 7]).
The time complexity is O(n! cdot m cdot n), and the space complexity is O(n! cdot n). Here, n is the length of the array, and m is the length of pre.
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Simulation | O(n³) | O(1) | Learning how prefix reversals affect ordering |
| Greedy Pancake Sort | O(n²) | O(1) | General case and interview settings |
| Optimized Greedy with Early Skip | O(n²) | O(1) | Partially sorted arrays with fewer flips |
Frequently Asked Questions
Is Sort Array Using Prefix Reversals easy or hard?
Sort Array Using Prefix Reversals Python/Java solution
How to solve Sort Array Using Prefix Reversals in O(n)?
What is the best approach for Sort Array Using Prefix Reversals?
Is Sort Array Using Prefix Reversals asked at Google/Amazon/Meta?
What data structure is used in Sort Array Using Prefix Reversals?
What is the time complexity of Sort Array Using Prefix Reversals?
Ready to solve this problem?
Practice Sort Array Using Prefix Reversals with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor