# Tensor linearization interview question [closed]

I got the following question in a coding interview for machine learning engineer position.

Write a function:

vector<int> solution(vector<int> &P, vector<int> &Q);


that given a zero-indexed, tensor P which is linearized consisting of M integers and a zero-indexed array Q consisting of N integers representing the size of each dimension of the tensor. It returns an array of integers where each element of the output tensor is the mean of the corresponding element in the input, P, and its neighbor in each dimension. We can treat non-existent neighbors with zero value. Non existent neighbor means neighbor which are outside the tensor dimension. If we wish we can round up the values of the output arrays.

For example:

If P is [1,2,3,4,5,6] and Q is [1,2,3] the P represents the linearization of tensor with an inner-most dimension of 3 and an outer dimension size of 1.

Test case:

[[44,14,92,6],[2,2,1,1]] Expected output: [17,7,16,12]

I was unable to find the solution. If anyone has any idea about the question please share it in the comment box.

• I'm not very good at C++, so I was having trouble implementing this, but I think I can give you a hint. To solve this problem you need to think about what the array looks like when expanded to its original dimension. I think of [[44,14,92,6],[2,2,1,1]] as a 2D array with a depth of 1 and a "time dimension" of 1. We need to fill in the elements of the expanded array. Start in the first dimension and dig into the structure. In the index [0,0,0,0] we have value 44. Similarly, [0,1,0,0]->14. Then [1,0,0,0]->92, and [1,1,0,0]->6. Now we can calculate the means in the output. – nwsteg Feb 10 at 19:27
• The length of the depth and time dimensions is 1, so they have no neighbors and we use zeros. Thus the first element in the output is given by (44 + 0 + 0 + 0 + 0 + 14 + 0 + 92 + 0)/9 = 16.667, and rounding to the nearest integer gives 17. Similarly, for the second output, compute (14 + 0 + 0 + 0 + 0 + 44 + 0 + 6 + 0)/9 = 7.111, which rounds to 7. – nwsteg Feb 10 at 19:30
• To program this, the tricky part is definitely finding the neighbors of a given element from P. To do this, you need to convert the index in P to the corresponding list of indices of the expanded n-dimensional array. That way you can determine the neighbors by simping adding/subtracting 1 from each dimension. – nwsteg Feb 10 at 19:32
• FYI, if you finish the problem, please edit your answer with the coded solution, as I'd love to see how this is done in c++ :) – nwsteg Feb 10 at 19:34