Click here to see the problem details.
This problem is quite simple. We will be given a string (s) and an array (indices) that is the same length as the string. All of the integers of the array are unique, and of course, all the integers will be less or equal to the string’s index value.
We have to shuffle each string’s character based on the arrays element. As problem description, “The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.”
After that, we have to return the final shuffled string.
Let’s see a small example. Our given string is ‘cab’ and array is [2, 0, 1]. So our final result will be ‘abc’. As per rule, the position of the c character is 0 and indices = 2, so c will be at the 2nd position in the final result. And rest of the characters will follow the same rule.
The solution is so straightforward and self-explanatory. If you know the basic Python, you can easily understand it. And no doubt, the code is better than my awful explanation. It will be quite understandable. Let’s see the solution.
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: shuffled = [None] * len(s) for i in range(len(s)): shuffled[indices[i]] = s[i] return ''.join(shuffled)
There are many solutions to this problem. I hope this one will help you.
This answer will be accepted. Before submitting an answer, try to understand the whole thing. And try to go through the code with a simple test case for better understanding. It helps a lot.