Minimum Distance Matching in a Forest
Updated
Problem statement
edges describes an undirected forest with uniquely labeled integer nodes. Match every label in left to a distinct label in right.
The cost of a pair is the number of forest edges on their path. Nodes in different trees cannot be paired. right may contain extra labels that remain unused.
Return the minimum total distance of a valid one-to-one matching, or -1 when no matching covers every label in left.
Function
minimumForestMatchingDistance(edges: int[][], left: int[], right: int[]) → intExamples
Example 1
edges = [[1,2],[2,3],[2,4],[5,6]]left = [1,3]right = [4,2]return = 3Either pairing has total distance 3.
Example 2
edges = [[1,2],[3,4]]left = [1,3]right = [4,2]return = 2Pair 1 with 2 and 3 with 4; the right-array order need not be preserved.
Example 3
edges = [[1,2],[3,4]]left = [1,2]right = [3,4]return = -1Every possible pair crosses disconnected trees.
Constraints
1 <= edges.length <= 200000.- The graph is an undirected forest with no duplicate edge.
- Every query label appears in at least one edge.
1 <= left.length <= right.length <= 12.- Labels within each query array are unique.
More Scale AI Onsite Interview questions
- Task Scheduler with DependenciesONSITE INTERVIEW · Seen Jul 2026
- Best Poker Category with a JokerPHONE SCREEN · ONSITE INTERVIEW · Seen Jun 2026
- Format and Validate a Model ResponseONSITE INTERVIEW · Seen Apr 2026
- Stateful Neuron Matrix UpdateONSITE INTERVIEW · Seen Apr 2026
- Clock Hand Angle with Subsecond PrecisionONSITE INTERVIEW · Seen Dec 2025
- Four-Player Matching Card GameONSITE INTERVIEW · Seen Feb 2025
- Rotate an Array to the RightONSITE INTERVIEW · Seen Oct 2024
- Rich-Text Segment Normalization and Bold ToggleONSITE INTERVIEW · Seen Apr 2024
- Shortest Distance Between Two NodesONSITE INTERVIEW · Seen Jan 2024
- Fit Beta Parameters by Maximum LikelihoodONSITE INTERVIEW · Seen Sep 2022
Similar questions at other companies
- Shortest Round Trip Through All DeliveriesGoogle · ONSITE INTERVIEWGoogle interview questions
- Shortest Path Visiting All NodesInMobi · ONSITE INTERVIEWInMobi interview questions
- Grid Robot Route with Charging PrioritiesUber · PHONE SCREEN · ONSITE INTERVIEWUber interview questions
- Maximum Currency Conversion Along a Simple PathRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Minimum Semesters With Course CapacityAmazon · ONSITE INTERVIEW
- Minimum Semesters with a Course LimitSnowflake · PHONE SCREENSnowflake interview questions
- Minimum Traveling Salesperson TourGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- Drone Delivery with Battery Swap StationsCisco · OACisco interview questions
- Longest Anchored Song ChainIntuit · OAIntuit interview questions
- Cheapest Visiting Order with PrerequisitesIndeed · OAIndeed interview questions