Sort Array Using Prefix Reversals Problem
Description
LeetCode Problem 3991.
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] = 3 elements to get nums = [1, 0, 2].
- Then reverse pre[0] = 2 elements to get nums = [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.
Solution
Approach: BFS
With n <= 8 there are at most 8! = 40320 permutations, so a breadth-first search over all reachable arrangements is cheap.
Treat each arrangement of the array as a state, with [0, 1, ..., n - 1] as the target. If the start is already sorted, return 0. Otherwise run BFS: from each state, reverse the first x elements for every x in pre to get the next states, and return the number of steps when the target appears. States that were seen before are skipped. If the queue empties without reaching the target, return -1. A state can be encoded as a base-8 integer because every value is in [0, 7].
Complexity: time O(n! * m * n) and space O(n! * n), where m is the length of pre.
class Solution:
def sortArray(self, nums: List[int], pre: List[int]) -> int:
from collections import deque
n = len(nums)
target = tuple(range(n))
start = tuple(nums)
if start == target:
return 0
vis = {start}
q = deque([(start, 0)])
while q:
state, dist = q.popleft()
nd = dist + 1
for x in pre:
nxt = state[:x][::-1] + state[x:]
if nxt == target:
return nd
if nxt not in vis:
vis.add(nxt)
q.append((nxt, nd))
return -1