Solving Leetcode Interviews in Seconds with AI: Largest Number After Digit Swaps by Parity
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2231" 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
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Example 1: Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this results in the number 3214. Swap the digit 2 with the digit 4, this results in the number 3412. Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number. Also note that we may not swap the digit 4 with the digit 1 since they are of different parities. Example 2: Input: num = 65875 Output: 87655 Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. Swap the first digit 5 with the digit 7, this results in the number 87655. Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number. Constraints: 1 <= num <= 109
Explanation
Here's an efficient solution to the problem:
- Separate and Sort: Extract the odd and even digits from the input number and sort them in descending order.
Reconstruct: Rebuild the number by iterating through the original number's digits. For each digit, pick the largest available odd or even digit from the sorted lists based on the digit's parity.
Runtime & Storage Complexity: O(N log N) due to sorting, where N is the number of digits in
num. O(N) storage for the lists of odd and even digits.
Code
def largestInteger(num: int) -> int:
"""
Finds the largest possible value of num after any number of swaps of digits with the same parity.
"""
s = str(num)
odds = sorted([int(d) for d in s if int(d) % 2 != 0], reverse=True)
evens = sorted([int(d) for d in s if int(d) % 2 == 0], reverse=True)
odd_idx = 0
even_idx = 0
result = ""
for digit in s:
digit_int = int(digit)
if digit_int % 2 == 0:
result += str(evens[even_idx])
even_idx += 1
else:
result += str(odds[odd_idx])
odd_idx += 1
return int(result)