Skip to the code
cf.
+10 XP

#3 Count Every Reply

easy

A discussion widget stores a thread as one comment object { id, replies }, where replies is an array of comment objects with the same shape. Replies can have replies of their own, as deep as people keep answering.

Write countComments(thread) that returns how many comments the thread holds, counting the top comment itself.

Example 1

Input: thread = {"id":1,"replies":[{"id":2,"replies":[]},{"id":3,"replies":[{"id":4,"replies":[]}]}]}
Output: 4

Comment 1 has replies 2 and 3, and 3 has reply 4: four comments.

Example 2

Input: thread = {"id":7,"replies":[]}
Output: 1

A comment with no replies is a thread of one.

Constraints

  • The thread has between 1 and 1000 comments.
  • Nesting is at most 100 levels deep.
  • Every comment has a replies array (it may be empty).
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).