Smallest Ad Headline Reachable With Allowed Position Swaps
Last updated: November 29, 2026
Quick Overview
Given an ad headline string s and a list of index pairs (i, j) whose characters may be swapped any number of times, return the lexicographically smallest string you can produce.
0
0
0 solved
Given an ad headline string s and a list of index pairs (i, j) whose characters may be swapped any number of times, return the lexicographically smallest string you can produce.
A Google technical screen staple that rewards one modeling insight: unlimited swaps over connected positions allow any permutation within that group. The interviewer checks that you see that, group positions with union-find, and then sort characters per group.
What the Interviewer Expects
- States that connected positions can be permuted arbitrarily
- Groups indices with union-find
- Sorts characters within each group and places them in ascending index order
- Handles positions that appear in no pair
- Analyzes the sorting cost
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if each swap can be used only once?
- Return the lexicographically largest string instead.
- How would you minimize the Hamming distance to a target string under the same swaps?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: string
sand list of(i, j)index pairs, each usable any number of times. - Output: smallest string obtainable.
- Indices not in any pair stay fixed....
High-Level Design
Adjacent transpositions generate every permutation, and more generally, if swaps form a connected graph over a set of positions, any arrangement of the characters on those positions is reachable. So u...