Problem
Run-length encoding is a compression algorithm that allows for an integer array nums with many segments of consecutive repeated numbers to be represented by a (generally smaller) 2D array encoded. Each encoded[i] = [vali, freqi] describes the ith segment of repeated numbers in nums where
vali is the value that is repeated freqi times.
- For example,
nums = [1,1,1,2,2,2,2,2]is represented by the run-length encoded arrayencoded = [[1,3],[2,5]]. Another way to read this is “three1’s followed by five2’s”.
The product of two run-length encoded arrays encoded1 and encoded2 can be calculated using the following steps:
- Expand both
encoded1andencoded2into the full arraysnums1andnums2respectively. - Create a new array
prodNumsof lengthnums1.lengthand setprodNums[i] = nums1[i] * nums2[i]. - Compress
prodNumsinto a run-length encoded array and return it.
You are given two run-length encoded arrays encoded1 and encoded2
representing full arrays nums1 and nums2 respectively. Both nums1 and
nums2 have the same length. Each encoded1[i] = [vali, freqi] describes the ith segment of nums1, and each encoded2[j] = [valj, freqj] describes the jth segment of nums2.
Return _theproduct of _encoded1 andencoded2.
Note: Compression should be done such that the run-length encoded array has the minimum possible length.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= encoded1.length, encoded2.length <= 10^5encoded1[i].length == 2encoded2[j].length == 21 <= vali, freqi <= 10^4for eachencoded1[i].1 <= valj, freqj <= 10^4for eachencoded2[j].- The full arrays that
encoded1andencoded2represent are the same length.
Solution
Method 1 – Two-Pointer Merge and Compress
Intuition
We can process both run-length encoded arrays with two pointers, multiplying values and compressing the result on the fly. This avoids expanding the arrays and is efficient.
Approach
- Use two pointers to iterate through
encoded1andencoded2. - At each step, multiply the current values and take the minimum frequency.
- Add the product and frequency to the result, merging with the previous if the value is the same.
- Decrement the frequencies and move pointers as needed.
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(N + M)where N and M are the lengths of the encoded arrays. - 🧺 Space complexity:
O(1)extra (output not counted).