Problem
Given an original array, and it new position to be. Reposition it according the given indices array. For example:
1 | let arr = ["a", "b", "c", "d", "e", "f"] |
Follow Up
Try to do it in-place, i.e. : Space Complexity O(1)
Solution 1: Space complexity O(n)
1 | function rePosition(arr, indices){ |
Solution 2: Space complexity O(1)
We need two variables: kickedItem
and kickedIndex
, to denote the kicked item in arr
and kicked index in indices
Every time we update an item in its new position, we put item in its new position, and swap the kicked item and index to their counterpart in
arr
&indices
Since the kicked item & its new position are just swapped to previous position, we can keep staring the same position to deal with the chaining update, until there is an end to the chain
NOTE: there are also cases (test case 3) that the new indices are not depended upon one another, but instead they are partially dependent. That’s why we need to maintain two variable for both
arr
&indices
, rather than just forarr
1 |
|