Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
nums1andnums2are non-empty:- Extract
val1andcount1fromnums1 - Extract
val2andcount2fromnums2 - Add
(val1 × val2) × min(count1, count2)toans - If
count2 > count1, put back remaining elements tonums2 - If
count1 > count2, put back remaining elements tonums1
- Extract
- 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=5andval2=2, count2=4 - Add
3×2×4 = 24to result - Since
count1 > count2, put backcount1-count2=1andval1=3tonums1 - 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.
