Largest Number After Digit Swaps by Parity solution and explanation
9 more videos on this problem
Largest Number After Digit Swaps by Parity | Leetcode 2231 | Max Heaps | Contest 288 🔥🔥Coding Decoded · 6:16 · 3K views
2231. Largest Number After Digit Swaps by Parity || Leetcode Weekly Contest 288 || Leetcode 2231Bro Coders · 9:10 · 2K views
2231. Largest Number After Digit Swaps by Parity (Leetcode Easy)Programming Live with Larry · 6:48 · 961 views
Largest Number After Digit Swaps by Parity | LeetCode 2231 | CppCodeClips with Abhishek Ranjan · 5:20 · 791 views
2231. Largest Number After Digit Swaps by Parity | LeetCode Weekly Contest 288 | EasyAceCoder Academy · 4:21 · 762 views
2231. Largest Number After Digit Swaps by Parity | Leetcode 288Mike the Coder · 7:01 · 423 views
Largest Number After Digit Swaps by Parity #java #Maths#strings #java #javainterview #leetcodeCodeVia · 4:50 · 310 views
Leetcode 2231 Largest Number After Digit Swaps by ParityMath Geeks · 3:47 · 272 views
LeetCode 2231 Largest Number After Digit Swaps by Parity || PQ-4||The Code Transaction · 15:46 · 229 views
#LeetCode 2231 | Largest Number After Digit Swaps by Parity #JavaSleepy Cracker · 5:14 · 149 views
The problem
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
Approach overview
Problem Overview: You are given an integer num. You may swap digits only with other digits that have the same parity (odd with odd, even with even). The goal is to rearrange the digits so the resulting number is as large as possible while respecting this restriction.
The constraint that swaps must preserve parity means each digit position can only receive digits from the same parity group. Odd digits can move only among odd positions, and even digits only among even positions. The problem reduces to reorganizing two independent groups of digits.
Approach 1: Sort Parity Groups (O(n log n) time, O(n) space)
Extract all digits from the number while keeping track of their parity. Store odd digits in one list and even digits in another. Sort both lists in descending order so the largest digits are used first. Then iterate through the original digit positions again: if the current digit position originally held an even digit, place the largest remaining even digit from the sorted list; if it held an odd digit, place the largest remaining odd digit.
The key insight is that swaps within the same parity group allow complete reordering inside that group. Sorting each group guarantees the largest available digit fills the leftmost valid position, which maximizes the final number. This approach is straightforward and performs well for typical integer lengths. It relies on basic sorting operations.
Approach 2: Priority Queue (Heap) Utilization (O(n log n) time, O(n) space)
Instead of sorting upfront, push odd digits and even digits into separate max-heaps. A max-heap ensures the largest available digit is always accessible in O(log n) time. After building the heaps, iterate through the digits of the original number. For each position, check the parity and pop the largest digit from the corresponding heap.
This approach produces the same result as sorting but retrieves the next best digit dynamically. Heaps are useful when the problem requires repeatedly extracting the maximum element during reconstruction. Implementation typically uses a priority queue, which guarantees efficient insertion and removal.
Recommended for interviews: The sorted parity groups approach is the most common and easiest to explain. It clearly demonstrates understanding of parity constraints and greedy placement of digits. The heap approach shows familiarity with priority queues and is a solid alternative when repeated maximum extraction is required. Showing the sorting approach first proves correctness quickly, while mentioning the heap variant demonstrates broader data structure knowledge.
Approach 1: Sort Parity Groups
This approach involves separating digits based on parity (odd and even). Once separated, each group is sorted in descending order. The digits from these sorted lists are then re-assigned to their original positions.
def largest_integer(num):
digits = list(str(num))
odds = sorted((d for d in digits if int(d) % 2 != 0), reverse=True)
evens = sorted((d for d in digits if int(d) % 2 == 0), reverse=True)
for i, d in enumerate(digits):
if int(d) % 2 == 0:
digits[i] = evens.pop(0)
else:
digits[i] = odds.pop(0)
return int(''.join(digits))
num = 1234
print(largest_integer(num))import java.util.Arrays;
public class LargestInteger {
public static int largestInteger(int num) {
char[] digits = Integer.toString(num).toCharArray();
char[] odds = new char[digits.length];
char[] evens = new char[digits.length];
int oddIndex = 0, evenIndex = 0;
for (char digit : digits) {
if ((digit - '0') % 2 == 0) evens[evenIndex++] = digit;
else odds[oddIndex++] = digit;
}
Arrays.sort(odds, 0, oddIndex);
Arrays.sort(evens, 0, evenIndex);
reverse(odds, 0, oddIndex - 1);
reverse(evens, 0, evenIndex - 1);
oddIndex = 0; evenIndex = 0;
for (int i = 0; i < digits.length; i++) {
if ((digits[i] - '0') % 2 == 0) digits[i] = evens[evenIndex++];
else digits[i] = odds[oddIndex++];
}
return Integer.parseInt(new String(digits));
}
private static void reverse(char[] arr, int start, int end) {
while (start < end) {
char temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int num = 1234;
System.out.println(largestInteger(num));
}
}#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int largestInteger(int num) {
string str = to_string(num);
vector<char> odds, evens;
for (char& ch : str) {
if ((ch - '0') % 2 == 0) evens.push_back(ch);
else odds.push_back(ch);
}
sort(odds.rbegin(), odds.rend());
sort(evens.rbegin(), evens.rend());
int oddIdx = 0, evenIdx = 0;
for (char& ch : str) {
if ((ch - '0') % 2 == 0) ch = evens[evenIdx++];
else ch = odds[oddIdx++];
}
return stoi(str);
}
int main() {
int num = 1234;
cout << largestInteger(num) << endl;
return 0;
}function largestInteger(num) {
let digits = num.toString().split('');
let odds = digits.filter(d => d % 2 !== 0).sort((a, b) => b - a);
let evens = digits.filter(d => d % 2 === 0).sort((a, b) => b - a);
for (let i = 0; i < digits.length; i++) {
if (digits[i] % 2 === 0) {
digits[i] = evens.shift();
} else {
digits[i] = odds.shift();
}
}
return parseInt(digits.join(''), 10);
}
console.log(largestInteger(1234));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return *(char*)b - *(char*)a;
}
int largestInteger(int num) {
char str[11];
sprintf(str, "%d", num);
char oddDigits[10] = {0};
char evenDigits[10] = {0};
int oddIndex = 0, evenIndex = 0;
for (int i = 0; str[i] != '\0'; i++) {
if ((str[i] - '0') % 2 == 0) {
evenDigits[evenIndex++] = str[i];
} else {
oddDigits[oddIndex++] = str[i];
}
}
qsort(oddDigits, oddIndex, sizeof(char), compare);
qsort(evenDigits, evenIndex, sizeof(char), compare);
oddIndex = 0; evenIndex = 0;
for (int i = 0; str[i] != '\0'; i++) {
if ((str[i] - '0') % 2 == 0) {
str[i] = evenDigits[evenIndex++];
} else {
str[i] = oddDigits[oddIndex++];
}
}
return atoi(str);
}
int main() {
int num = 1234;
printf("%d\n", largestInteger(num));
return 0;
}using System;
using System.Linq;
class LargestInteger {
static int LargestInteger(int num) {
char[] digits = num.ToString().ToCharArray();
var evens = digits.Where(d => (d - '0') % 2 == 0).OrderByDescending(d => d).ToArray();
var odds = digits.Where(d => (d - '0') % 2 != 0).OrderByDescending(d => d).ToArray();
int evenIndex = 0, oddIndex = 0;
for (int i = 0; i < digits.Length; i++) {
if ((digits[i] - '0') % 2 == 0) digits[i] = evens[evenIndex++];
else digits[i] = odds[oddIndex++];
}
return int.Parse(new string(digits));
}
static void Main() {
int num = 1234;
Console.WriteLine(LargestInteger(num));
}
}In Python, list comprehensions and built-in sorted functions efficiently sort and extract digits by parity into two separate lists, which are then used to reconstruct the largest possible number.
Time Complexity: O(n log n) due to sorting operations.
Space Complexity: O(n) for storing odd and even digits separately.
Approach 2: Priority Queue (Heap) Utilization
This approach utilizes priority queues (heaps) to efficiently sort and retrieve the largest elements of each parity group. This guarantees that when re-constructing the number from sorted parts, the retrieval operations are optimal.
import heapq
def largest_integer(num):
digits = list(str(num))
odds = []
evens = []
for d in digits:
if int(d) % 2 == 0:
heapq.heappush(evens, -int(d)) # Max-heap behaviour by inverting
else:
heapq.heappush(odds, -int(d))
result = []
for d in digits:
if int(d) % 2 == 0:
result.append(str(-heapq.heappop(evens)))
else:
result.append(str(-heapq.heappop(odds)))
return int(''.join(result))
num = 1234
print(largest_integer(num))#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
int largestInteger(int num) {
string str = to_string(num);
priority_queue<int> odds, evens;
for (char digit : str) {
int val = digit - '0';
if (val % 2 == 0) evens.push(val);
else odds.push(val);
}
string result = "";
for (char digit : str) {
if ((digit - '0') % 2 == 0) {
result += to_string(evens.top());
evens.pop();
} else {
result += to_string(odds.top());
odds.pop();
}
}
return stoi(result);
}
int main() {
int num = 1234;
cout << largestInteger(num) << endl; // Output: 3412
return 0;
}This Python variant leverages the heapq module to implement min-heaps. The integers are stored as their negative to simulate max-heap behaviour.
Time Complexity: O(n log n) due to heap manipulation.
Space Complexity: O(n) because of the heaps for even and odd digits.
Approach 3: Counting
We can use an array cnt of length 10 to count the occurrences of each digit in the integer num. We also use an index array idx to record the largest available even and odd digits, initially set to [8, 9].
Next, we traverse each digit of the integer num. If the digit is odd, we take the digit corresponding to index 1 in idx; otherwise, we take the digit corresponding to index 0. If the count of the digit is 0, we decrement the digit by 2 and continue checking until we find a digit that meets the condition. Then, we update the answer and the count of the digit, and continue traversing until we have processed all digits of the integer num.
The time complexity is O(log num), and the space complexity is O(log num).
function largestInteger(num: number): number {
const s = num.toString().split('');
const cnt = Array(10).fill(0);
for (const c of s) {
cnt[+c]++;
}
const idx = [8, 9];
let ans = 0;
for (const c of s) {
const x = +c;
while (cnt[idx[x % 2]] === 0) {
idx[x % 2] -= 2;
}
ans = ans * 10 + idx[x % 2];
cnt[idx[x % 2]]--;
}
return ans;
}func largestInteger(num int) int {
s := []byte(fmt.Sprint(num))
cnt := [10]int{}
for _, c := range s {
cnt[c-'0']++
}
idx := [2]int{8, 9}
ans := 0
for _, c := range s {
x := int(c - '0')
for cnt[idx[x&1]] == 0 {
idx[x&1] -= 2
}
ans = ans*10 + idx[x&1]
cnt[idx[x&1]]--
}
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Sort Parity Groups | Time Complexity: O(n log n) due to sorting operations. |
| Priority Queue (Heap) Utilization | Time Complexity: O(n log n) due to heap manipulation. |
| Counting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sort Parity Groups | O(n log n) | O(n) | Best general solution. Simple implementation using sorting and greedy reconstruction. |
| Priority Queue (Heap) | O(n log n) | O(n) | Useful when repeatedly extracting the largest element dynamically or demonstrating heap usage. |
Frequently asked questions
Is Largest Number After Digit Swaps by Parity easy or hard?
Largest Number After Digit Swaps by Parity is classified as an Easy problem. The key idea is recognizing that digits can be freely rearranged within their parity group, allowing a greedy solution using sorting or heaps.
Largest Number After Digit Swaps by Parity Python/Java solution
In Python or Java, extract digits from the number, place odd digits and even digits into separate lists, sort them in descending order, and rebuild the number by selecting from the appropriate list based on the original digit's parity. This approach runs in O(n log n) time and O(n) space.
How to solve Largest Number After Digit Swaps by Parity in O(n)?
Since digits range only from 0–9, a counting approach can reduce sorting overhead by storing frequency counts for odd and even digits. Rebuilding the number by always selecting the largest available digit from the correct parity group can achieve near O(n) time. Most implementations, however, use sorting for simplicity.
What is the best approach for Largest Number After Digit Swaps by Parity?
The most common solution separates digits into odd and even groups, sorts both groups in descending order, and reconstructs the number using the largest available digit of the same parity. This greedy strategy guarantees the maximum possible number. The time complexity is O(n log n) due to sorting.
Is Largest Number After Digit Swaps by Parity asked at Google/Amazon/Meta?
Parity-based digit manipulation and greedy rearrangement problems frequently appear in coding interviews at large tech companies. Variants of digit reordering and constraint-based swaps are common practice questions for companies like Google, Amazon, and Meta.
What data structure is used in Largest Number After Digit Swaps by Parity?
The common implementation uses arrays or lists to store odd and even digits, followed by sorting. Another valid approach uses a max-heap (priority queue) to always retrieve the largest available digit of the required parity.
What is the time complexity of Largest Number After Digit Swaps by Parity?
The typical solution runs in O(n log n) time because the odd and even digit groups are sorted before reconstruction. Extracting digits and rebuilding the result takes O(n). Space complexity is O(n) to store the parity groups.
