Shuffle String

The given problem asks to shuffle the characters in a given string s according to the given indices. We will follow the mapping given in the indices array to rearrange the characters in the original string.

Approach

  1. Create a new list result of the same length as s, initialized with empty strings.
  2. Iterate through s and indices together, placing each character from s at the index specified in indices in the result list.
  3. Join the result list to get the shuffled string.

Code

1
2
3
4
5
6
class Solution:
    def restoreString(self, s: str, indices: List[int]) -> str:
        result = [''] * len(s)
        for char, index in zip(s, indices):
            result[index] = char
        return ''.join(result)

Example

For s = "codeleet" and indices = [4,5,6,7,0,2,1,3], the function would return "leetcode".

Complexity

The time complexity of this solution is O(n), where n is the length of the given string s, as we iterate through the string once. The space complexity is also O(n) for the result list.