Count Linked-List Islands
Updated
Problem statement
You are given several heads of finite, acyclic singly linked lists. Different lists may share node objects. Once two lists reach the same node, their remaining suffix is therefore shared.
Two heads belong to the same island when their reachable lists share at least one node. Return the number of distinct islands represented by the given heads.
Indexed representation
Nodes are identified by indices from 0 through next.length - 1. For node i, next[i] is the index of its next node, or -1 when i is a tail. Each value in heads is the index of one list head.
Duplicate heads and heads that point into the middle of another list are allowed. They do not create an additional island.
Function
countLinkedListIslands(next: int[], heads: int[]) → intExamples
Example 1
next = [1,2,-1,4,2,-1]heads = [0,3,5]return = 2The lists beginning at 0 and 3 merge at node 2, so both end at tail 2 and form one island. Head 5 ends at a different tail and forms the second island.
Example 2
next = [1,-1,3,1,-1]heads = [0,2,4,3]return = 2Heads 0, 2, and 3 all reach tail 1. Head 4 reaches tail 4, so there are two islands.
Constraints
1 <= next.length <= 200000.1 <= heads.length <= 100000.- Every
next[i]is-1or a valid node index. - Every
heads[i]is a valid node index. - Following
nextfrom any node eventually reaches-1; no list contains a cycle.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Copy a Doubly Linked List with a Special PointerMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Merge Event PreferencesAirbnb · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Mutual-Friend Referral RecommendationsFireworks AI · PHONE SCREEN · ONSITE INTERVIEW
- LRU CacheApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- LRU CacheServiceNow · PHONE SCREEN · ONSITE INTERVIEWServiceNow interview questions
- Package Install OrderVerily · ONSITE INTERVIEW
- LRU CacheLotusFlare · ONSITE INTERVIEW
- LRU CacheJP Morgan Chase · ONSITE INTERVIEWJP Morgan Chase interview questions