Google questions

Minimum Direction Violations

GoogleMedium

You are given a directed graph with n nodes numbered 0 to n - 1 and a list of directed edges, where each edge [u, v] goes from u to v. You may traverse an edge in its own direction for free, or against its direction at a cost of 1. Edges may be traversed any number of times in either direction, and parallel edges and self loops may appear.

Part 1: Cheapest walk from start to end

Given the directed graph described above, return the smallest total cost of a walk from start to end, where traversing an edge against its direction costs 1 and traversing it in its direction costs 0.

Return -1 if no walk from start to end exists, even when edges may be walked backward. If start == end, the cost is 0.

  1. Example 1
    n
    5
    end
    4
    edges
    [[0,1],[2,1],[2,3],[4,3]]
    start
    0
    Output
    2

    Why: The walk 0, 1, 2, 3, 4 uses edge [0,1] forward, edge [2,1] backward, edge [2,3] forward and edge [4,3] backward, so two edges are walked against their direction.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u < n and 0 <= v < n for every edge [u, v]
  • 0 <= start < n
  • 0 <= end < n
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question