Bird
Raised Fist0
Interview Prepunion-findmediumAmazonGoogle

Smallest String With Swaps

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Union-Find Structure

Create a UnionFind instance for all indices of the string 'dcab'. Each index is initially its own parent, representing separate sets.

💡 This initialization sets up the foundation for grouping indices that can be swapped. Each index starts isolated.
Line:uf = UnionFind(n)
💡 Each index is initially in its own group, so no swaps are possible yet.
📊
Smallest String With Swaps - Watch the Algorithm Execute, Step by Step
Watching each union operation and the grouping of indices reveals how connected components form, which is key to understanding how swaps can reorder characters within these groups.
Step 1/15
·Active fill★Answer cell
Visiting: none
0
1
2
3
Visiting: 0
Edge: 0 → 3
0
1
2
3
Visiting: 1
Edge: 1 → 2
0
1
2
3
Visiting: 0
0
1
2
3
Visiting: 0
0
1
2
3
Visiting: 1
0
1
2
3
Visiting: 1
0
1
2
3
Visiting: 2
0
1
2
3
Visiting: 2
0
1
2
3
Visiting: 3
0
1
2
3
Visiting: 3
0
1
2
3
Visiting: 0
0
1
2
3
Visiting: 1
0
1
2
3
Visiting: 2
0
1
2
3
Visiting: 3
0
1
2
3

Key Takeaways

✓ Union-Find groups indices that can be swapped, revealing connected components.

This grouping is not obvious from code alone but is clear when watching union operations merge sets.

✓ Characters within each connected component are collected and sorted using min-heaps.

Seeing characters grouped and sorted visually helps understand how swaps reorder characters locally.

✓ Reconstructing the string by extracting smallest characters from each group's heap ensures lexicographically smallest result.

The step-by-step extraction clarifies how the final string is built from local minimums.

Practice

(1/5)
1. You are given a list of user accounts, each with a username and multiple email addresses. Some accounts may belong to the same user if they share at least one email address. Which algorithmic approach best guarantees merging all accounts belonging to the same user efficiently?
easy
A. Greedy approach that merges accounts by comparing usernames only
B. Dynamic programming to find the longest common subsequence of emails
C. Brute force nested loops checking every pair of accounts for email overlap
D. Union-Find data structure to group emails that appear in multiple accounts

Solution

  1. Step 1: Understand the problem structure

    The problem requires grouping accounts by shared emails, which naturally forms connected components in a graph where emails are nodes.
  2. Step 2: Identify the suitable algorithm

    Union-Find efficiently merges sets of emails that belong to the same user, handling multiple overlaps without redundant comparisons.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Union-Find is the classic pattern for merging overlapping sets [OK]
Hint: Accounts merge is a connected components problem [OK]
Common Mistakes:
  • Merging by username only misses shared emails
  • Brute force is too slow for large inputs
2. What is the time complexity of the optimal union-find based solution for the Accounts Merge problem, where N is the number of accounts and M is the maximum number of emails per account?
medium
A. O(N^2 * M) because each account is compared with every other
B. O(N * M^2) due to nested loops over emails
C. O(N * M * α(N * M)) where α is the inverse Ackermann function
D. O(N * M log (N * M)) due to sorting emails after union

Solution

  1. Step 1: Identify union-find operations cost

    Union-find operations (union/find) run in nearly O(1) amortized time, specifically O(α(N*M)) per operation.
  2. Step 2: Count total operations

    We perform union operations for each email in each account, totaling O(N*M) unions and finds.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Union-find with path compression yields almost linear time [OK]
Hint: Union-find nearly linear with inverse Ackermann factor [OK]
Common Mistakes:
  • Confusing sorting cost with union-find cost
  • Assuming quadratic due to nested loops
3. Examine the following buggy DFS code for counting provinces. Which line contains the subtle bug that can cause incorrect results or infinite recursion?
medium
A. Line 4: visited[city] = True
B. Line 2: for neighbor in graph[city]:
C. Line 1: def dfs(city: int):
D. Line 3: if not visited[neighbor]:

Solution

  1. Step 1: Understand DFS visit marking

    Visited nodes must be marked before recursive calls to avoid revisiting and infinite loops.
  2. Step 2: Identify bug in visit marking

    Marking visited after recursion causes repeated visits and possible infinite recursion.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Visited marking must be before recursion to prevent cycles [OK]
Hint: Visited marking after recursion causes infinite loops [OK]
Common Mistakes:
  • Marking visited too late
  • Confusing visited marking with neighbor iteration
4. Examine the following buggy code snippet for the optimal solution. Which line contains the subtle bug that can cause incorrect results?
medium
A. Line 2: Sorting edges by type descending
B. Line 16: Checking if both Alice and Bob are fully connected
C. Line 9: Using union-find union for type 3 edges
D. Line 6: Not adjusting node indices from 1-based to 0-based

Solution

  1. Step 1: Identify indexing issue

    Input edges use 1-based node indices, but union-find expects 0-based. Missing adjustment causes wrong unions or runtime errors.
  2. Step 2: Confirm other lines are correct

    Sorting edges, union calls, and connectivity checks are correct; only indexing is buggy.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing "u -= 1; v -= 1" causes incorrect unions [OK]
Hint: Check if node indices are adjusted before union-find calls [OK]
Common Mistakes:
  • Ignoring 1-based to 0-based index conversion
  • Misusing union-find union return value
  • Skipping connectivity check for both users
5. Suppose you want to find a minimum spanning forest (MST for each connected component) in a graph that may be disconnected. Which modification to the Kruskal's algorithm with union-find is necessary to correctly handle this scenario?
hard
A. Remove the break condition and process all edges to connect all components separately
B. Use DFS to find connected components first, then run Kruskal on each separately
C. Stop after adding n-1 edges, as usual, since MST covers all nodes
D. Add edges only if they connect nodes in the same component to avoid cycles

Solution

  1. Step 1: Understand MST vs MST forest

    In disconnected graphs, MST is a forest; stopping after n-1 edges assumes connectivity, which may not hold.
  2. Step 2: Modify Kruskal to process all edges

    Removing the break condition allows union-find to connect all components separately, building MST forest.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Process all edges to cover disconnected components [OK]
Hint: Don't stop early if graph is disconnected; build MST forest instead [OK]
Common Mistakes:
  • Stopping early assuming graph is connected
  • Running DFS first adds unnecessary complexity
  • Misusing union-find to connect nodes in same component
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