Similar Problems

Similar Problems not available

Shuffle String - Leetcode Solution

Companies:

LeetCode:  Shuffle String Leetcode Solution

Difficulty: Easy

Topics: string array  

Shuffle String is a problem that requires us to rearrange a given string based on an integer array representing the indices of each character in the original string. We are asked to return the shuffled string.

For example, if the given string is "codeleet" and the integer array is [4,5,6,7,0,2,1,3], then the shuffled string would be "leetcode".

One simple solution for this problem would be to create an empty string of the same length as the given string. We would then iterate through the indices array, and for each index i, we would append the character at the corresponding index i in the given string to the shuffled string.

Here is the detailed solution:

  1. Define a function named "restoreString" that takes two parameters: a string "s" and an integer array "indices".
  2. Create an empty string "shuffled" of the same length as the given string "s".
  3. Iterate through the indices array using a for loop. For each index "i" in the indices array, perform the following steps: a) Get the character at the corresponding index "i" in the given string "s", and store it in a variable "char". b) Append the character "char" to the shuffled string "shuffled".
  4. Return the shuffled string.

Here is the Python code for the solution:

def restoreString(s, indices): shuffled = [None] * len(s) for i in range(len(s)): shuffled[indices[i]] = s[i] return ''.join(shuffled)

Explanation:

In this solution, we create an empty list "shuffled" of the same length as the given string "s" using the following code:

shuffled = [None] * len(s)

This creates a list with "None" values, which we will later fill in with the characters from the given string "s" based on the indices array. Next, we iterate through the indices array using a for loop, and for each index "i" in the indices array, we get the character at the corresponding index "i" in the given string "s" using the following code:

char = s[i]

We then store this character in the "shuffled" list at the index given by the "i"th value in the indices array using the following code:

shuffled[indices[i]] = char

Finally, we join the characters in the "shuffled" list to form a string using the following code:

''.join(shuffled)

This returns the shuffled string as the output of the function.

Shuffle String Solution Code

1