Problem Description
Given two arrays arr1
and arr2
, return a new array joinedArray
. All the objects in each of the two inputs arrays will contain an id
field that has an integer value. joinedArray
is an array formed by merging arr1
and arr2
based on their id
key. The length of joinedArray
should be the length of unique values of id
. The returned array should be sorted in ascending order based on the id
key. If a given id
exists in one array but not the other, the single object with that id
should be included in the result array without modification. If two objects share an id
, their properties should be merged into a single object, where values from arr2
override those from arr1
.
Key Insights
- Each input array contains objects with unique
id
values. - The result should handle merging objects with the same
id
by prioritizing values fromarr2
. - Sorting the final result based on the
id
is necessary. - Efficiently merging the two arrays can be achieved using a hash map.
Space and Time Complexity
Time Complexity: O(n + m), where n is the length of arr1
and m is the length of arr2
, due to the need to iterate through both arrays and construct the result.
Space Complexity: O(n + m) for storing the merged results in a hash map and then converting it to a list.
Solution
To solve this problem, we can use a hash map (dictionary) to store the merged objects based on their id
. We will iterate through both arr1
and arr2
, adding each object to the hash map. If an id
exists in both arrays, we will merge the properties, ensuring that properties from arr2
take precedence. Finally, we will extract the values from the hash map, sort them based on the id
, and return the result.