Magicsheet logo

Shuffle String

Easy
12.5%
Updated 8/1/2025

Asked by 4 Companies

Shuffle String

What is this problem about?

The Shuffle String interview question gives you a string s and an integer array indices of the same length. Character s[i] should be placed at position indices[i] in the resulting string. Return the rearranged string. This is a straightforward array permutation/index-mapping problem.

Why is this asked in interviews?

Apple, Microsoft, Amazon, and Google ask this as a beginner-level warm-up to test basic array indexing and string construction. It validates that candidates can perform index-based rearrangement without confusing source and destination indices, and that they build the result cleanly without modifying the input in-place in a way that corrupts the mapping.

Algorithmic pattern used

The pattern is index-mapped array construction. Create a result array res of the same length as s. For each index i, place s[i] at res[indices[i]]. After processing all characters, join res into a string and return it. This is O(n) time and O(n) space. The key is to write to res[indices[i]] (the destination) from s[i] (the source) — not the reverse.

Example explanation

s = "aiohn", indices = [3, 1, 4, 2, 0].

  • i=0: s[0]='a' → res[3]='a'.
  • i=1: s[1]='i' → res[1]='i'.
  • i=2: s[2]='o' → res[4]='o'.
  • i=3: s[3]='h' → res[2]='h'.
  • i=4: s[4]='n' → res[0]='n'.

res = ['n','i','h','a','o'] → "nihao".

Common mistakes candidates make

  • Confusing source and destination: writing res[i] = s[indices[i]] instead of res[indices[i]] = s[i] — a subtle direction reversal that gives a different permutation.
  • Modifying s in-place — string characters are immutable in Python; use a list for res.
  • Not initializing res with the correct size — res = [''] * len(s) or res = [None] * len(s).
  • Converting back to string using str(res) (gives "['n', 'i', ...]") instead of "".join(res).

Interview preparation tip

For the Shuffle String coding problem, the array index string interview pattern is the simplest one-pass rearrangement. The key conceptual clarification: indices[i] tells you WHERE to PUT s[i], not WHERE TO GET the character for position i. Google and Apple interviewers use this as a 2-minute warm-up — solve it instantly with res[indices[i]] = s[i] and move on. Practice the inverse: if asked for res[i] = s[indices[i]] (the reverse mapping) — know which direction maps source to destination vs. destination to source. This clarity about index direction is tested in many permutation and mapping problems.

Similar Questions