Magicsheet logo

Lexicographically Smallest String After a Swap

Easy
70.4%
Updated 6/1/2025

Asked by 2 Companies

Lexicographically Smallest String After a Swap

What is this problem about?

The "Lexicographically Smallest String After a Swap interview question" allows you to perform at most one swap between two adjacent characters. However, there is a constraint: you can only swap characters if they have the same parity (both even or both odd). Your goal is to find the lexicographically smallest string you can obtain. This "Lexicographically Smallest String After a Swap coding problem" is a focused exercise in greedy decision-making with specific constraints.

Why is this asked in interviews?

This is a common "warm-up" question for roles at companies like J.P. Morgan. it tests a candidate's ability to apply a "Greedy interview pattern" while strictly adhering to parity rules. It evaluates whether you can identify the first opportunity to improve the string's order, which is the hallmark of lexicographical optimization.

Algorithmic pattern used

The strategy is Greedy. You iterate through the string once and look for the first pair of adjacent characters s[i] and s[i+1] such that they have the same parity AND s[i] > s[i+1]. Swapping these two will immediately make the string lexicographically smaller. Since you only get one swap, you stop as soon as you find and perform this first beneficial swap.

Example explanation

String: "4532"

  1. '4', '5': Different parity (even, odd). No swap.
  2. '5', '3': Same parity (both odd) AND 5 > 3. Swap them.
  3. String becomes "4352". We stop here. If we had continued to '3', '2' (different parity), we wouldn't swap anyway. Result: "4352".

Common mistakes candidates make

  • Swapping the wrong pair: Swapping a later pair when an earlier pair could have been swapped to make the string even smaller.
  • Ignoring parity: Swapping "4" and "3" because 4 > 3, even though they have different parities.
  • Performing multiple swaps: The problem specifies "at most one swap," but some might try to sort the entire string using these rules.

Interview preparation tip

Lexicographical smallest problems usually mean you want to change the leftmost possible character to something smaller. Always look for the first violation of ascending order that you have the power to fix.

Similar Questions