LeetCode Solutions

339. Nested List Weight Sum

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int depthSum(vector<NestedInteger>& nestedList) {
    int ans = 0;
    int depth = 0;
    queue<NestedInteger> q;

    addIntegers(q, nestedList);

    while (!q.empty()) {
      ++depth;
      for (int sz = q.size(); sz > 0; --sz) {
        const NestedInteger ni = q.front();
        q.pop();
        if (ni.isInteger())
          ans += ni.getInteger() * depth;
        else
          addIntegers(q, ni.getList());
      }
    }

    return ans;
  }

 private:
  void addIntegers(queue<NestedInteger>& q,
                   const vector<NestedInteger>& nestedList) {
    for (const NestedInteger& ni : nestedList)
      q.push(ni);
  }
};
			

class Solution {
  public int depthSum(List<NestedInteger> nestedList) {
    int ans = 0;
    int depth = 0;
    Queue<NestedInteger> q = new ArrayDeque<>();

    addIntegers(q, nestedList);

    while (!q.isEmpty()) {
      ++depth;
      for (int sz = q.size(); sz > 0; --sz) {
        final NestedInteger ni = q.poll();
        if (ni.isInteger())
          ans += ni.getInteger() * depth;
        else
          addIntegers(q, ni.getList());
      }
    }

    return ans;
  }

  private void addIntegers(Queue<NestedInteger> q, List<NestedInteger> nestedList) {
    for (final NestedInteger ni : nestedList)
      q.offer(ni);
  }
}
			

class Solution:
  def depthSum(self, nestedList: List[NestedInteger]) -> int:
    ans = 0
    depth = 0
    q = deque()

    def addIntegers(nestedList: List[NestedInteger]) -> None:
      for ni in nestedList:
        q.append(ni)

    addIntegers(nestedList)

    while q:
      depth += 1
      for _ in range(len(q)):
        ni = q.popleft()
        if ni.isInteger():
          ans += ni.getInteger() * depth
        else:
          addIntegers(ni.getList())

    return ans