FastPrepTwo-Color an Undirected Graph

Two-Color an Undirected Graph

Apple logoApple● MediumNEW GRADPHONE SCREEN

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[][]) → boolean

Examples

Example 1

n = 4edges = [[0,1],[1,2],[2,3],[3,0]]return = true

Give 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 = false

The 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 = true

The 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

Similar questions at other companies

Apple interview experiences

All Apple interview questionsSee Apple hiring insights
Saved
class Solution {
    public boolean canTwoColor(int n, int[][] edges) {
        // write your code here
    }
}
Checking account…