Shuffle String
Problem
You are given a string s and an integer array indices of the same length. The string is shuffled so that the character originally at position i moves to position indices[i] in the result. Return the shuffled string.
s = "codeleet", indices = [4,5,6,7,0,2,1,3]"leetcode"s = "abc", indices = [0,1,2]"abc"def restore_string(s, indices):
n = len(s)
result = [""] * n
for i in range(n):
result[indices[i]] = s[i]
return "".join(result)
function restoreString(s, indices) {
const n = s.length;
const result = new Array(n);
for (let i = 0; i < n; i++) {
result[indices[i]] = s[i];
}
return result.join("");
}
String restoreString(String s, int[] indices) {
int n = s.length();
char[] result = new char[n];
for (int i = 0; i < n; i++) {
result[indices[i]] = s.charAt(i);
}
return new String(result);
}
string restoreString(string s, vector<int>& indices) {
int n = s.size();
string result(n, ' ');
for (int i = 0; i < n; i++) {
result[indices[i]] = s[i];
}
return result;
}
Explanation
The problem describes a permutation of characters: each source position i has a target position indices[i]. Because every value in indices is unique and lies in [0, n), the mapping is a bijection — every target slot is filled exactly once.
The cleanest approach is a single scatter pass. Allocate a result buffer of length n, then for each i write s[i] into result[indices[i]]. No sorting and no extra bookkeeping are needed.
After the loop, every slot of result holds the correct character, so we join the buffer back into a string and return it.
For example with s = "codeleet", the character 'c' at i = 0 is placed at index 4, 'o' at index 5, and continuing through the array spells out "leetcode".
This runs in O(n) time with a single pass, and O(n) extra space for the result buffer.