![]() |
VOOZH | about |
Given two lists, sort the values of one list using the second list.
Examples:
Input: list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Output: [‘a’, ‘d’, ‘h’, ‘b’, ‘c’, ‘e’, ‘i’, ‘f’, ‘g’]
Explanation: Since 'a', 'd' and 'h' have value = 0 in list 2, therefore they occur first, then 'b', 'c', 'e' and 'i' have values = 1 so they occur next and at last occurs 'f' and 'g' which have values = 2.Input: list1 = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'], list2 = [ 0, 1, 1, 0, 1, 2, 2, 2, 0, 1, 1, 0, 1]
Output: ['g', 'k', 'g', 'k', 'e', 'e', 's', 'e', 'e', 's', 'f', 'o', 'r']
Explanation: Since 'g' and 'k' have value = 0 in list2, therefore they occur first, then 'e' and 's' have value = 1 in list2 so they occur next and at last occurs 'f', 'o' and 'r' which have values = 2.
Approach: To solve the problem, follow the below idea:
The problem can be solved using the same idea as Counting Sort. Maintain a map to store the frequency of list2. After that we can take the prefix sum of the array to get the ending index for every position. We can maintain a new list to store all the sorted elements. So, we traverse the list2 from right to left and find the respective position from list2. Now, we check the prefix sum array to find the index and put the character at that place. Similarly, we can traverse the whole array and finally copy it back to list2.
Step-by-step algorithm:
Below is the implementation of the algorithm:
a d h b c e i f g
Time Complexity: O(N), where N is the length of list.
Auxiliary Space: O(N)