#2722

Join Two Arrays by ID

Medium
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In this approach, we use a HashMap to store objects from both arrays based on their id. This allows us to merge them efficiently in a single pass, reducing the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap to store merged objects by id.
  2. 2Step 2: Loop through arr1 and add each object to the HashMap using its id as the key.
  3. 3Step 3: Loop through arr2 and for each object, merge it with the existing object in the HashMap if the id exists.
  4. 4Step 4: Convert the HashMap values to an array.
  5. 5Step 5: Sort the array based on the id.
solution.py10 lines
1def join_arrays(arr1, arr2):
2    merged_map = {}
3    for obj in arr1:
4        merged_map[obj['id']] = obj
5    for obj in arr2:
6        if obj['id'] in merged_map:
7            merged_map[obj['id']].update(obj)
8        else:
9            merged_map[obj['id']] = obj
10    return sorted(merged_map.values(), key=lambda x: x['id'])

Complexity note: The time complexity is O(n) because we make a single pass through both arrays to build the HashMap, and then another pass to sort the results.

  • 1Using a HashMap allows for efficient merging of objects by id.
  • 2Sorting the final result ensures the output is in the desired order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.