algoadvance

Problem Statement

2363. Merge Similar Items

You are given two 2D lists items1 and items2, where each list contains items represented as pairs [value, weight]. Merge the two lists into a single list of unique items, summed by their weights. Output the merged list sorted by the value of the items.

Clarifying Questions

  1. Input Format: Can items1 or items2 be empty?
    • Yes, they can be empty.
  2. Element Uniqueness: Are the values in each of the input lists unique?
    • Values may repeat within the lists, but the goal is to merge them by summing their weights.
  3. Output Requirements: Should the result be sorted by the value of the items?
    • Yes, the result should be sorted by the item values in ascending order.

Strategy

  1. Data Structure Choice: Use a dictionary to facilitate the merging process. The dictionary’s keys will be the item values, and the values will be the cumulative weights.

  2. Processing:
    • Iterate through items1 and items2, and for each item, update the dictionary with the item value as the key and sum the weights.
    • Convert the dictionary back to a list of [value, weight] pairs.
    • Sort the merged list by the item values.
  3. Sorting: Python’s in-built sorted() function efficiently sorts the list.

Code

def mergeSimilarItems(items1, items2):
    # Initialize a dictionary to store the merged items
    merged_items = {}

    # Function to add items to the dictionary
    def add_items_to_dict(items):
        for value, weight in items:
            if value in merged_items:
                merged_items[value] += weight
            else:
                merged_items[value] = weight

    # Add items from both lists to the dictionary
    add_items_to_dict(items1)
    add_items_to_dict(items2)

    # Convert the dictionary to a sorted list of pairs
    merged_list = [[value, weight] for value, weight in merged_items.items()]
    merged_list.sort()

    return merged_list

# Test the function with an example
items1 = [[1, 1], [4, 5], [3, 8]]
items2 = [[3, 1], [1, 5]]
print(mergeSimilarItems(items1, items2))
# Output: [[1, 6], [3, 9], [4, 5]]

Time Complexity

Thus, the overall time complexity is O((n + m) + k log k), which should be efficient for most reasonable input sizes.

This solution ensures that the items are merged appropriately and sorted by their values as required.

Try our interview co-pilot at AlgoAdvance.com