oneby7

Advanced Graphs Special edges and paths

488. Critical Connections in a Network

Hard

A network has n servers, numbered from 0 to n - 1. Each pair [a, b] in connections is a cable between servers a and b, and data can travel along it both ways. At the start, every server can reach every other server, directly or through other servers.

A critical connection is a cable that, if it is removed, leaves some server unable to reach some other server.

Return every critical connection, in any order. Each pair may be written either way round, as [a, b] or [b, a]. If no cable is critical, return an empty list. The outputs below write each pair with the smaller server first, and the pairs in sorted order.

Example 1

0123456

Input: n = 7 connections = [[0, 1], [1, 2], [2, 0], [1, 3], [3, 4], [4, 5], [5, 6], [6, 4]]

Output: [[1,3],[3,4]]

Explanation: Removing [1,3] cuts servers 0, 1 and 2 off from the rest, and removing [3,4] cuts servers 4, 5 and 6 off. Every other cable is on the loop 0, 1, 2 or the loop 4, 5, 6, so data can still go the other way round.

Example 2

0123

Input: n = 4 connections = [[0, 1], [1, 2], [2, 3], [3, 0]]

Output: []

Explanation: All four cables form one loop. Removing any one of them leaves a path the other way round.

Example 3

01

Input: n = 2, connections = [[1, 0]]

Output: [[0,1]]

Explanation: Without the only cable, the two servers cannot reach each other. Returning it as [1,0] is accepted too.

Check your understanding

Work out the answer for this input before you write any code.

n = 6 connections = [[0, 1], [1, 2], [2, 3], [3, 0], [0, 4], [4, 5]]

Constraints

  • 2 ≤ n ≤ 105
  • n - 1 ≤ connections.length ≤ 105
  • connections[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi
  • No cable appears twice. [a, b] and [b, a] are the same cable.
  • Every server can reach every other server.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.