Two-Color an Undirected Graph
Updated
Problem statement
You are given n nodes, numbered from 0 through n - 1, and an array edges of undirected edges. Give every node one of two colors. Return whether you can do this so that the two ends of every edge get different colors.
Each entry edges[i] = [u, v] is an undirected edge that joins nodes u and v.
Function
canTwoColor(n: int, edges: int[][]) → booleanExamples
Example 1
n = 4edges = [[0,1],[1,2],[2,3],[3,0]]return = trueGive nodes 0 and 2 one color, and nodes 1 and 3 the other. Every edge of the square joins two different colors, so the answer is true.
Example 2
n = 3edges = [[0,1],[1,2],[2,0]]return = falseThe three nodes form an odd cycle. Whatever color node 0 gets, nodes 1 and 2 both need the other color. But they share an edge, so no coloring works and the answer is false.
Example 3
n = 5edges = [[0,1],[2,3],[3,4]]return = trueThe graph has two separate parts: a single edge, and a short path. Color each part on its own, switching colors along every edge. The same two colors work for both parts, so the answer is true.
More Apple Phone Screen questions
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
- Maintain a Consistent-Hashing RingPHONE SCREEN · Seen Oct 2026
- Count Nodes in a ChainPHONE SCREEN · Seen Oct 2026
- Run-Length DecodingPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Course ScheduleAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Possible BipartitionByteDance · PHONE SCREENByteDance interview questions
- Route Graph Reachability with a Broken LinkFigma · PHONE SCREENFigma interview questions
- Count Friend CirclesOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Number of IslandsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Count Connected IslandsUber · PHONE SCREENUber interview questions
- Course ScheduleNykaa · PHONE SCREENNykaa interview questions
- Number of IslandsSpaceX · PHONE SCREENSpaceX interview questions
- Pacific Atlantic Water FlowAnduril · PHONE SCREENAnduril interview questions
- Detonate Bombs with Chain ReactionsAirbnb · PHONE SCREENAirbnb interview questions
Apple interview experiences
- Apple SWE Phone Screen: Subarray Products: 1 Experience
- Apple New Grad SWE Java, Coding and Manager Rounds: 1 Experience
- Apple AI Coding and Related Interviews: 17 Experiences
- Apple India SWE New Grad Interviews: 5 Experiences
- Apple New Grad SWE Phone Screens: 12 Experiences (Part 3 of 3)
- Apple New Grad SWE and Embedded: 16 Experiences (Part 2 of 3)