## Interview Question for SDE-2s

Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public static void main(String[] args) {
System.out.println(nestedList_LeetCode_364("[1,1[1,[1,1],1,[1]]]".toCharArray()));
}

public static int nestedList_LeetCode_364(char[] string) {
int sum = 0;
Stack<String> stack = new Stack<>();
int index = 0;
int level = 0;
while (index < string.length) {
if (Character.isDigit(string[index]) || string[index] == '[') {
stack.push("" + string[index]);
if (string[index] == '[') {
level = Math.max(1, level - 1);
}
} else if (string[index] == ']' && !stack.isEmpty()) {
int tempSum = 0;
while (!stack.isEmpty() && !stack.peek().equals("[")) {
tempSum = tempSum + Integer.valueOf(stack.pop());
}
sum = sum + (tempSum * level++);
stack.pop();
}
index++;
}
return sum;
}``````

Can anybody offer a better solution pls ? Please don't change the method signature

Comment hidden because of low score. Click to expand.
0
of 0 vote

@koustav.adorable, the input is a list of integers, not a string, please note. I have a solution involving two-pass. First pass is to find the maxDepth of the nested list and the second pass is to sum up the numbers using max-depth. Can probably be done in a clever way using one-pass but I'll have to think about it. Outlining my solution in Python below:

``````def sumList(l):
if not l:
return 0

max_d = -1
def maxDepth(nums, d=1):
nonlocal max_d
for x in nums:
if type(x) == list:
maxDepth(x, d+1)
else:
max_d = max(max_d, d)

maxDepth(l)

total_sum = 0
def findSum(nums, maxDepth=max_d):
nonlocal total_sum
for x in nums:
if type(x) == list:
total_sum += findSum(x, maxDepth - 1)
else:
total_sum += x

findSum(l)

Comment hidden because of low score. Click to expand.
0

There is error in your code. in findSum() need to multiple by maxDepth while calculating sum.

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.