Shuffle String | LeetCode 1528

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.

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.

Example

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

Solution

We can easily solve “Shuffle String” coding problem using single loop. Stepwise breakdown of solution is as follows.

  • Create a string to store the answer.
  • Iterate through each character of original string.
    • For each character store character to new index from indices array in answer string.
  • Return the answer string.

Implementation of above solution in C++ is as follows.

C++
class Solution {
public:
    string restoreString(string s, vector<int>& indices) {
       int n = s.size();
       string answer = s;

       for(int i=0; i<n; i++) {
        answer[indices[i]] = s[i];
       }

       return answer;
    }
};

Time Complexity

O(n) where n = number of characters in string.

Space Complexity

O(n) where n = number of characters in string.

Thanks for reading and have a nice day.