Solve Array Distance and Wiki Navigation
Company: Snowflake
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates array-processing and graph-algorithm skills, specifically minimum-distance computation between marked elements in a one-dimensional array and shortest-path navigation in a directed link graph, plus edge-case reasoning and test-case design.
Part 1: Minimum Distance Between a Person and a Cake
Constraints
- `0 <= len(arr) <= 10^5`
- Each `arr[i]` is one of `0`, `1`, or `2`
- Return `-1` if there is no person or no cake
Examples
Input: ([0, 1, 0, 0, 2, 0, 1],)
Expected Output: 2
Explanation: The closest person-cake pair is at indices 4 and 6, with distance 2.
Input: ([1, 2],)
Expected Output: 1
Explanation: The person and cake are adjacent.
Input: ([0, 0, 0],)
Expected Output: -1
Explanation: There is neither a person nor a cake.
Input: ([],)
Expected Output: -1
Explanation: Empty input has no valid pair.
Input: ([1],)
Expected Output: -1
Explanation: There is a person but no cake.
Hints
- Scan from left to right and remember the most recent index of a person and the most recent index of a cake.
- Whenever you see a `1` or `2`, check whether the opposite type has already appeared and update the best distance.
Part 2: Minimum Clicks Between Wiki Pages
Constraints
- `0 <= number of pages <= 10^5`
- `0 <= total number of links <= 2 * 10^5`
- Page names are strings
- The graph is directed and may contain cycles
- Pages absent from `graph` have no outgoing links
Examples
Input: ({'Home': ['A', 'B'], 'A': ['Target'], 'B': [], 'Target': []}, 'Home', 'Target')
Expected Output: 2
Explanation: One shortest path is Home -> A -> Target.
Input: ({'A': ['B'], 'B': ['C', 'A'], 'C': ['D'], 'D': []}, 'A', 'D')
Expected Output: 3
Explanation: The graph contains a cycle A -> B -> A, but the shortest route to D is A -> B -> C -> D.
Input: ({'A': ['B'], 'B': [], 'C': ['A']}, 'A', 'C')
Expected Output: -1
Explanation: Starting from A, there is no path that reaches C.
Input: ({'A': ['B'], 'B': ['A']}, 'A', 'A')
Expected Output: 0
Explanation: No clicks are needed when start and target are the same page.
Input: ({}, 'A', 'B')
Expected Output: -1
Explanation: An empty graph has no links, so B cannot be reached from A.
Hints
- Model the wiki as an unweighted directed graph. In such graphs, breadth-first search finds the shortest path in number of edges.
- Use a `visited` set so cycles do not cause infinite loops or repeated work.