Shuffle String (LeetCode 1528): Solution and Explanation

Easy
Array
String

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

  1. Allocate a character buffer result of length n.
  2. For each position i in s, write s[i] into result[indices[i]].
  3. Join the buffer into a string and return it.

Step-by-step example

s = "codeleet", indices = [4,5,6,7,0,2,1,3]
  1. 'c' goes to slot 4, 'o' to slot 5, 'd' to slot 6, 'e' to slot 7.
  2. 'l' goes to slot 0, so the word now starts with l.
  3. 'e' goes to slot 2, 'e' to slot 1, 't' to slot 3.
  4. The slots read l, e, e, t, c, o, d, e.
  5. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Scatter into a buffer O(n)
Cyclic swaps in place O(n)
Sort pairs by index O(n log n)
Time

O(n)

One write per character plus the final join.

Space

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 s matters 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.