#3216

Lexicographically Smallest String After a Swap

Easy
StringGreedyGreedySortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Instead of checking all pairs, we can group the digits by parity and sort them. This allows us to swap the smallest digits in each group to form the smallest possible string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two lists, one for even digits and one for odd digits, and populate them with the corresponding digits from the string.
  2. 2Step 2: Sort both lists to have the smallest digits at the front.
  3. 3Step 3: Reconstruct the string by replacing the digits in the original string with the smallest available digit from the corresponding sorted list based on parity.
solution.py13 lines
1def smallestStringAfterSwap(s):
2    evens = sorted([c for c in s if int(c) % 2 == 0])
3    odds = sorted([c for c in s if int(c) % 2 != 0])
4    result = []
5    even_index, odd_index = 0, 0
6    for c in s:
7        if int(c) % 2 == 0:
8            result.append(evens[even_index])
9            even_index += 1
10        else:
11            result.append(odds[odd_index])
12            odd_index += 1
13    return ''.join(result)

Complexity note: The time complexity is O(n log n) due to the sorting of the even and odd lists, while the space complexity is O(n) because we store the digits in separate lists.

  • 1Swapping only adjacent digits with the same parity allows for targeted optimizations.
  • 2Sorting helps in quickly finding the smallest possible arrangement.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.