Bird
Raised Fist0
Interview Prepunion-findmediumAmazonFacebookGoogle

Number of Provinces

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize variables and graph structure

We determine the number of cities (n=3) and create an empty adjacency list for each city.

💡 Setting up adjacency lists prepares for efficient graph traversal instead of repeatedly checking the matrix.
Line:n = len(isConnected) graph = [[] for _ in range(n)]
💡 Adjacency lists will represent the graph connections more efficiently for DFS.
📊
Number of Provinces - Watch the Algorithm Execute, Step by Step
Watching each step of DFS traversal and adjacency list construction reveals how connected components are identified, which is the core of this problem.
Step 1/15
·Active fill★Answer cell
Visiting: none
0
1
2
Visiting: 0
Edge: 0 → 1
0
1
2
Visiting: 1
Edge: 1 → 0
0
1
2
Visiting: 2
0
1
2
Visiting: none
0
1
2
Visiting: 0
0
1
2
Queue / Stack
0
Visiting: 1
Edge: 0 → 1
0
1
2
Queue / Stack
01
Visiting: 1
Edge: 1 → 0
0
1
2
Queue / Stack
01
Visiting: 0
0
1
2
Queue / Stack
0
Visiting: none
0
1
2
Visiting: 1
0
1
2
Visiting: 2
0
1
2
Queue / Stack
2
Visiting: 2
0
1
2
Queue / Stack
2
Visiting: none
0
1
2
Visiting: none
0
1
2

Key Takeaways

✓ DFS traversal discovers connected components representing provinces.

Reading code alone hides how DFS explores neighbors recursively; visualization shows the exact order and marking.

✓ Adjacency list conversion simplifies repeated neighbor checks during DFS.

Seeing adjacency lists built step-by-step clarifies why they are more efficient than matrix lookups.

✓ Visited array prevents revisiting nodes and infinite loops.

Visualizing visited states and skipped nodes concretely shows how the algorithm avoids redundant work.

Practice

(1/5)
1. You are given a graph with edges of three types: edges usable by Alice only, edges usable by Bob only, and edges usable by both. The goal is to remove the maximum number of edges while ensuring both Alice and Bob can still traverse the entire graph. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. A greedy approach that processes type 3 edges first using union-find, then type 1 and 2 edges separately.
B. A brute force approach that tries all subsets of edges and checks connectivity for both Alice and Bob.
C. A dynamic programming approach that counts ways to connect nodes with subsets of edges.
D. A shortest path algorithm like Dijkstra's applied separately for Alice and Bob.

Solution

  1. Step 1: Understand problem constraints

    The problem requires maximizing edge removals while keeping the graph fully traversable for both Alice and Bob, who share some edges (type 3) and have exclusive edges (type 1 and 2).
  2. Step 2: Identify the best approach

    Processing type 3 edges first with union-find maximizes shared connectivity, then adding exclusive edges ensures full connectivity for both. This greedy union-find approach guarantees optimality, unlike brute force (too slow), DP (not applicable), or shortest path (irrelevant).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Greedy union-find with type 3 edges first -> optimal [OK]
Hint: Process shared edges first to maximize connectivity [OK]
Common Mistakes:
  • Trying brute force despite exponential complexity
  • Ignoring type 3 edges first
  • Using shortest path algorithms incorrectly
2. What is the time complexity of the optimal union-find approach for the Swim in Rising Water problem on an n x n grid, where n is the grid dimension?
medium
A. O(n^2 log n) due to sorting all n^2 cells and near-constant union-find operations
B. O(n^4) due to nested loops over grid and union operations
C. O(n^2 * maxElevation) because of simulating water rise for each elevation
D. O(n^2) because each cell is processed once with union-find operations

Solution

  1. Step 1: Identify main operations

    Sorting all n^2 cells takes O(n^2 log n^2) = O(n^2 log n). Union-find operations are almost O(1) amortized per union/find.
  2. Step 2: Combine complexities

    Total complexity dominated by sorting: O(n^2 log n). Union-find merges add negligible overhead.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting dominates; union-find nearly constant time per operation [OK]
Hint: Sorting n^2 cells dominates complexity [OK]
Common Mistakes:
  • Assuming union-find operations cost O(log n) each
  • Confusing brute force simulation complexity with optimal
  • Ignoring sorting cost or treating union-find as O(1) without justification
3. Suppose the problem is extended so that variables can be reused multiple times in equations, and inequalities can be chained (e.g., a==b, b!=c, c==a). Which modification to the union-find approach correctly handles early contradiction detection in this scenario?
hard
A. Process all equalities and inequalities in a single pass, unioning and checking contradictions immediately
B. First union all equalities, then check all inequalities for contradictions, returning false if any found
C. Use union-find with early contradiction detection by checking inequalities during union operations and aborting immediately on conflict
D. Replace union-find with a graph coloring approach to handle chained inequalities

Solution

  1. Step 1: Understand reuse and chaining impact

    Variables appearing multiple times and chained inequalities require detecting contradictions as soon as they arise to avoid unnecessary work.
  2. Step 2: Early contradiction detection

    Checking inequalities during union operations allows immediate detection of conflicts, improving efficiency and correctness.
  3. Step 3: Compare alternatives

    Single pass union and check can miss contradictions; two-pass delays detection; graph coloring is more complex and less efficient here.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Early contradiction detection aborts on conflict [OK]
Hint: Check contradictions during union to detect conflicts early [OK]
Common Mistakes:
  • Checking inequalities only after all unions
  • Trying single pass union and check without order
4. Suppose the problem is modified so that each pair can be used multiple times but swaps are only allowed between indices connected by a path of pairs (transitive closure). Which modification to the algorithm is necessary to handle this variant efficiently?
hard
A. Use a brute force DFS to try all swap sequences since union-find no longer applies
B. Use BFS to find shortest swap sequences between indices before swapping
C. Sort the entire string once since any character can be swapped anywhere
D. Use union-find to find connected components, then use a priority queue per component to assign characters on-the-fly

Solution

  1. Step 1: Understand transitive closure of pairs

    Indices connected by any path form connected components; union-find efficiently finds these.
  2. Step 2: Use priority queues per component

    Priority queues allow on-the-fly assignment of smallest available characters to indices in each component.
  3. Step 3: Avoid brute force or BFS over sequences

    Brute force or BFS over swap sequences is inefficient; union-find + priority queue is optimal.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Union-find + priority queue handles multiple swaps and transitive connections efficiently [OK]
Hint: Union-find + priority queue handles transitive swaps efficiently [OK]
Common Mistakes:
  • Trying brute force DFS
  • Sorting entire string ignoring connectivity
  • Using BFS for swap sequences
5. Suppose the Swim in Rising Water problem is modified so that you can revisit cells multiple times (cycles allowed), and the grid elevations can be negative. Which modification to the union-find approach is necessary to correctly solve this variant?
hard
A. Sort cells by absolute elevation and union in that order to handle negative values.
B. Add a visited set to union-find to prevent cycles during union operations.
C. Use a priority queue (min-heap) to process cells by elevation dynamically instead of sorting all upfront.
D. No change needed; the original union-find with sorting by elevation works as is.

Solution

  1. Step 1: Understand impact of negative elevations and revisits

    Negative elevations break sorting assumption; revisiting cells means connectivity can change dynamically.
  2. Step 2: Identify suitable data structure

    A priority queue allows processing cells in order of elevation dynamically, handling negative values and revisits correctly.
  3. Step 3: Why other options fail

    Sorting by absolute elevation loses ordering semantics; visited sets don't apply to union-find; original approach assumes non-negative elevations and no revisits.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Priority queue enables dynamic elevation processing [OK]
Hint: Dynamic processing needed for negative elevations and revisits [OK]
Common Mistakes:
  • Sorting by absolute elevation breaks ordering
  • Assuming union-find alone handles cycles
  • Ignoring negative elevation impact on sorting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard