Relative Sorting Efficient Code
In this class, We discuss Relative Sorting Efficient Code.
Readers can prepare an entire competitive coding course to crack product development companies. Click Here.
The reader should have basic coding skills to work with competitive coding. Click here.
Question:
Given two arrays, arr1 and arr2, of size N and M.
Sort the first array based on the relative position of elements in the first array, the same as the elements’ positions in the second array.
Note: If elements are repeated in arr2. Consider the first occurrence position.
Example:
arr1 = [2, 1, 2, 1, 5, 3, 6, 7, 4]
arr2 = [5, 1, 2, 9]
Output: [5, 1, 1, 2, 2, 3, 4, 6, 7]
Time Complexity: O(nlogn)
Space Complexity: O(n)
Logic:
Using hashing, we can do this example in the specified time.
The reader should have the basics of hash table data structure.
The hash table finds the required element in O(1).
We maintain the element and element count in the hash table as key-value pair.
In Python, we use a dictionary to maintain key-value pairs.
Read the elements from arr2.
We append the value to the list if the element is present in the dictionary.
We append the value based on the count present in the hash table.
The step-by-step explanation is provided in the video.
In Python collections, we have a counter class.
The counter class creates the element and its count in the dictionary.
Code: