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.
items1 or items2 be empty?
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.
items1 and items2, and for each item, update the dictionary with the item value as the key and sum the weights.[value, weight] pairs.sorted() function efficiently sorts the list.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]]
items1 and items2, respectively. This is because we iterate through both lists once.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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?