## 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,]]".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
return total_sum

findSum(l)
return total_sum``````

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

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

Add a Comment
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.

Learn More

### 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.

Learn More

### Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

### Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More