Linkedin Interview Question for Software Engineer / Developers


Country: United States




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

public int depthSum (List<NestedInteger> input)
{  
    return depthSumHelper(input, 1);
}

private int depthSumHelper(List<NestedInteger> input, int level){
    int sum = 0;

    // look at each nested integer
    for( NestedInteger nestedInt : input){
        if(nestedInt.isInteger()){
            sum += nestedInt.getInteger() * level;
        } else {
            sum += depthSumHelper(nestedInt.getList(), level++);
        }
    }
    return sum;
}

- Paul Lee November 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 votes

//The above code has an issue with respect to using level++ in the recursion //because for the same level nested integer the level is incremented already
//Here is my attempt
	public int depthSum (List<NestedInteger> input) 
	{ // ur implementation here}
		int finalSum = 0;
		for (NestedInteger nestedInteger : input) {
			finalSum += depthSumInternal(nestedInteger,1);	
		}
		return finalSum;
	}
	private int depthSumInternal(NestedInteger input, int level) {
		int returnSum = 0;
		if(input.isInteger()) return level*input.getInteger();
		for(NestedInteger childInput:input.getList()) {
			int childLevel = level+1;
			returnSum+=depthSumInternal(childInput,childLevel);
		}
		return returnSum;
	}

- anonymous November 06, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Can't you just change it from depth++ to depth + 1 ?

- Vic January 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I agree with what Vic said changing level++ to level + 1 in @Paul example will solve the problem

- <--> January 13, 2016 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Here's a python solution

def calStrWeight( str ):
    currentDepth = 0
    weight = 0

    if len(str)==0:
        return 0

    for i in range(len(str)):

        if currentDepth<0:
            break

        if str[i]=='{':
            currentDepth+=1
        elif str[i]=='}':
            currentDepth-=1
        elif str[i].isdigit():
            weight += int(str[i]) * currentDepth

    return weight

print calStrWeight('{1,{4,{6

}')

- Akkking October 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what if the number has two or more digits ?

- dev January 03, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_val(l_int, depth):
val = 0
for i in l_int:
if isinstance(i, list):
val = val + get_val(i, depth+1)
else:
val = val + depth*i
return val


if __name__ == "__main__":
print get_val([[1,1],[1,1],2], 1)

- Peter November 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_val(l_int, depth):
    val = 0
    for i in l_int:
        if isinstance(i, list):
            val = val + get_val(i, depth+1)
        else:
            val = val + depth*i
    return val
            

if __name__ == "__main__":
    print get_val([[1,1],[1,1],2], 1)

- Peter November 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below is the code which uses the same approach as mentioned above, with added classes and method implementations.

/**
 * This is the interface that represents nested lists. You should not implement
 * it, or speculate about its implementation.
 */
interface NestedInteger {
	/**
	 * @return true if this NestedInteger holds a single integer, rather than a
	 *         nested list
	 */
	boolean isInteger();

	/**
	 * @return the single integer that this NestedInteger holds, if it holds a
	 *         single integer Return null if this NestedInteger holds a nested
	 *         list
	 */
	Integer getInteger();

	/**
	 * @return the nested list that this NestedInteger holds, if it holds a
	 *         nested list Return null if this NestedInteger holds a single
	 *         integer
	 */
	List<NestedInteger> getList();
}

class MyNestedIneteger implements NestedInteger {

	private Integer theSingleInteger;
	private List<NestedInteger> theList;

	public MyNestedIneteger(Integer theSingleInteger, List<NestedInteger> theList) {
		this.theSingleInteger = theSingleInteger;
		this.theList = theList;
	}

	@Override
	public boolean isInteger() {
		return null == theList && null != theSingleInteger;
	}

	@Override
	public Integer getInteger() {
		return theSingleInteger;
	}

	@Override
	public List<NestedInteger> getList() {
		return theList;
	}

	@Override
	public String toString() {

		StringBuilder string = new StringBuilder();

		string.append("{");
		if (null != theSingleInteger) {
			string.append(theSingleInteger);
		}
		if (null != theList) {
			for (NestedInteger current : theList) {
				string.append(", " + current.toString());
			}
		}
		string.append("}");
		return string.toString();
	}

}

public class NestedIntegerSum {

	/**
	 * Given a nested list of integers, returns the sum of all integers in the
	 * list weighted by their depth For example, given the list {{1,1},2,{1,1}}
	 * the function should return 10 (four 1's at depth 2, one 2 at depth 1)
	 * Given the list {1,{4,{6

the function should return 27 (one 1 at depth
* 1, one 4 at depth 2, and one 6 at depth 3)
*/
public static int depthSum(List<NestedInteger> input) {
if (null == input) {
return 0;
} else {
int sum = 0;
for (NestedInteger current : input) {
sum += depthSumNestedInteger(current, 1);
}
return sum;
}

}

private static int depthSumNestedInteger(NestedInteger current, int level) {
System.out.println("current: " + current + " level: " + level);
if (null == current) {
return 0;
} else {
if (current.isInteger()) {
return current.getInteger() * level;
} else {
int tempSum = 0;
if (current.getInteger() != null) {
tempSum = current.getInteger() * level;
}
for (NestedInteger nestedCurrent : current.getList()) {
tempSum += depthSumNestedInteger(nestedCurrent, level + 1);
}
return tempSum;
}
}
}

public static void main(String[] args) {

List<NestedInteger> list1 = new ArrayList<>();
List<NestedInteger> list2 = new ArrayList<>();

NestedInteger nestedInteger1 = new MyNestedIneteger(1, list1);
NestedInteger nestedInteger2 = new MyNestedIneteger(4, list2);
NestedInteger nestedInteger3 = new MyNestedIneteger(6, null);

list1.add(nestedInteger2);
list2.add(nestedInteger3);

List<NestedInteger> input = new ArrayList<>();
input.add(nestedInteger1);

System.out.println(input);
System.out.println(depthSum(input));
}

}

- Bhumik November 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class DepthSumDemoTest {
    public static void main(String[] args) {
        
        //for my test case
        //{{1,1},2,{1,1}}
        List<NestedIntegers> parent = new ArrayList<NestedIntegers>();
        parent.add(new NestedIntegers(2));
        
        List<NestedIntegers> myChild1 = new ArrayList<NestedIntegers>();
        myChild1.add(new NestedIntegers(1));
        myChild1.add(new NestedIntegers(1));
        
        parent.add(new NestedIntegers(myChild1));
       
        
        List<NestedIntegers> myChild2 = new ArrayList<NestedIntegers>();
        myChild2.add(new NestedIntegers(1));
        myChild2.add(new NestedIntegers(1));
        
        parent.add(new NestedIntegers(myChild2));
        System.out.println("sum of all depth is : "+myDepthSum(parent, 1));
        
        // {1,{4,{6

= 27
List<NestedIntegers> myParent2 = new ArrayList<NestedIntegers>();
myParent2.add(new NestedIntegers(1));

List<NestedIntegers> myChild21 = new ArrayList<NestedIntegers>();
myChild21.add(new NestedIntegers(4));

myParent2.add(new NestedIntegers(myChild21));


List<NestedIntegers> myChild22 = new ArrayList<NestedIntegers>();
myChild22.add(new NestedIntegers(6));

myChild21.add(new NestedIntegers(myChild22));
System.out.println("sum of all depth is : "+myDepthSum(myParent2, 1));

}

public static int myDepthSum(List<NestedIntegers> list,int level){
int sum = 0;
for(NestedIntegers entry: list){
if(entry.isSingleInteger()){
sum+=entry.getInteger()*level;
}
else{
sum+=myDepthSum(entry.getList(), level+1);
}
}
return sum;
}
}

interface INestedIntegers{

boolean isSingleInteger();
List<NestedIntegers> getList();
Integer getInteger();

}

class NestedIntegers implements INestedIntegers{
List<NestedIntegers> list = new ArrayList<NestedIntegers>();
Integer singleValue = null;
public NestedIntegers(Integer SingleValue){
this.singleValue = SingleValue;
}
public NestedIntegers(List<NestedIntegers> listValues){
singleValue = null;
this.list = listValues;
}

@Override
public boolean isSingleInteger() {
return singleValue!=null;
}

@Override
public List<NestedIntegers> getList() {
return list;
}

@Override
public Integer getInteger() {
return singleValue;
}

}

- Resh January 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simple recursion. First call with weight=1

public int depthSum (List<NestedInteger> input, int weight) 
{ 
	if (input == null) {
		return 0;
	}
	
	int sum = 0;
	for (NestedInteger elem : input)
	{
		if (elem.isInteger()) {
			sum += weight * elem.getInteger();
		} else {
			sum += depthSum(elem.getList(), weight+1);
		}
	}
	
	return sum;

}

- pavel.kogan January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's a python solution

def calStrWeight( str ):
    currentDepth = 0
    weight = 0

    if len(str)==0:
        return 0

    for i in range(len(str)):

        if currentDepth<0:
            break

        if str[i]=='{':
            currentDepth+=1
        elif str[i]=='}':
            currentDepth-=1
        elif str[i].isdigit():
            weight += int(str[i]) * currentDepth

    return weight

print calStrWeight('{1,{4,{6

}')

- Akkking October 20, 2015 | Flag Reply


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