LinkedIn Interview

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-06-11Added By Anonymous
Source: Link

I recently completed first round of interview with LinkedIn, where I was asked to solve the following problem.


Given a list of node integers, I have to calculate the total weights of the list. The weight calculated as follows,

{{1,2},2,{1,2}} = 1x1 + 2x1 + 1x1 + 2x2 + 2x2 = 8


i.e. innermost depth multiplier is 1, in this case it is {1,2} & {1,2} and a layer outer to that multiplier is 2, in this case it is 2



similarly for,

{{1,2}, 3, {4, {6}, 5}} = 6x1 + 4x2 + 5x2 + 3x3 + 1x2 + 2x2


I know I have to solve maxDepth first (by first recursion) and then use recursion (second) by reducing the depth by 1 on each inner level. But, instead of implementing the solution I tried to simplify it further by calculating the weight and depth in single recursive call. Eventually timed out. Feeling sad for missing this simple problem which I know can be solved in less than 10 mins. I actually solved the problem after the interview in 5 mins but of no use. Not sure if it is the only approach or any other better approach is available.

// implementation of NodeInteger


public class NodeInteger {

// returns true if this node has integer rather list

public isInteger();


// returns the integer this node holds

public getInteger();


// returns the list of child NodeIntegers

public getList();


}

My solution (in Java)

public int weight(List input) {

int maxDepth = getDepth(input);

return getWeight(input, maxDepth);

}

public int getDepth(List input) {

int depth = 1;

for(NodeInteger ni : input) {

if(ni.getList() != null) {

int maxDepth = 1 + getDepth(ni.getList());

depth = Math.max(maxDepth, depth);

}

}

return depth;

}

public int getWeight(List input, int depth) {

int sum = 0;

for (NodeInteger ni : input) {

if (ni.isInteger()) {

sum += ni.getInteger() * depth;

} else {

sum += getWeight(input, depth - 1);

}

}

return sum;

}

Comments