Approach
Breadth-first search
For Sort Array Using Prefix Reversals, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 67 lines of Python from the credited upstream file sort-array-using-prefix-reversals.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def sortArray(self, nums, pre):7 """8 :type nums: List[int]9 :type pre: List[int]10 :rtype: int11 """12 def bi_bfs(start, target):13 left, right = {start}, {target}14 lookup = set()15 steps = 016 while left:17 if len(left) > len(right): 18 left, right = right, left19 for x in left:20 lookup.add(x)21 new_left = set()22 for x in left:23 if x in right: 24 return steps25 for i in pre:26 nx = tuple(reversed(x[:i]))+x[i:]27 if nx in lookup:28 continue29 new_left.add(nx)30 left = new_left31 steps += 132 return -133 34 return bi_bfs(tuple(nums), tuple(xrange(len(nums))))35 36 37383940class Solution2(object):41 def sortArray(self, nums, pre):42 """43 :type nums: List[int]44 :type pre: List[int]45 :rtype: int46 """47 def bfs(start, target):48 lookup = {start}49 q = [start]50 steps = 051 while q:52 new_q = []53 for x in q:54 if x == target:55 return steps56 for i in pre:57 nx = tuple(reversed(x[:i]))+x[i:]58 if nx in lookup:59 continue60 lookup.add(nx)61 new_q.append(nx)62 q = new_q63 steps += 164 return -165 66 return bfs(tuple(nums), tuple(xrange(len(nums))))67