Leetcode #1868: Product of Two Run-Length Encoded Arrays
In this guide, we solve Leetcode #1868 Product of Two Run-Length Encoded Arrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Two Pointers
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: encoded1 = [[1,3],[2,3]], encoded2 = [[6,3],[3,3]]
Output: [[6,6]]
Explanation: encoded1 expands to [1,1,1,2,2,2] and encoded2 expands to [6,6,6,3,3,3].
prodNums = [6,6,6,6,6,6], which is compressed into the run-length encoded array [[6,6]].
Python Solution
class Solution:
def findRLEArray(
self, encoded1: List[List[int]], encoded2: List[List[int]]
) -> List[List[int]]:
ans = []
j = 0
for vi, fi in encoded1:
while fi:
f = min(fi, encoded2[j][1])
v = vi * encoded2[j][0]
if ans and ans[-1][0] == v:
ans[-1][1] += f
else:
ans.append([v, f])
fi -= f
encoded2[j][1] -= f
if encoded2[j][1] == 0:
j += 1
return ans
Complexity
The time complexity is O(n) (after optional sort O(n log n)). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.