Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Split people who dislike each other

Medium · Target 15 minutes · Graphs · Type asked atAmazonGoogle

There are n people, labelled 1 to n. Each pair [a, b] in dislikes means a and b must not be in the same room. There are two rooms, of any size. Return true if everyone can be placed, and false otherwise.

Examples

InputOutputWhy
n = 4, dislikes = [[1,2],[1,3],[2,4]]trueRoom one {1, 4}, room two {2, 3}.
n = 3, dislikes = [[1,2],[1,3],[2,3]]falseThree people who all dislike each other need three rooms.
n = 6, dislikes = [[1,2],[3,4],[5,6],[2,3],[4,5],[6,1]]trueA cycle of six alternates: {1, 3, 5} and {2, 4, 6}.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ dislikes.length ≤ 10⁴
  • 1 ≤ a < b ≤ n; no pair repeats

Hints

Hint 1

Draw each dislike as an edge. The two rooms are two colours, and every edge must join different colours.

Hint 2

This is exactly the bipartite check: colour by breadth-first search from every uncoloured person.

Hint 3

Labels start at 1, so size your arrays n + 1.

Where people lose marks

  • Off-by-one from the 1-based labels.
  • Assigning rooms greedily in input order without propagating forced choices.
  • Starting a single search from person 1 and ignoring people in other pieces.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.