Similar Problems

Similar Problems not available

Merge Similar Items - Leetcode Solution

Companies:

LeetCode:  Merge Similar Items Leetcode Solution

Difficulty: Easy

Topics: hash-table sorting array  

Problem:

You are given a list of items. Each item is a pair of string and integer, representing the name and price of an item, respectively. You need to merge the items that have the same name. If two or more items have the same name, their prices should be summed up, and the resulting item should have the same name but the total price. Return a list of merged items.

Example:

Input: items = [["item1", 10], ["item2", 15], ["item1", 3], ["item4", 7], ["item2", 6], ["item3", 18]]

Output: [["item1", 13], ["item2", 21], ["item3", 18], ["item4", 7]]

Solution:

This problem can be easily solved using a dictionary. We can iterate through each item in the list and check if the name of the item is already present in the dictionary. If the name is present, we add the price of the current item to the price of the item with the same name in the dictionary. If the name is not present, we add the current item to the dictionary.

Finally, we convert the dictionary into a list of lists, where each inner list contains the name and price of an item. This list is the final output.

Here's the Python code for the solution:

def merge_items(items): merged_items = {} for item in items: name = item[0] price = item[1] if name in merged_items: merged_items[name] += price else: merged_items[name] = price return [[name, price] for name, price in merged_items.items()]

items = [["item1", 10], ["item2", 15], ["item1", 3], ["item4", 7], ["item2", 6], ["item3", 18]] print(merge_items(items))

Output: [['item1', 13], ['item2', 21], ['item4', 7], ['item3', 18]]

Time Complexity: O(n) Space Complexity: O(n)

Merge Similar Items Solution Code

1