#Linkedin screening round question
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-04-20Added By Anonymous
Source: Link
/** Suppose you are given a class that implements a k-dimensional array
•interface and you want to perform an operation that requires you to
•iterate over all elements of the array using its indices. To be
•specific, let's assume we want to calculate the sum of all elements in
•the array. The interface only provides you a getDims() method that
•returns an array of sizes (maximum index values + 1) for each dimension
•and a get(int[]) method that fetches the element at the location specified
•by the indices along each dimension
•
•For example, suppose the class implements a 4D arrays, and the getDims()
•method returns [3, 2, 5, 1]. Then [2, 1, 3, 0] describes a valid index
•array, and a call to get([2, 1, 3, 0]) provides you with array[2][1][3][0],
•
•Write a function that given an instance of the k-D array class as above,
•calculates the sum of all elements.
•
•@param m instance of MultiDimArray class that implements a k-D array of
1 ints that provides a method m.getDims() of index non-inclusive
2 upper bounds and a method m.get(int[]) to get the element
3 located at the indices in its array argument•@return an int which is the sum of all elements in the k-D array
•
•example: Given object m that holds a 2x2x3 array
•a=[[[3, 2, 2], [1, 5, 0]], [[2, 0, 1], [1, 1, -2]]] (only for example;
•this need not be the internal implementation of our k-D array),
•the function call arraySum(m) should return 16 = 3+2+2+1+5+2+1+1+1-2
•*/
I gave this answer but got rejected
public interface MultiDimArray {
int[] getDims(); // [2, 2, 3]
int get(int[] indices); // m.get([0,0,0]) = 3
}
public int arraySum (MultiDimArray m) {
//Implementation here
int[] dim = m.getDims();
int[] temp = new int[dim.length];
return backtrack(dim,m,0, temp);
}
private int backtrack(int[] dim,MultiDimArray m, int curr, int[] temp ){
int sum =0;
if(curr == dim.length-1){
for(int i =0;i<dim[curr];i++){
temp[curr] =i;
sum+= m.get(temp);
}
return sum;
}
for(int i = 0;i<dim[curr];i++){
temp[curr] = i;
sum + = backtrack(dim, m, curr+1, temp);
}
return sum;
}
Any idea whats the most effient way of doing this ?
Any idea whats the most effient way of doing this ?