Largest Number After Digit Swaps by Parity - Complete Solution Guide
Largest Number After Digit Swaps by Parity is LeetCode problem 2231, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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 poss
Detailed Explanation
The problem asks you to find the largest possible integer that can be formed by swapping digits of the input integer `num` such that only digits of the same parity (both even or both odd) can be swapped. The input is a positive integer, and the output is the largest possible integer achievable through these allowed swaps. For example, if the input is 1234, the largest possible number after swapping digits with the same parity is 3412 (swapping 1 and 3, and 2 and 4).
Solution Approach
The solution uses a greedy approach. It first separates the digits of the input number into two lists: one for odd digits and one for even digits. Then it sorts these lists in descending order. Finally, it iterates through the original digits and replaces them with the largest available odd or even digit from the sorted lists, maintaining the original order of even and odd positions.
Step-by-Step Algorithm
- Step 1: Convert the input integer `num` into a string `s` for easier digit access.
- Step 2: Create two lists (or arrays): `odds` to store odd digits and `evens` to store even digits from `s`.
- Step 3: Sort `odds` and `evens` in descending order.
- Step 4: Iterate through the characters of `s`. If a digit is odd, replace it with the next largest odd digit from the sorted `odds` list. If a digit is even, replace it with the next largest even digit from the sorted `evens` list.
- Step 5: Concatenate the modified digits to form a new string, and convert it back to an integer, which is the result.
Key Insights
- Insight 1: Separating even and odd digits is crucial. We cannot swap even and odd digits, so they need to be handled independently.
- Insight 2: Sorting the even and odd digits in descending order allows us to easily construct the largest possible number by placing the largest even digits in even positions and largest odd digits in odd positions.
- Insight 3: Converting the integer to a string (or an array of digits) simplifies digit manipulation and comparison.
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(n)
Topics
This problem involves: Sorting, Heap (Priority Queue).
Companies
Asked at: ZScaler.