mediumArraysPattern: New or Existing ID
Merge And Sort Segments Solution
Problem Statement
You are given an array of arrays `segments`, where each inner array represents a segment of scores with a specific ID. Each segment has the same number of scores (at most 3). The task is to create a new merged array with overall scores for each segment, where the score of each segment is the sum of its individual scores, and sort them in descending order. All scores are non-negative integers.
Examples
Example 1:
Input:[[{"id":1,"scores":[10,20,30]},{"id":2,"scores":[40,50]},{"id":3,"scores":[60,70,80]}]]
Output:[{"id":3,"score":210},{"id":1,"score":60},{"id":2,"score":90}]
Explanation: Sum of scores for each segment and sort them in descending order
Constraints
- Each segment can have at most 3 test scores.
- The scores can be in the range of 0-100.
- All segment IDs are unique.
- Array size is ≤ 10^5.
- The scores are non-negative integers.
Time: O(n log n) Space: O(n)
The optimal approach is to first calculate the sum of scores for each segment, and then sort these segments based on their scores in descending order. This approach uses a hash map to store the sum of scores for each segment, allowing for constant-time lookups and updates. The time complexity of this approach is O(n log n) due to the sorting step.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
