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
- 93 lines of C++ from the credited upstream file sort-array-using-prefix-reversals.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 9 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 {6public:7 int sortArray(vector<int>& nums, vector<int>& pre) {8 const auto& to_string = [](const auto& arr) {9 string result;10 result.reserve(size(arr));11 for (const auto& x : arr) {12 result.push_back('0' + x);13 }14 return result;15 };16 17 const auto& bi_bfs = [&](const auto& start, const auto& target) {18 unordered_set<string> left = {start}, right = {target}, lookup;19 for (int steps = 0; !empty(left); ++steps) {20 if (size(left) > size(right)) {21 swap(left, right);22 }23 for (const auto& x : left) {24 lookup.emplace(x);25 }26 unordered_set<string> new_left;27 for (auto x : left) {28 if (right.count(x)) {29 return steps;30 }31 for (const auto& i : pre) {32 reverse(begin(x), begin(x) + i);33 if (!lookup.count(x)) {34 new_left.emplace(x);35 }36 reverse(begin(x), begin(x) + i);37 }38 }39 left = move(new_left);40 }41 return -1;42 };43 44 vector<int> arr(size(nums));45 iota(begin(arr), end(arr), 0);46 return bi_bfs(to_string(nums), to_string(arr));47 }48};49 50515253class Solution2 {54public:55 int sortArray(vector<int>& nums, vector<int>& pre) {56 const auto& to_string = [](const auto& arr) {57 string result;58 result.reserve(size(arr));59 for (const auto& x : arr) {60 result.push_back('0' + x);61 }62 return result;63 };64 65 const auto& bfs = [&](const auto& start, const auto& target) {66 unordered_set<string> lookup = {start};67 vector<string> q = {start};68 for (int steps = 0; !empty(q); ++steps) {69 vector<string> new_q;70 for (auto x : q) {71 if (x == target) {72 return steps;73 }74 for (const auto& i : pre) {75 reverse(begin(x), begin(x) + i);76 if (!lookup.count(x)) {77 lookup.emplace(x);78 new_q.emplace_back(x);79 }80 reverse(begin(x), begin(x) + i);81 }82 }83 q = move(new_q);84 }85 return -1;86 };87 88 vector<int> arr(size(nums));89 iota(begin(arr), end(arr), 0);90 return bfs(to_string(nums), to_string(arr));91 }92};93