Leetcode 2363: Merge Similar Items

grid47
grid47
Exploring patterns and algorithms
Mar 15, 2024 5 min read

You are given two 2D integer arrays, items1 and items2, each representing a set of items. Each item has a value and a weight. You need to combine both arrays by summing the weights of items with the same value, and return the result as a 2D array, sorted by the item values in ascending order.
Problem
Approach
Steps
Complexity
Input: The input consists of two 2D arrays, items1 and items2. Each array contains pairs of integers where the first integer is the item's value and the second integer is the item's weight.
Example: items1 = [[2,3],[5,7],[4,1]], items2 = [[4,2],[2,4]]
Constraints:
• 1 <= items1.length, items2.length <= 1000
• items1[i].length == items2[i].length == 2
• 1 <= valuei, weighti <= 1000
• Each valuei in items1 is unique.
• Each valuei in items2 is unique.
Output: The output should be a 2D array where each element is a pair [value, weight], where the weight is the sum of weights of all items with the same value. The result should be sorted by value in ascending order.
Example: [[2,7],[4,3],[5,7]]
Constraints:
Goal: We need to combine the items from both arrays and sum the weights for the same values, then return the sorted result.
Steps:
• Create a map to store the value and weight pairs.
• Iterate through the items of the first array and add the value-weight pairs to the map.
• For each item in the second array, check if the value already exists in the map. If it does, add the weight; if it doesn't, create a new entry.
• Convert the map to a 2D array and sort it by the value.
Goal: Constraints ensure that the number of items and their values are within manageable limits.
Steps:
• 1 <= items1.length, items2.length <= 1000
• 1 <= valuei, weighti <= 1000
Assumptions:
• The value of each item is unique within the respective arrays.
• Each array contains at least one item.
Input: Input: items1 = [[2,3],[5,7],[4,1]], items2 = [[4,2],[2,4]]
Explanation: Here, the item with value 2 has a weight of 3 in items1 and a weight of 4 in items2, so the total weight becomes 7. Similarly, for value 4, the total weight is 3 (1 from items1 and 2 from items2). After merging, the result is sorted by the values: [[2,7],[4,3],[5,7]].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus