Leetcode 2231: Largest Number After Digit Swaps by Parity

grid47
grid47
Exploring patterns and algorithms
Mar 28, 2024 7 min read

You are given a positive integer num. You are allowed to swap any two digits of num that have the same parity (i.e., both digits are either odd or both even). The goal is to return the largest possible value of num after any number of swaps.
Problem
Approach
Steps
Complexity
Input: The input consists of a positive integer `num`.
Example: num = 8235
Constraints:
• 1 <= num <= 10^9
Output: Return the largest possible value of `num` after performing any number of valid swaps.
Example: Output: 8532
Constraints:
• The result will be a positive integer.
Goal: The goal is to maximize the number by swapping digits of the same parity. To achieve this, we will use priority queues to store the odd and even digits in descending order and then place the largest possible digits at their respective positions.
Steps:
• 1. Convert the number into a string to easily access each digit.
• 2. Separate the odd and even digits into two different priority queues, ensuring the digits are stored in descending order.
• 3. For each digit in the original number, replace it with the largest available odd or even digit from the respective priority queue, depending on its parity.
Goal: The solution must handle up to 9 digits in `num` efficiently.
Steps:
• The number `num` will have at most 9 digits.
Assumptions:
• The input is always a valid positive integer.
Input: Input: num = 8235
Explanation: In this case, we have two even digits (8, 2) and two odd digits (3, 5). After sorting both even and odd digits in descending order, we get 8, 2 for evens and 5, 3 for odds. Swapping the digits gives the largest possible number: 8532.

Input: Input: num = 4321
Explanation: Here, we have two even digits (4, 2) and two odd digits (3, 1). After sorting, we get 4, 2 for evens and 3, 1 for odds. Swapping the digits to maximize the value results in 4321, which is already the largest possible number.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus