8x8 Interview Question
Applications DevelopersCountry: United States
public class NestedWeightedSum {
static int sum =0;
static int boolean shouldUseBFS = false;
static int boolean shouldUseDFS = true;
public void bfs(List<NestedInteger> nestedList) {
Queue<NestedInteger> queue = new LinkedList<>();
for (NestedInteger nestedInt : nestedList) {
queue.offer(nestedInt);
}
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
depth++;
for (int i = 0; i < size; i++) {
NestedInteger nestedInt = queue.poll();
if (nestedInt.isInteger()) {
sum += nestedInt.getInteger() * depth;
} else {
for (NestedInteger innerInt : nestedInt.getList()) {
queue.offer(innerInt);
}
}
}
}
}
public int depthSum(List<NestedInteger> nestedList) {
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
if(shouldUseBFS){
bfs(nestedList);
}
if(shouldUseDFS){
dfs(nestedList,0);
}
return sum;
}
public void dfs(List<NestedInteger> nestedList,int depth){
for(NestedInteger list: nestedList){
if(list.isInteger()){
sum += list.getInteger() * depth;
}
else {
dfs(list.getList(),depth + 1);
}
}
}
}
func sum(of array: [Any], level: Int = 1) -> Int {
guard array.isEmpty == false else { return 0 }
var runningSum = 0
for item in array {
if let intValue = item as? Int {
runningSum += intValue * level
} else if let array = item as? [Any] {
runningSum += sum(of: array, level: level + 1)
} else {
assertionFailure("Unexpected/Unhandled type")
}
}
return runningSum
}
sum(of: [1,[4,[6]]])
public int depthSum(const List<NestedInteger>& nestedList) {
- v^2 June 23, 2020sum = 0;
std::stack<std::pair<NestedInteger, int>> listStack;
listStack.push(std::make_pair(listStack, 1);
do {
const auto [currentList, depth] = listStack.pop();
for (const auto& listItem : currentLsit) {
if (listItem.isInteger() {
sum += depth * currentList.isInteger();
} else {
listStack.push(std::make_pair(listItem, depth + 1));
}
}
} while (!listStack.empty());
return sum;
}