#1528

Shuffle String

Easy
ArrayStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a similar approach as the brute force but is more efficient in terms of clarity and execution. We directly assign characters to their new positions in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an empty array of the same length as s.
  2. 2Step 2: Loop through each index and character in s simultaneously.
  3. 3Step 3: Assign each character to its new position in the result array using the indices array.
  4. 4Step 4: Convert the result array back to a string and return it.
solution.py5 lines
1def shuffleString(s, indices):
2    result = [''] * len(s)
3    for i in range(len(s)):
4        result[indices[i]] = s[i]
5    return ''.join(result)

Complexity note: The time complexity is O(n) because we make a single pass through the string and indices. The space complexity is O(n) due to the auxiliary array used to store the result.

  • 1Understanding the relationship between indices and characters is crucial.
  • 2Using an auxiliary array helps manage character placement effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.