Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to shuffle string with given indices in Python
Suppose we have a string s and a list of indices ind, they are of same length. The string s will be shuffled such that the character at position i moves to indices[i] in the final string. We have to find the final string.
So, if the input is like s = "ktoalak" and ind = [0,5,1,6,2,4,3], then the output will be "kolkata".
To solve this, we will follow these steps ?
fin_str:= a list whose size is same as s and fill with empty strings-
for each index i and character v in s, do
fin_str[ind[i]] := v
join each character present in fin_str and return
Example
Let us see the following implementation to get better understanding ?
def solve(s, ind):
fin_str = [''] * len(s)
for i, v in enumerate(s):
fin_str[ind[i]] = v
return "".join(fin_str)
s = "ktoalak"
ind = [0,5,1,6,2,4,3]
print(solve(s, ind))
kolkata
Step-by-Step Breakdown
Let's trace through the algorithm with our example ?
def solve_with_steps(s, ind):
print(f"Original string: {s}")
print(f"Indices mapping: {ind}")
fin_str = [''] * len(s)
print(f"Initial result array: {fin_str}")
for i, v in enumerate(s):
fin_str[ind[i]] = v
print(f"Step {i+1}: Place '{v}' at position {ind[i]} ? {fin_str}")
result = "".join(fin_str)
print(f"Final result: {result}")
return result
s = "ktoalak"
ind = [0,5,1,6,2,4,3]
solve_with_steps(s, ind)
Original string: ktoalak Indices mapping: [0, 5, 1, 6, 2, 4, 3] Initial result array: ['', '', '', '', '', '', ''] Step 1: Place 'k' at position 0 ? ['k', '', '', '', '', '', ''] Step 2: Place 't' at position 5 ? ['k', '', '', '', '', 't', ''] Step 3: Place 'o' at position 1 ? ['k', 'o', '', '', '', 't', ''] Step 4: Place 'a' at position 6 ? ['k', 'o', '', '', '', 't', 'a'] Step 5: Place 'l' at position 2 ? ['k', 'o', 'l', '', '', 't', 'a'] Step 6: Place 'a' at position 4 ? ['k', 'o', 'l', '', 'a', 't', 'a'] Step 7: Place 'k' at position 3 ? ['k', 'o', 'l', 'k', 'a', 't', 'a'] Final result: kolkata
Alternative Approach Using Dictionary
We can also solve this using a dictionary for cleaner code ?
def solve_dict(s, ind):
char_map = {ind[i]: char for i, char in enumerate(s)}
return "".join(char_map[i] for i in range(len(s)))
s = "ktoalak"
ind = [0,5,1,6,2,4,3]
print(solve_dict(s, ind))
kolkata
Conclusion
String shuffling with indices involves creating a new array and placing each character at its designated position. Both the list-based and dictionary approaches provide efficient solutions with O(n) time complexity.
