arr1
and arr2
are always given and are both non-empty?arr2
always contain distinct integers, and will all elements of arr2
be present in arr1
?arr1
that do not appear in arr2
be handled in the final sorted array?arr1
and arr2
?arr1
?arr1
and arr2
?With these questions, we can comprehend the requirements and constraints needed to tailor an efficient solution for this problem.
Let’s assume the following until further details are provided:
arr2
will only contain unique values, and each of these values will definitely be present in arr1
.arr1
not in arr2
should be sorted in ascending order at the end of the output list.arr2
: Use a dictionary to map each element in arr2
to its index, which will help in ordering elements of arr1
that are present in arr2
.arr1
:
arr2
and sort them using the mapping from the dictionary.arr2
and sort them in ascending order.arr2
and the sorted elements not in arr2
.arr2
will take (O(n2)) time, where (n2) is the length of arr2
.arr1
and categorizing elements will take (O(n1)) time, where (n1) is the length of arr1
.arr1
that are not in arr2
will take (O(m \log m)) time, where (m) is the number of elements in arr1
not found in arr2
.Hence, the overall complexity will be (O(n1 + m \log m + n2)), which simplifies to (O(n \log n)) in the worst case where n
is the length of arr1
.
def relativeSortArray(arr1, arr2):
# Create a mapping from arr2 to its indices
order_map = {val: idx for idx, val in enumerate(arr2)}
# Function to get sort key
def sort_key(val):
if val in order_map:
return (0, order_map[val]) # Elements in arr2 are prioritized
else:
return (1, val) # Elements not in arr2 are sorted naturally
# Sort arr1 using the custom key
arr1.sort(key=sort_key)
return arr1
# Example usage
arr1 = [2,3,1,3,2,4,6,7,9,2,19]
arr2 = [2,1,4,3,9,6]
print(relativeSortArray(arr1, arr2)) # Output: [2,2,2,1,4,3,3,9,6,7,19]
In the given code:
arr2
.sort_key
function ensures that elements present in arr2
are prioritized and sorted according to their indices.arr2
are sorted naturally in ascending order.Feel free to run this code with different inputs to verify its correctness!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?