LeetCode 2722: Join Two Arrays by ID Solution

Master LeetCode problem 2722 (Join Two Arrays by ID), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2722. Join Two Arrays by ID

Medium

Problem Explanation

Explanation

To solve this problem, we will iterate over both input arrays and merge the objects based on their id keys. We will use a hash map to store the merged objects based on their id. When merging two objects with the same id, we will prioritize the values from arr2 over arr1. Finally, we will convert the hash map to a list and sort it based on the id key.

  • Time complexity: O(n)
  • Space complexity: O(n)

Solution Code

import java.util.*;

class Solution {
    public List<Map<String, Object>> joinArrays(List<Map<String, Object>> arr1, List<Map<String, Object>> arr2) {
        Map<Integer, Map<String, Object>> mergedMap = new HashMap<>();
        
        for (Map<String, Object> obj : arr1) {
            mergedMap.put((Integer) obj.get("id"), obj);
        }
        
        for (Map<String, Object> obj : arr2) {
            int id = (Integer) obj.get("id");
            if (mergedMap.containsKey(id)) {
                Map<String, Object> mergedObj = mergedMap.get(id);
                for (Map.Entry<String, Object> entry : obj.entrySet()) {
                    mergedObj.put(entry.getKey(), entry.getValue());
                }
            } else {
                mergedMap.put(id, obj);
            }
        }
        
        List<Map<String, Object>> result = new ArrayList<>(mergedMap.values());
        result.sort(Comparator.comparingInt(obj -> (Integer) obj.get("id")));
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2722 (Join Two Arrays by ID)?

This page provides optimized solutions for LeetCode problem 2722 (Join Two Arrays by ID) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2722 (Join Two Arrays by ID)?

The time complexity for LeetCode 2722 (Join Two Arrays by ID) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2722 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2722 in Java, C++, or Python.

Back to LeetCode Solutions