Shuffle String - 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.

Input & Output

Example 1 — Basic Shuffling
$ Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
💡 Note: Characters are rearranged: s[0]='c' goes to indices[0]=4, s[1]='o' goes to indices[1]=5, etc. Result: "leetcode"
Example 2 — Short String
$ Input: s = "abc", indices = [0,1,2]
Output: "abc"
💡 Note: Each character stays in the same position: 'a' at 0, 'b' at 1, 'c' at 2
Example 3 — Complete Reversal
$ Input: s = "aiohn", indices = [3,1,4,2,0]
Output: "nihao"
💡 Note: s[0]='a' → pos 3, s[1]='i' → pos 1, s[2]='o' → pos 4, s[3]='h' → pos 2, s[4]='n' → pos 0

Constraints

  • s.length == indices.length
  • 1 ≤ s.length ≤ 100
  • s contains only lowercase English letters
  • 0 ≤ indices[i] < s.length
  • All values of indices are unique

Visualization

Tap to expand
Shuffle String - Direct Building INPUT String s = "codeleet" c o d e l e e t 0 1 2 3 4 5 6 7 indices = [4,5,6,7,0,2,1,3] 4 5 6 7 0 2 1 3 Mapping: s[i] goes to indices[i] c-->4 o-->5 d-->6 e-->7 l-->0 e-->2 e-->1 t-->3 ALGORITHM STEPS 1 Create Result Array Initialize array of same length as input string 2 Iterate Through String For each index i from 0 to length-1 3 Place Characters result[indices[i]] = s[i] Direct placement 4 Build Final String Join array to form the shuffled string Building Result: i=0: res[4]='c' i=1: res[5]='o' i=4: res[0]='l' i=2: res[6]='d' i=3: res[7]='e' ... FINAL RESULT Shuffled String: l e e t c o d e 0 1 2 3 4 5 6 7 Output: "leetcode" OK - Verified! Complexity Analysis Time: O(n) - single pass Space: O(n) - result array n = length of string Key Insight: The indices array tells us exactly where each character should go in the result. By directly placing s[i] at position indices[i], we build the answer in one pass - no need to sort or rearrange! TutorialsPoint - Shuffle String | Direct String Building Approach
Asked in
Microsoft 15 Amazon 12 Google 8
72.8K Views
Medium Frequency
~8 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen