Editor

Count the Leaves

#215 · Trees · Beginner · 30 XP · about 5 min

A discussion thread is a tree. Comment 0 is the original post, and every other comment is a reply to exactly one earlier comment. The list replies_to stores the whole thread: replies_to[i] is the number of the comment that comment i answers, and replies_to[0] is -1 because the post answers nobody.

Write count_leaves(replies_to) that returns how many comments have no replies at all. In tree words these comments are the leaves: the nodes with no children.

Examples

count_leaves([-1, 0, 0, 1])  # returns 2
count_leaves([-1, 0, 1, 2])  # returns 1
count_leaves([-1])  # returns 1

In the first thread, comments 1 and 2 answer the post and comment 3 answers comment 1. Nobody answered comments 2 and 3, so there are 2 leaves. In the last thread the post has no replies, so the post itself is a leaf.

Note

  • There is always at least one comment, the post.
  • For every reply, replies_to[i] is a number from 0 to i - 1, and a comment can get any number of replies.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.