KatInterview

Dot Product of Two Run-Length Encoded Vectors

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingtwo-pointersrun-length-encodingsimulation

Last updated

Compute the dot product of two run-length encoded integer vectors by walking both run lists together, without expanding them into full arrays.

Dot Product of Run-Length Encoded Vectors

A long integer vector often contains stretches of equal values. To save memory, such a vector can be stored as a list of runs, where each run is a pair [value, count] meaning that value appears count times in a row. For example, [[1, 2], [3, 1]] stands for the vector [1, 1, 3].

You are given two vectors in this run-length form, first and second. Return their dot product: the sum of products of the elements at matching positions of the two expanded vectors.

Do not build the expanded vectors. Your solution should depend on the number of runs, not on the expanded length.

Details

  • The run boundaries of the two vectors usually do not line up, so a run in one vector may span several runs in the other.
  • Runs are processed in the order given.
  • If one vector is exhausted before the other (different expanded lengths), only the positions covered by both vectors contribute. Positions beyond the shorter vector add nothing.
  • If either list is empty, the result is 0.
  • A run with count equal to 0 contributes nothing.
  • Values may be zero or negative.

Function

Implement run_length_dot(first, second) which returns the dot product as an integer.

Constraints

  • Each expanded vector can have up to 10^6 elements, while each list has far fewer runs (around 10^3).
  • Every run is a two-element list [value, count] with integer value and non-negative integer count.
  • Results fit in Python's arbitrary-precision integers.

Examples

Example 1

Input: run_length_dot([[1, 2], [3, 1]], [[2, 1], [1, 2]])

Output: 6

Example 2

Input: run_length_dot([[5, 10]], [[2, 5], [3, 5]])

Output: 125

Hints

Hint 1

Expanding both vectors costs time and memory proportional to the expanded length. Think about what the product looks like over a stretch where both vectors are constant.

Hint 2

Keep one pointer per vector and a counter of how many elements remain in the current run of each. The next aligned stretch has length equal to the smaller of the two counters.

Hint 3

After consuming a stretch, subtract its length from both counters. Whichever counter reaches zero moves its pointer to the next run. Use two independent checks so that both can advance at once.