Member-only story
Leetcode 1528: Shuffle String
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
- Languages handle string manipulation, and memory allocations differently. In some cases it is easier to handle arrays of chars rather than the strings.
- 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 complexityO(l²)
- Space complexity is
O(l)
to storeres
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…