Linkedin Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




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

The thought is DFS:

private int getListSum(List<NestedInteger> lni, int depth)
{
	int sum = 0;
	NestedInteger ni = null;
	while(lni.hasNext()){
		ni = lni.next();
		if(ni.isInteger()) sum += ni.getInteger() * depth;
		else sum += getListSum(ni.getList(), depth + 1);
	}
	return sum;
}
public int getSum(NestedInteger ni)
{
	if(ni.isInteger()) return ni.getInteger();
	else return getListSum(ni.getList(), 1);
}

- uuuouou February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

else sum += getSum(ni.getList(), depth + 1);

Shouldnt this line be

else sum += getListSum(ni.getList(), depth + 1);

- duskan February 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@duskan,yes, you are right. Thanks for pointing that out, I have corrected it now.

- uuuouou February 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

define a recursive function:

int valueit(NestedInteger root, depth) {
  int val=0;
  if(root.isInteger()) {
    val+=n.getInteger();
  }
  else {
    List<NestedInteger> nlist=n.getList();
    for n in nlist {
      if(n.isInteger()) {
        val+=n.getInteger();
      }
      else {
        val+=valueit(n,depth+1);
      }
    }      
  }
  return val;
}

- samuel February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Fix some errors:

int valueit(NestedInteger root, depth) {
  int val=0;
  if(root.isInteger()) {
    val+=n.getInteger()*depth;
  }
  else {
    List<NestedInteger> nlist=root.getList();
    for n in nlist {
      if(n.isInteger()) {
        val+=n.getInteger()*depth;
      }
      else {
        val+=valueit(n,depth+1);
      }
    }      
  }
  return val;
}

- samuel February 23, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote
# a python implementation {{{ def valueit(root, depth): val=0; if type(root) is int: val+=root*depth else: nlist=root for n in nlist: if type(n) is int: val+=n*depth else: val+=valueit(n,depth+1) return val #--------------------------------------------- d=[1,[4,[6]]] print( valueit(d,1) ) - samuel February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

i can read this code, i just coded mine in a minute, let me know if its wrong.

def getdepth(list, depth):
    sum = 0
    for item in list:
        if type(item) == type(list):
           sum += getDepth(item, depth + 1)
        else:
            sum += item * depth;
    return sum

looks similar to yours

- byteattack June 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def valueit(root, depth):
  val=0;
  if type(root) is int:
    val+=root*depth
  else:
    nlist=root
    for n in nlist:
      if type(n) is int:
        val+=n*depth      
      else:
        val+=valueit(n,depth+1)
  return val



d=[1,[4,[6]]]
print( valueit(d,1) )

- samuel February 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Using javascript:

var total = function (arr, depth) {
                                 if (!depth) depth = 1;
                                 var result = 0;
                                 for (var i = 0; i < arr.length; i++) {
                                     if ( arr[i] instanceof Array) {
                                         result += total(arr[i], ++depth);
                                     } else {
                                         result += arr[i]*depth;
                                     }
                                 }
                                 return result;

                             }

- Anonymous March 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def foo(A):
    return _aux(A, 1)


def _aux(A, weight):
    res = 0
    for item in A:
        if type(item) is list:
            res += _aux(item, weight + 1)
        else:
            res += item * weight
    return res

- shoudaw April 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

private static int GetSum(NestedInteger item, int weight)
        {
            if (item.IsInteger())
            {
                return (int)item.GetInteger()*weight;
            }
            else
            {
                int sum = 0;
                var list = item.GetList();
                foreach (var subItem in list)
                {
                    if (subItem.IsInteger())                    
                        sum += GetSum(subItem, weight);                    
                    else
                        sum += GetSum(subItem, weight + 1);
                }

                return sum;
            }

}}

- Zia July 04, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SumOfNestedLists {

	public static int getSum(List<Object> list) {
		
		int sum = 0;
		for(Object o : list) {
			if(o.getClass() == Integer.class)
				sum += (int)o;
			else if(o.getClass() == LinkedList.class)
				sum += getNestedSum(o, 2);
		}
		
		return sum;
		
	}
	
	private static int getNestedSum(Object o, int level) {
		if(o.getClass() != LinkedList.class) return -1;
		List<Object> list = (List<Object>)o;
		int tempSum = 0;
		
		for(Object io : list) {
			if(io.getClass() == Integer.class)
				tempSum += (level*(int)io);
			else if(io.getClass() == LinkedList.class)
				tempSum += getNestedSum(io, level+1);
		}
		
		return tempSum;
	}
}

- XXX August 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class FindSumByListFlattening {
	@SuppressWarnings("unchecked")
	public static int findSumByDepth(ArrayList<Object> inputList) {
		int sum = 0;
		int currentElementDepth = 1;
		ListIterator<Object> listIterator = inputList.listIterator();
		int currentPosition = 0;
		int resetPoint = 0;
		ArrayList<Object> tempList;
		while (listIterator.hasNext()) {
			Object i = listIterator.next();
			if (!(i instanceof List)) {
				if (resetPoint % 2 == 0)
					currentElementDepth = 1;
				else
					resetPoint++;
				sum += (currentElementDepth * (int) i);
				currentPosition++;

			} else {
				tempList = (ArrayList<Object>) i;
				listIterator.remove();
				currentElementDepth++;
				resetPoint++;
				for (Object obj : tempList) {
					listIterator.add(obj);
				}
			}
			listIterator = inputList.listIterator(currentPosition);
		}
		return sum;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<Object> inputList = new ArrayList<Object>();
		ArrayList<Object> List1 = new ArrayList<Object>();
		inputList.add(1);
		List1.add(4);
		ArrayList<Object> List2 = new ArrayList<Object>();
		List2.add(6);
		List1.add(List2);
		inputList.add(List1);
		// inputList.add(4);
		for (Object obj : inputList) {
			System.out.print(obj + " ");
		}
		System.out.println("Sum: " + findSumByDepth(inputList));
	}

}

- sLion August 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
using namespace std;

int getWeightedSum(const char* str)
{
   int sum = 0;
   int depth = 0;
   for(;*str; str++)
   {
       if (*str == '{')
       {
          depth++;
       }
       else if (*str == '}')
       {
          depth--;
       }
       else if (*str != ',')
       {
          int nested_sum = 0;
          while(*str >= '0' && *str <= '9')
          {
              nested_sum += nested_sum * 10 + (*str - '0');
              str++;
          }
          sum+=nested_sum * depth;
       }
   }
   return sum;
}

int main() {
	printf("%d\n", getWeightedSum("{1, {1,{1,2,{1,2

}"));
return 0;
}

- wjian@yahoo-inc.com September 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findSumByWt(ArrayList<Object> inputList, int depth,int sum){
		// sum=0;
		// depth=1;
		for(int i=0;i<inputList.size();i++){
			Object obj=inputList.get(i);
			if(obj instanceof List){
				sum=findSumByWt((ArrayList<Object>)obj, (depth+1),sum);
			}
			if(obj instanceof Integer){
				sum+=((int)obj*depth);
			}
		}
		return sum;

}

- Anonymous January 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findSumByWt(ArrayList<Object> inputList, int depth,int sum){
		// sum=0;
		// depth=1;
		for(int i=0;i<inputList.size();i++){
			Object obj=inputList.get(i);
			if(obj instanceof List){
				sum=findSumByWt((ArrayList<Object>)obj, (depth+1),sum);
			}
			if(obj instanceof Integer){
				sum+=((int)obj*depth);
			}
		}
		return sum;
	}

- Anonymous January 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class NestedIntegerSum {

    public int sum(NestedInteger root) {
        if (root.isInteger()) {
            return root.getInteger();
        }
        return sum(root.getList(), 1);
    }

    private int sum(List<NestedInteger> nodes, int depth) {
        if (nodes == null || nodes.isEmpty()) {
            return 0;
        }
        int sum = 0;
        for (NestedInteger node : nodes) {
            if (node.isInteger()) {
                sum += node.getInteger() * depth;
            } else {
                sum += sum(node.getList(), depth + 1);
            }
        }
        return sum;
    }
    
}

- Anonymous September 07, 2016 | 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