Join Two Arrays by ID - Problem
Imagine you're working as a data analyst for a social media company. You have two datasets containing user information, and you need to combine them into a single, comprehensive view of your users.
Given two arrays arr1 and arr2, where each object contains an id field with an integer value, your task is to join these arrays based on their IDs, similar to how databases perform JOIN operations.
Key Requirements:
- ๐ Merge by ID: Objects with the same
idshould be combined into one - ๐ Property Override: When properties conflict, values from
arr2take precedence - ๐ฏ Preserve Unique: Objects that exist in only one array remain unchanged
- ๐ Sort Result: Final array must be sorted by
idin ascending order
This problem tests your understanding of hash tables, object merging, and data processing - essential skills for backend development and data engineering roles!
Input & Output
example_1.py โ Basic merge with overlapping IDs
$
Input:
arr1 = [{"id": 1, "x": 1}, {"id": 2, "x": 9}]
arr2 = [{"id": 3, "x": 5}]
โบ
Output:
[{"id": 1, "x": 1}, {"id": 2, "x": 9}, {"id": 3, "x": 5}]
๐ก Note:
No overlapping IDs, so simply combine all objects and sort by ID (1, 2, 3).
example_2.py โ Property override from arr2
$
Input:
arr1 = [{"id": 1, "name": "Alice", "age": 25}]
arr2 = [{"id": 1, "age": 26, "city": "NYC"}]
โบ
Output:
[{"id": 1, "name": "Alice", "age": 26, "city": "NYC"}]
๐ก Note:
Same ID (1) exists in both arrays. Properties are merged: 'name' from arr1, 'age' overridden by arr2 value (26), and 'city' added from arr2.
example_3.py โ Complex merge scenario
$
Input:
arr1 = [{"id": 2, "a": 1, "b": 2}, {"id": 3, "a": 5, "c": 6}]
arr2 = [{"id": 1, "b": 3, "c": 4}, {"id": 2, "a": 2}]
โบ
Output:
[{"id": 1, "b": 3, "c": 4}, {"id": 2, "a": 2, "b": 2}, {"id": 3, "a": 5, "c": 6}]
๐ก Note:
ID 1: only in arr2, kept as-is. ID 2: exists in both, 'a' overridden (1โ2), 'b' kept from arr1. ID 3: only in arr1, kept as-is. Final result sorted by ID.
Constraints
- 1 โค arr1.length, arr2.length โค 1000
-
Each object guaranteed to have an integer
idfield - 0 โค id โค 105
- All IDs within each array are unique
- Objects may contain various property types (string, number, boolean, null)
Visualization
Tap to expand
Understanding the Visualization
1
Create Index
Build a hash map (like a filing system) with employee IDs as keys
2
Add Base Records
Insert all records from the first table into your index
3
Merge Updates
For each record in the second table, either merge with existing or add new
4
Generate Report
Extract all records from index and sort by employee ID
Key Takeaway
๐ฏ Key Insight: Hash maps provide O(1) lookups, making the join operation efficient. Like having a perfectly organized filing system where you can instantly find and update any employee record by their ID!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code