We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Join Two Arrays by ID

Difficulty: Medium


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 from arr2.
  • 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.


Code Solutions

def join_arrays(arr1, arr2):
    merged_dict = {}
    
    # Merge arr1 into the dictionary
    for obj in arr1:
        merged_dict[obj['id']] = obj
    
    # Merge arr2 into the dictionary, overriding where necessary
    for obj in arr2:
        if obj['id'] in merged_dict:
            merged_dict[obj['id']].update(obj)
        else:
            merged_dict[obj['id']] = obj
    
    # Convert dictionary to a list and sort by id
    joined_array = list(merged_dict.values())
    joined_array.sort(key=lambda x: x['id'])
    
    return joined_array
← Back to All Questions