Sunday, March 28, 2021

Representation and dot product of two vectors

 Question:

Given the following vectors (arbitrary numbers), design a more memory-efficient representation of these vectors.

A: [1, 1, 4, 4, 4, 4, 7, 7, 7, 7, 7, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
B: [2, 2, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

Follow-up:
With the vectors represented as suggested, write a function to calculate the dot product of two vectors.

Example:

Input:
A: [1, 1, 4, 4, 4, 4, 7, 7, 7, 7, 7, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
B: [2, 2, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

Output: 291

Explanation: 1 * 2 + 1 * 2 + 4 * 5 + ... + 2 * 3

Additional information:

  • The vectors are guaranteed to contain a large number of duplicate values, similar to the example given above.

======== https://leetcode.com/discuss/interview-question/286446/Representation-and-dot-product-of-two-vectors/271143
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;

vector<vector<int>> rle(vi& A){
    int n = A.size();

    vvi ans;
    int cnt = 0;

    for(int i = 0; i < n;){        
        int curr = A[i];
        while(curr == A[i]){
            i++;
            cnt++;
        }
        ans.push_back({cnt, curr});
        cnt = 0;
    }

    return ans;
}

int dotP(vvi A, vvi B){

    int n = A.size(), m = B.size();
    int i = 0, j = 0;
    int sum = 0;
    while(i < n and j < m){
        vi& p = A[i];
        vi& q = B[j];

        int common = min(p[0], q[0]);// cnt - min(2, 5) = 2

        p[0] -= common;
        q[0] -= common;

        sum += p[1] * q[1] * common;

        if(p[0] == 0)
            i++;
        if(q[0] == 0)
            j++;
    }

    return sum;
}


No comments:

Post a Comment