Shuffle String - Problem
Shuffle String is a fundamental array manipulation problem that tests your understanding of index mapping and string reconstruction.

You are given a string s and an integer array indices of the same length. The task is to rearrange the characters of the string according to the position mapping defined by the indices array.

Specifically, the character at position i in the original string should be moved to position indices[i] in the shuffled result.

Goal: Return the shuffled string after applying the position transformations.

Example: If s = "codeleet" and indices = [4,5,6,7,0,2,1,3], then:
• Character 'c' at index 0 goes to position indices[0] = 4
• Character 'o' at index 1 goes to position indices[1] = 5
• And so on...

The result would be "leetcode".

Input & Output

example_1.py — Basic String Shuffle
$ Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
💡 Note: Character 'c' at index 0 goes to position 4, 'o' at index 1 goes to position 5, 'd' at index 2 goes to position 6, etc. The final rearranged string spells "leetcode".
example_2.py — Simple Pattern
$ Input: s = "abc", indices = [0,1,2]
Output: "abc"
💡 Note: Each character stays in its original position since indices[i] = i for all positions. No shuffling occurs.
example_3.py — Complete Reversal
$ Input: s = "aiohn", indices = [3,1,4,2,0]
Output: "nihao"
💡 Note: Characters are rearranged according to the indices mapping: 'a'→pos3, 'i'→pos1, 'o'→pos4, 'h'→pos2, 'n'→pos0, forming "nihao".

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 (it's a permutation)

Visualization

Tap to expand
🎭 Musical Chairs: String ShuffleInitial Line-up (Original String)CTicket: 4OTicket: 5DTicket: 6ETicket: 7LTicket: 0ETicket: 2ETicket: 1TTicket: 3Movement Arrows (Each Goes to Their Seat)L→Seat 0E→Seat 1E→Seat 2Final Seating Arrangement (Result)LSeat 0ESeat 1ESeat 2TSeat 3CSeat 4OSeat 5DSeat 6ESeat 7"LEETCODE"Final Result
Understanding the Visualization
1
Setup
Musicians line up with their destination tickets
2
Direct Placement
Each musician moves directly to their assigned seat
3
Result
Final orchestra arrangement is complete
Key Takeaway
🎯 Key Insight: Since each character knows exactly where to go (via indices), we can place them directly in O(n) time without any searching!
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 15
42.0K Views
Medium Frequency
~8 min Avg. Time
1.9K 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