Problem Description
Given two run-length encoded arrays, encoded1 and encoded2, each representing full arrays where each element is defined by a pair [value, frequency], compute the element-wise product of the two underlying arrays and then compress the result back into a run-length encoded format with the minimum possible length.
Key Insights
- Use a two-pointer technique to process both encoded arrays simultaneously without expanding them to the full arrays.
- Multiply corresponding segments of values and determine the overlapping frequency (minimum of the current frequencies).
- Maintain optimal compression by merging consecutive segments having the same product.
- Reduce frequencies and move pointers forward as segments get fully used.
Space and Time Complexity
Time Complexity: O(n + m), where n and m are the lengths of encoded1 and encoded2, respectively. Space Complexity: O(n + m) for the output in the worst case, though typically the output will be compressed and smaller.
Solution
We use a two-pointer approach to iterate over the two run-length encoded arrays simultaneously. At each step, we take the minimum frequency from the current segments and compute the product of their values. We then append or merge this product to the result run-length encoded array. After processing the overlapping segment, we subtract the used frequency from both segments and move the pointer forward when a segment is exhausted. This avoids the costly operation of expanding the arrays and ensures an optimal and compressed result.