Program to find dot product of run length encoded vectors in Python

Suppose we have two lists nums1 and nums2. Each of these two lists represents a vector in run-length encoded form. For example, a vector [1, 1, 1, 2, 2, 2, 2] is represented as [3, 1, 4, 2] (because there are 3 ones and 4 twos). We need to find the dot product of these two vectors, which is the sum of element-wise multiplication of items present in two vectors.

So, if the input is like nums1 = [2, 7, 5, 3] and nums2 = [3, 5, 4, 2], then the output will be 109 because:

The vectors are [7, 7, 3, 3, 3, 3, 3] and [5, 5, 5, 2, 2, 2, 2]

Dot product = 7×5 + 7×5 + 3×5 + 3×2 + 3×2 + 3×2 + 3×2 = 35 + 35 + 15 + 6 + 6 + 6 + 6 = 109

Algorithm

To solve this, we will follow these steps:

  • Initialize ans = 0
  • While both nums1 and nums2 are non-empty:
    • Extract val1 and count1 from nums1
    • Extract val2 and count2 from nums2
    • Add (val1 × val2) × min(count1, count2) to ans
    • If count2 > count1, put back remaining elements to nums2
    • If count1 > count2, put back remaining elements to nums1
  • Return ans

Example

Let us see the following implementation to get better understanding:

def solve(nums1, nums2):
    ans = 0
    
    while nums1 and nums2:
        val1 = nums1.pop()
        count1 = nums1.pop()
        val2 = nums2.pop()
        count2 = nums2.pop()
        
        ans += (val1 * val2) * min(count2, count1)
        
        if count2 > count1:
            nums2.append(abs(count2 - count1))
            nums2.append(val2)
        elif count1 > count2:
            nums1.append(abs(count2 - count1))
            nums1.append(val1)
    
    return ans

# Test the function
nums1 = [2, 7, 5, 3]
nums2 = [3, 5, 4, 2]
print(solve(nums1, nums2))
109

How It Works

The algorithm processes pairs of values from the end of each list. In our example:

  • Step 1: Process val1=3, count1=5 and val2=2, count2=4
  • Add 3×2×4 = 24 to result
  • Since count1 > count2, put back count1-count2=1 and val1=3 to nums1
  • Step 2: Process remaining elements until both lists are empty

This approach efficiently calculates the dot product without expanding the vectors, making it memory-efficient for large run-length encoded vectors.

Conclusion

This algorithm efficiently computes the dot product of run-length encoded vectors by processing pairs of (count, value) elements and handling overlapping segments. The time complexity is O(n+m) where n and m are the lengths of the input lists.

Updated on: 2026-03-26T16:52:36+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements