Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
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 <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
1234
65875
largest-number-at-least-twice-of-others)sort-array-by-parity)sort-array-by-parity-ii)smallest-string-with-swaps)rearrange-array-elements-by-sign)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2231: Largest Number After Digit Swaps by Parity
class Solution {
public int largestInteger(int num) {
char[] s = String.valueOf(num).toCharArray();
int[] cnt = new int[10];
for (char c : s) {
++cnt[c - '0'];
}
int[] idx = {8, 9};
int ans = 0;
for (char c : s) {
int x = c - '0';
while (cnt[idx[x & 1]] == 0) {
idx[x & 1] -= 2;
}
ans = ans * 10 + idx[x & 1];
cnt[idx[x & 1]]--;
}
return ans;
}
}
// Accepted solution for LeetCode #2231: Largest Number After Digit Swaps by Parity
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
}
# Accepted solution for LeetCode #2231: Largest Number After Digit Swaps by Parity
class Solution:
def largestInteger(self, num: int) -> int:
nums = [int(c) for c in str(num)]
cnt = Counter(nums)
idx = [8, 9]
ans = 0
for x in nums:
while cnt[idx[x & 1]] == 0:
idx[x & 1] -= 2
ans = ans * 10 + idx[x & 1]
cnt[idx[x & 1]] -= 1
return ans
// Accepted solution for LeetCode #2231: Largest Number After Digit Swaps by Parity
/**
* [2231] Largest Number After Digit Swaps by Parity
*
* 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 <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
// discuss: https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn largest_integer(num: i32) -> i32 {
let mut num = num as usize;
let mut evens_odds = [
std::collections::BinaryHeap::new(),
std::collections::BinaryHeap::new(),
];
let mut digits = Vec::new();
while num > 0 {
let dig = num % 10;
evens_odds[dig % 2].push(dig as i32);
digits.push(dig);
num /= 10;
}
digits
.iter()
.rev()
.fold(0, |res, &dig| 10 * res + evens_odds[dig % 2].pop().unwrap())
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2231_example_1() {
let num = 1234;
let result = 3412;
assert_eq!(Solution::largest_integer(num), result);
}
#[test]
fn test_2231_example_2() {
let num = 65875;
let result = 87655;
assert_eq!(Solution::largest_integer(num), result);
}
}
// Accepted solution for LeetCode #2231: Largest Number After Digit Swaps by Parity
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;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.