Parent and Child Counts for Every Node
Updated
Problem statement
Each row of pairs is a directed relationship [parent,child]. Return a count of direct parents and direct children for every represented node.
For this exercise, assume a represented node is any ID appearing as either endpoint. Count distinct immediate neighbor IDs: repeated copies of a pair have no effect. These counts do not include more distant ancestors or descendants.
For this exercise, assume cycles and self-loops are allowed. A self-loop contributes one to both the parent count and child count of its node.
For this exercise, assume the result consists of rows [node,parentCount,childCount], sorted by increasing numeric node ID. Empty input returns an empty array.
Function
parentChildCounts(pairs: int[][]) → int[][]Examples
Example 1
pairs = [[1,3],[2,3],[3,4]]return = [[1,0,1],[2,0,1],[3,2,1],[4,1,0]]Node 3 has two distinct direct parents and one direct child. Roots 1 and 2 still receive their own rows.
Example 2
pairs = [[7,9],[7,9],[9,7],[7,7]]return = [[7,2,2],[9,1,1]]This cyclic graph counts each distinct relationship once; the self-loop contributes once to both degree columns of node 7.
Constraints
- For this exercise, assume
0 <= pairs.length <= 1000. - Each row contains exactly two positive integer IDs, each at most
10^9. - Repeated records are permitted; counts use distinct directed relationships.
More Karat interview questions
- Do Two Nodes Share a Proper Ancestor?PHONE SCREEN · Seen Sep 2021
- Validate a Latin-Square MatrixPHONE SCREEN · Seen Aug 2020
- Validate a Nonogram GridPHONE SCREEN · Seen Aug 2020
- Nodes With Zero or One ParentPHONE SCREEN · Seen May 2020
- Lowest Common Ancestor in a Rooted TreeONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Rooms With Two Other Entrances and a Treasure SuccessorWalmart · PHONE SCREENWalmart interview questions
- People with Zero or One ParentIndeed · PHONE SCREENIndeed interview questions
- Nodes With Zero or Three ParentsCompass International Holdings · PHONE SCREENCompass International Holdings interview questions
- Mutual-Friend Referral RecommendationsFireworks AI · PHONE SCREEN · ONSITE INTERVIEW
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Top K Users by Distinct ContactsGoogle · PHONE SCREENGoogle interview questions
- Assign Campers to the First Arriving CarAtlassian · PHONE SCREENAtlassian interview questions
- Resource Transition ProbabilitiesWhatNot · PHONE SCREENWhatNot interview questions
- Find Every Reachable Derived Vocabulary WordDuolingo · PHONE SCREENDuolingo interview questions
- Order Employees by a Reports-To HierarchyBloomberg LP · PHONE SCREENBloomberg LP interview questions