Solving Leetcode Interviews in Seconds with AI: Lexicographically Smallest String After a Swap
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3216" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a string s containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s with the same parity at most once. Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not. Example 1: Input: s = "45320" Output: "43520" Explanation: s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string. Example 2: Input: s = "001" Output: "001" Explanation: There is no need to perform a swap because s is already the lexicographically smallest. Constraints: 2 <= s.length <= 100 s consists only of digits.
Explanation
Here's the solution:
- Iterate and Find: Iterate through the string. For each digit, find the lexicographically smallest digit with the same parity to its right.
- Swap if Smaller: If a smaller digit with the same parity is found, swap them to minimize the string lexicographically. Only the first such swap from left to right matters.
Early Exit: After performing a swap, proceed to the next digit.
Runtime Complexity: O(N^2), where N is the length of the string. Storage Complexity: O(N)
Code
def smallest_string(s: str) -> str:
"""
Given a string s containing only digits, return the lexicographically smallest string that can be obtained
after swapping adjacent digits in s with the same parity at most once. Digits have the same parity if both
are odd or both are even.
For example:
smallest_string("45320") == "43520"
smallest_string("001") == "001"
"""
s_list = list(s)
n = len(s)
for i in range(n):
best_idx = -1
for j in range(i + 1, n):
if (int(s_list[i]) % 2 == int(s_list[j]) % 2):
if best_idx == -1 or s_list[j] < s_list[best_idx]:
best_idx = j
if best_idx != -1 and s_list[best_idx] < s_list[i]:
s_list[i], s_list[best_idx] = s_list[best_idx], s_list[i]
break # Only one swap is allowed
return "".join(s_list)