Shuffle String (LeetCode 1528): Solution and Explanation
Each character of s comes with a target position indices[i]. Put every character at its target and return the resulting string.
Intuition
The problem already tells you where every character goes, so there is no searching or sorting to do. It is a pure scatter.
Since indices is a permutation of 0..n-1, every slot of the answer receives exactly one character and no two characters fight over a slot.
Strings are immutable in most languages, so write into a character buffer of length n and turn it into a string at the end.
Approach: Scatter into a buffer
- Allocate a character buffer
resultof length n. - For each position
iins, writes[i]intoresult[indices[i]]. - Join the buffer into a string and return it.
Step-by-step example
s = "codeleet", indices = [4,5,6,7,0,2,1,3]
- 'c' goes to slot 4, 'o' to slot 5, 'd' to slot 6, 'e' to slot 7.
- 'l' goes to slot 0, so the word now starts with l.
- 'e' goes to slot 2, 'e' to slot 1, 't' to slot 3.
- The slots read l, e, e, t, c, o, d, e.
- Return "leetcode".
Code: Python, Java, C++
1class Solution:
2 def restoreString(self, s: str, indices: List[int]) -> str:
3 result = [''] * len(s)
4 for i, ch in enumerate(s):
5 result[indices[i]] = ch
6 return ''.join(result)1class Solution {
2 public String restoreString(String s, int[] indices) {
3 char[] result = new char[s.length()];
4 for (int i = 0; i < s.length(); i++) {
5 result[indices[i]] = s.charAt(i);
6 }
7 return new String(result);
8 }
9}1class Solution {
2public:
3 string restoreString(string s, vector<int>& indices) {
4 string result(s.size(), ' ');
5 for (int i = 0; i < (int)s.size(); i++) {
6 result[indices[i]] = s[i];
7 }
8 return result;
9 }
10};Time and space complexity
O(n)
One write per character plus the final join.
O(n)
The output buffer has n characters. No other memory is needed.
Other approaches
Sort pairs by index (time O(n log n), space O(n))
Zip each character with its index, sort the pairs by index and read the characters. Works, but sorting is unnecessary when the target positions are given.
Cyclic swaps in place (time O(n), space O(1) extra)
Treat indices as a permutation and swap each character into place, updating indices as you go, like cycle sort. This avoids a second buffer when the input is mutable.
Common mistakes
- Reading instead of writing:
result[i] = s[indices[i]]applies the inverse permutation and gives the wrong string unless the permutation is its own inverse. - Building the answer by repeated string concatenation in a loop, which is quadratic in languages with immutable strings.
- Assuming the character order in
smatters for the loop. Any visiting order works because each slot is written once.
Frequently asked questions
Why is result[indices[i]] = s[i] correct and not the other way round?
indices[i] is where the character at i ends up. Writing s[i] into that slot moves it there. Reading from s[indices[i]] would instead pull characters from their destinations.
Can two characters land in the same slot?
No. The constraints say all values of indices are unique, so it is a permutation and every slot gets exactly one character.
Can this be done without extra space?
If you may modify the input, yes: follow each permutation cycle and swap characters (and indices) into place. In languages with immutable strings you still need a mutable copy.