Shuffle String with Python and Javascript

Created on Aug 14, 2020
Updated on Sep 28, 2020

Shuffle String is an easy leetcode problem, please invest some time in understanding and implementing at leetcode first and then come back here again to see how we can approach it.

How to Approach such Problem

We need to pair each item in the indices list to each character in the string; we can do that by zipping indices to the string. Try to print zip(indices, s) in python which gives you an object pairing each element to the other.

But what does object represent? To know that we need to convert that object to dictionary which contains tuples of key-value pairs so for example 4 is associated to ‘c’ and 5 is linked to the value ‘o’ which means the character ‘c’ will be in the 4th index (5th position because python is 0-indexed) and ‘o’ will be at the 6th position. That’s why we’ve used dict() for this conversion.

This dictionary has now list of tuples, each tuple contains position and character that we should put at that position. If we sort this dictionary based on its positions we end up with sorted list of tuples that has all characters with associated positions. That can be done by using sorted() function which by default sorts that dictionary according to its keys

Next is to loop over each character and concatenate them all to construct the final word. You’ve now shuffled the string and here is my implementations in Python and Javascript.

Python

Javascript

Other problem-solving stuff

If you want to see more problem-solving blog posts, check out:

https://www.ezzeddinabdullah.com/categories/problem-solving