Problem
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:
- If a key only exists in one object, that single key-value pair should be included in the object.
- If a key is included in both objects, the value in the object from
arr2should override the value fromarr1.
Examples
Example 1
| |
Example 2
| |
Example 3
| |
Constraints
arr1andarr2are valid JSON arrays- Each object in
arr1andarr2has a unique integeridkey 2 <= JSON.stringify(arr1).length <= 10^62 <= JSON.stringify(arr2).length <= 10^6
Solution
Method 1 – Hash Map Merge and Sort
Intuition
We want to merge two arrays of objects by their id field, combining properties and letting arr2 override arr1 for duplicate keys. Using a hash map allows efficient merging and lookup.
Approach
- Create a hash map to store objects by their
id. - Insert all objects from
arr1into the map, usingidas the key. - For each object in
arr2, merge it with the existing object in the map (if any), witharr2’s values taking precedence. - Collect all merged objects, sort them by
idin ascending order, and return as an array.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + m + k log k)— n and m are the lengths of arr1 and arr2, k is the number of unique ids (for sorting). - 🧺 Space complexity:
O(n + m)— For the hash map and result array.