DSA Heaps

Largest Number After Digit Swaps by Parity

Sort odd-positioned and even-positioned digits independently in descending order — two heaps.

Easy
Time O(d log d) Space O(d)
LeetCode
5 min read
heaps

Problem#

You may swap any two digits of num only if both have the same parity. Return the largest number obtainable.

Examples#

  • 12343412 (swap 1↔3, 2↔4 — both pairs same parity)
  • 6587587655

Constraints#

  • 1 <= num <= 10^9.

Approach#

Convert to string. Two max-heaps: one for odd digits, one for even. Walk positions left-to-right; at each position, pop the largest digit of the matching parity.

Solution#

Largest Number After Digit Swaps by Parity
class Solution {
public:
int largestInteger(int num) {
string s = to_string(num);
priority_queue<int> odd, even;
for (char c : s) (c - '0') % 2 == 0 ? even.push(c - '0') : odd.push(c - '0');
for (char& c : s) {
int d = c - '0';
if (d % 2 == 0) { c = '0' + even.top(); even.pop(); }
else { c = '0' + odd.top(); odd.pop(); }
}
return stoi(s);
}
};

Editorial#

Same-parity swaps form two disjoint groups. Within each group, we can freely permute, so the optimum is to place the largest digit of each group at the leftmost position of that parity. Two sorts (or heap-extracts) deliver that placement.

Complexity#

  • Time: O(d log d) where d = #digits.
  • Space: O(d).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.