Member-only story

Leetcode 1528: Shuffle String

Pierre-Marie Poitevin
2 min readJul 30, 2020

--

I tried to write the solution in most backend languages (JavaScript being the main exception I believe). I wrote the solution for C, C++, Java, Kotlin, PHP, Golang and Python. The problem is not particularly difficult and can be translate in pseudo language:

function shuffle (String s, int[] indices) 
-> returns shuffled string
let res a new string to store the result
let l the length of the string s
for i integer from 0 to l - 1
res[indices[i]] <- s[i]
return res

Notes on implementation

  1. Languages handle string manipulation, and memory allocations differently. In some cases it is easier to handle arrays of chars rather than the strings.
  2. The time complexity should be O(l) with l the length of the string unless we copy the string at each step, which makes the time complexity O(l²)
  3. Space complexity is O(l) to store res

Java

Use StringBuilder in Java to avoid a copy at each step.

class Solution {
public String restoreString(String s, int[] indices) {
StringBuilder res = new StringBuilder(s);
int l = s.length();
for (int i = 0; i < l; i++) {
res.setCharAt(indices[i], s.charAt(i));
}
return res.toString();
}
}

C++

Update characters using array style.

class Solution {
public:
string restoreString(string s…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet