Problem solution · Python

Sort Array Using Prefix Reversals

Sort Array Using Prefix Reversals: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
67 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeSort Array Using Prefix Reversals · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n! * n * m)# Space: O(n! * n) # bi-bfsclass Solution(object):    def sortArray(self, nums, pre):        """        :type nums: List[int]        :type pre: List[int]        :rtype: int        """        def bi_bfs(start, target):            left, right = {start}, {target}            lookup = set()            steps = 0            while left:                if len(left) > len(right):                     left, right = right, left                for x in left:                    lookup.add(x)                new_left = set()                for x in left:                    if x in right:                         return steps                    for i in pre:                        nx = tuple(reversed(x[:i]))+x[i:]                        if nx in lookup:                            continue                        new_left.add(nx)                left = new_left                steps += 1            return -1         return bi_bfs(tuple(nums), tuple(xrange(len(nums))))  # Time:  O(n! * n * m)# Space: O(n! * n)# bfsclass Solution2(object):    def sortArray(self, nums, pre):        """        :type nums: List[int]        :type pre: List[int]        :rtype: int        """        def bfs(start, target):            lookup = {start}            q = [start]            steps = 0            while q:                new_q = []                for x in q:                    if x == target:                        return steps                    for i in pre:                        nx = tuple(reversed(x[:i]))+x[i:]                        if nx in lookup:                            continue                        lookup.add(nx)                        new_q.append(nx)                q = new_q                steps += 1            return -1         return bfs(tuple(nums), tuple(xrange(len(nums)))) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗