Skip to main content

Shuffle String - Solution & Explanation

EasyArrayString11 min readAsked at: Microsoft, Google
Practice this problem

Problem Statement

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.

 

Example 1:

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

Example 2:

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.

Approach Overview

Problem Overview: You are given a string s and an integer array indices of the same length. Each position in indices tells you where the character at that position in s should appear in the final string. The task is to reconstruct the shuffled string after applying all index mappings.

Approach 1: Array Construction (O(n) time, O(n) space)

The direct solution builds a new character array of size n. Iterate through the string once, and for each index i, place s[i] into position indices[i] of the result array. After the loop finishes, convert the array back to a string. The key insight is that indices already tells you the exact final position of every character, so there is no need for searching or shifting. Every element is processed exactly once, giving O(n) time complexity and O(n) extra space for the result array.

This approach is clean, readable, and works consistently across languages. It relies on basic operations like array indexing and iteration, which makes it ideal when working with arrays and strings. Most production code would use this version because clarity outweighs the small extra memory cost.

Approach 2: In-place Array Modification (O(n) time, O(1) extra space)

You can avoid allocating a separate array by performing swaps until each character reaches its correct index. Iterate through the array, and while indices[i] != i, swap the character at position i with the character at position indices[i]. At the same time, swap the corresponding values in the indices array so the mapping stays consistent. Each swap moves at least one element into its correct position, so the total work remains linear.

This technique treats the problem as a permutation correction. The indices array describes a permutation of positions, and swaps gradually fix cycles in that permutation. Because all rearrangement happens inside the existing arrays, the algorithm runs in O(n) time with O(1) extra space. The tradeoff is slightly more complex logic and careful swap handling.

Recommended for interviews: The array construction approach is what most interviewers expect first. It demonstrates that you quickly recognized the direct mapping between source and destination indices. After presenting it, mentioning the in-place permutation idea shows deeper understanding of array manipulation and space optimization. Interviewers typically accept the O(n) time, O(n) space solution as optimal because it keeps the code simple and avoids unnecessary complexity.

Approach 1: Approach 1: Array Construction

This approach involves iterating over the given string and indices, creating a new array that simulates the shuffled string by placing each character at its target index as specified in the indices array.

The solution uses a new array to shuffle characters. We allocate space for the shuffled string and iterate through the 'indices' array, placing each character from the original string 's' into its new position in 'shuffled.' Finally, remember to null-terminate the shuffled string.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string. We iterate over the string once.
Space Complexity: O(n) due to the additional array used for the shuffled string.

Try this approach in the editor →

Approach 2: Approach 2: In-place Array Modification

This in-place approach involves swapping characters within the original string transformed to a mutable data structure. This technique reduces additional space usage by modifying the existing characters' positions based on indices, ensuring the shuffled sequence is derived directly.

The method involves converting the string into a list for mutable operations. Swapping is performed both on characters and their indices until each character reaches its target position, maintaining a time complexity generally dependent on the swapping constraints rather than individual searches.

Code

Python

Complexity

Time Complexity: O(n) in a typical scenario but can more expensive based on swaps.
Space Complexity: O(1) if the initial space for list conversion is ignored since swaps are in place.

Try this approach in the editor →

Approach 3: Simulation

We create a character array or string ans of the same length as the input string, then iterate through the string s and place each character s[i] at position indices[i] in ans. Finally, we join the character array or string ans to form the final result and return it.

The time complexity is O(n) and the space complexity is O(n), where n is the length of the string.

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Array Construction

Time Complexity: O(n), where n is the length of the string. We iterate over the string once.
Space Complexity: O(n) due to the additional array used for the shuffled string.

Approach 2: In-place Array Modification

Time Complexity: O(n) in a typical scenario but can more expensive based on swaps.
Space Complexity: O(1) if the initial space for list conversion is ignored since swaps are in place.

Simulation—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Array ConstructionO(n)O(n)Best general solution. Simple implementation and easy to explain in interviews.
In-place Array ModificationO(n)O(1)When memory is constrained or when demonstrating knowledge of permutation swaps.

Video Solution

Shuffle String (LeetCode 1528) | Full solution with diagrams | Easy Explanation • Nikhil Lohia • 8,706 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Shuffle String easy or hard?
Shuffle String is classified as an Easy problem on LeetCode with a high acceptance rate of around 85%. The challenge mainly checks whether you recognize the direct index mapping and implement a linear-time reconstruction.
How to solve Shuffle String in O(n)?
Create a character array of the same length as the input string. Loop through the indices array, and place s[i] into result[indices[i]]. After filling all positions, convert the array to a string. Each element is handled once, giving O(n) time complexity.
What is the best approach for Shuffle String?
The best approach is array construction. Iterate through the string once and place each character s[i] at position indices[i] in a new result array. This solution runs in O(n) time with O(n) space and is the most straightforward method expected in coding interviews.
What data structure is used in Shuffle String?
The main data structure is an array (or character array). The indices array acts as a mapping that determines where each character should move in the final string. No advanced structures like hash maps or trees are required.
What is the time complexity of Shuffle String?
The optimal solution runs in O(n) time because each character is processed exactly once. A result array is filled using direct index mapping from the indices array. Space complexity is O(n) for storing the reconstructed string.
Shuffle String Python or Java solution approach?
Both Python and Java solutions follow the same logic: allocate a result array, iterate through the string, and assign result[indices[i]] = s[i]. Python often uses a list of characters before joining into a string, while Java uses a char array for efficient assignment.
Is Shuffle String asked at Google, Amazon, or Meta?
Shuffle String is an Easy-level array and string manipulation problem commonly used for screening rounds and practice. While not among the most frequently reported problems at top companies, similar index-mapping and permutation problems appear in interviews at companies like Amazon and Google.

Ready to solve this problem?

Practice Shuffle String with our built-in code editor and test cases.

Practice on FleetCode