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

1
2
3
4
5
6

![](https://assets.leetcode.com/uploads/2020/07/09/q1.jpg)

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

Example 2

1
2
3
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.

Constraints

  • s.length == indices.length == n
  • 1 <= n <= 100
  • s consists of only lowercase English letters.
  • 0 <= indices[i] < n
  • All values of indices are 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

  1. Initialize a result array of length n.
  2. For each i, set result[indices[i]] = s[i].
  3. Join and return the result as a string.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#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;
    }
};
1
2
3
4
5
6
7
8
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);
    }
}
1
2
3
4
5
6
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.