VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-the-values-of-first-list-using-second-list/

⇱ Sort the values of first list using second list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort the values of first list using second list

Last Updated : 23 Jul, 2025

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:

  • Maintain a frequency array for list2, say freqList2[] to store the frequency of positions in list2.
  • Now, calculate the prefix sum of all the elements in freqList2[] to get the last position where an element with position = list2[i], will be stored.
  • Maintain a temp array to store the sorted list of characters.
  • Iterate from i = N-1 to 0, and for every position find the character to be put from list1 and the exact position to be put at from freqList2[].
  • Copy the sorted list temp[] back to list1[].

Below is the implementation of the algorithm:


Output
a d h b c e i f g 

Time Complexity: O(N), where N is the length of list.
Auxiliary Space: O(N)

Comment