Smallest Caption After Swapping Characters at Allowed Index Pairs

Last updated: November 29, 2026

Quick Overview

Given a caption string and a list of index pairs, you may swap the characters at any listed pair any number of times. Return the lexicographically smallest string you can produce.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a caption string and a list of index pairs, you may swap the characters at any listed pair any number of times. Return the lexicographically smallest string you can produce.

A Meta technical screen problem in the style of string canonicalization for deduplication. The interviewer checks that you realize repeated swaps within a connected set of indices allow any permutation of that set, so the answer is to sort characters per component and place them back into sorted index slots.

What the Interviewer Expects
  • Group indices into components with union find
  • Argue any permutation within a component is reachable
  • Sort characters within each component
  • Assign them to the component's indices in ascending order
  • State O(n log n + p) time
Key Topics to Cover
union find
connected components
sorting
permutations
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Why do swaps generate every permutation within a component?
  • What if each swap had a cost and you wanted the cheapest way to reach the smallest string?
  • How would you find the largest string instead?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: string s and pairs of indices [i, j].
  • Output: lexicographically smallest reachable string....
High-Level Design

Swaps along edges of a connected graph generate every permutation of its vertices (transpositions along a spanning tree generate the full symmetric group). So within each connected component of indice...


Submit Your Answer
Markdown supported