Shuffle String
EasyUpdated: Aug 2, 2025
Practice on:
Problem
You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith
position moves to indices[i] in the shuffled string.
Return the shuffled string.
Examples
Example 1

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
Constraints
s.length == indices.length == n1 <= n <= 100sconsists of only lowercase English letters.0 <= indices[i] < n- All values of
indicesare unique.
Solution
Method 1 – Direct Placement
Intuition
Create a result array of the same length as s. For each character, place it at the index specified by indices[i].
Approach
- Initialize a result array of length n.
- For each i, set result[indices[i]] = s[i].
- Join and return the result as a string.
Code
C++
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
string res(s.size(), ' ');
for (int i = 0; i < s.size(); ++i)
res[indices[i]] = s[i];
return res;
}
};
Java
class Solution {
public String restoreString(String s, int[] indices) {
char[] res = new char[s.length()];
for (int i = 0; i < s.length(); ++i)
res[indices[i]] = s.charAt(i);
return new String(res);
}
}
Python
class Solution:
def restoreString(self, s, indices):
res = [''] * len(s)
for i, c in enumerate(s):
res[indices[i]] = c
return ''.join(res)
Complexity
- ⏰ Time complexity:
O(n)— n = len(s). - 🧺 Space complexity:
O(n)— For the result array.