Relative Sort Array in Python

Suppose we have two arrays arr1 and arr2, where elements of arr2 are unique, and all elements in arr2 are also present in arr1. We need to sort the elements of arr1 such that the relative ordering of items follows the sequence in arr2. Elements not present in arr2 should be placed at the end in ascending order.

For example, if arr1 is [2,3,1,3,2,4,6,7,9,2,19] and arr2 is [2,1,4,3,9,6], the result will be [2,2,2,1,4,3,3,9,6,7,19].

Algorithm

To solve this, we follow these steps −

  • Create a frequency map to count occurrences of each element in arr1
  • Define two arrays: res (result) and temp (for remaining elements)
  • For each element in arr2, add it to res based on its frequency in arr1
  • Collect remaining elements (not in arr2) in temp
  • Sort temp and append to res

Implementation

class Solution:
    def relativeSortArray(self, arr1, arr2):
        # Create frequency map for arr1
        freq_map = {}
        for num in arr1:
            freq_map[num] = freq_map.get(num, 0) + 1
        
        result = []
        remaining = []
        
        # Add elements in order of arr2
        for num in arr2:
            for _ in range(freq_map[num]):
                result.append(num)
            freq_map[num] = 0
        
        # Collect remaining elements not in arr2
        for num, count in freq_map.items():
            if count > 0:
                for _ in range(count):
                    remaining.append(num)
        
        # Sort remaining elements and add to result
        remaining.sort()
        result.extend(remaining)
        
        return result

# Test the solution
solution = Solution()
arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19]
arr2 = [2, 1, 4, 3, 9, 6]
print(solution.relativeSortArray(arr1, arr2))
[2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]

Alternative Approach Using Counter

We can simplify the frequency counting using Python's Counter from the collections module ?

from collections import Counter

def relativeSortArray(arr1, arr2):
    # Count frequencies
    counter = Counter(arr1)
    result = []
    
    # Add elements in arr2 order
    for num in arr2:
        result.extend([num] * counter[num])
        del counter[num]
    
    # Add remaining elements in sorted order
    for num in sorted(counter.keys()):
        result.extend([num] * counter[num])
    
    return result

# Test the function
arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19]
arr2 = [2, 1, 4, 3, 9, 6]
print(relativeSortArray(arr1, arr2))
[2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]

How It Works

The algorithm maintains the relative order by:

  • Step 1: Counting frequency of each element in arr1
  • Step 2: Processing elements in the order they appear in arr2
  • Step 3: Adding remaining elements in ascending order

Time Complexity

The time complexity is O(n log n) where n is the length of arr1, due to sorting the remaining elements. The space complexity is O(n) for storing the frequency map and result array.

Conclusion

The relative sort array problem is efficiently solved using frequency mapping and custom ordering. The Counter approach provides cleaner code while maintaining the same time complexity.

Updated on: 2026-03-25T07:22:25+05:30

851 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements