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 _thelargest possible value of _num afterany number of swaps.

Examples

Example 1

1
2
3
4
5
6
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

1
2
3
4
5
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

Solution

Method 1 – Sort and Greedy Placement

Intuition

To get the largest number, sort all odd digits in descending order and all even digits in descending order. Then, for each digit in the original number, replace it with the largest available digit of the same parity.

Approach

  1. Convert the number to a list of digits.
  2. Separate odd and even digits, sort each in descending order.
  3. For each digit in the original number:
    • If it’s odd, take the next largest odd digit.
    • If it’s even, take the next largest even digit.
  4. Reconstruct the number from the new digits.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int largestInteger(int num) {
        vector<int> odd, even, digits;
        int n = num;
        while (n) { digits.push_back(n%10); n /= 10; }
        reverse(digits.begin(), digits.end());
        for (int d : digits) (d%2 ? odd : even).push_back(d);
        sort(odd.rbegin(), odd.rend());
        sort(even.rbegin(), even.rend());
        int oi = 0, ei = 0, ans = 0;
        for (int d : digits) {
            ans = ans*10 + (d%2 ? odd[oi++] : even[ei++]);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func largestInteger(num int) int {
    digits := []int{}
    n := num
    for n > 0 { digits = append([]int{n%10}, digits...); n /= 10 }
    odd, even := []int{}, []int{}
    for _, d := range digits {
        if d%2 == 0 { even = append(even, d) } else { odd = append(odd, d) }
    }
    sort.Sort(sort.Reverse(sort.IntSlice(odd)))
    sort.Sort(sort.Reverse(sort.IntSlice(even)))
    oi, ei, ans := 0, 0, 0
    for _, d := range digits {
        if d%2 == 0 { ans = ans*10 + even[ei]; ei++ } else { ans = ans*10 + odd[oi]; oi++ }
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int largestInteger(int num) {
        List<Integer> digits = new ArrayList<>();
        int n = num;
        while (n > 0) { digits.add(0, n%10); n /= 10; }
        List<Integer> odd = new ArrayList<>(), even = new ArrayList<>();
        for (int d : digits) if (d%2==0) even.add(d); else odd.add(d);
        odd.sort(Collections.reverseOrder());
        even.sort(Collections.reverseOrder());
        int oi = 0, ei = 0, ans = 0;
        for (int d : digits) {
            ans = ans*10 + (d%2==0 ? even.get(ei++) : odd.get(oi++));
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
    fun largestInteger(num: Int): Int {
        val digits = num.toString().map { it - '0' }
        val odd = digits.filter { it%2==1 }.sortedDescending().toMutableList()
        val even = digits.filter { it%2==0 }.sortedDescending().toMutableList()
        val ans = digits.map { if (it%2==0) even.removeAt(0) else odd.removeAt(0) }
        return ans.joinToString("") { it.toString() }.toInt()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def largestInteger(self, num: int) -> int:
        digits = [int(x) for x in str(num)]
        odd = sorted([d for d in digits if d%2], reverse=True)
        even = sorted([d for d in digits if d%2==0], reverse=True)
        oi = ei = 0
        ans = []
        for d in digits:
            if d%2:
                ans.append(odd[oi])
                oi += 1
            else:
                ans.append(even[ei])
                ei += 1
        return int(''.join(map(str, ans)))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
impl Solution {
    pub fn largest_integer(num: i32) -> i32 {
        let mut digits: Vec<i32> = num.to_string().chars().map(|c| c.to_digit(10).unwrap() as i32).collect();
        let mut odd: Vec<i32> = digits.iter().cloned().filter(|&d| d%2==1).collect();
        let mut even: Vec<i32> = digits.iter().cloned().filter(|&d| d%2==0).collect();
        odd.sort_by(|a, b| b.cmp(a));
        even.sort_by(|a, b| b.cmp(a));
        let (mut oi, mut ei) = (0, 0);
        let mut ans = 0;
        for &d in &digits {
            ans = ans*10 + if d%2==0 { even[ei]; ei+=1; even[ei-1] } else { odd[oi]; oi+=1; odd[oi-1] };
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    largestInteger(num: number): number {
        const digits = Array.from(String(num), x => +x)
        const odd = digits.filter(d => d%2).sort((a,b)=>b-a)
        const even = digits.filter(d => d%2===0).sort((a,b)=>b-a)
        let oi = 0, ei = 0, ans = 0
        for (const d of digits) {
            ans = ans*10 + (d%2===0 ? even[ei++] : odd[oi++])
        }
        return ans
    }
}

Complexity

  • ⏰ Time complexity: O(n log n), where n is the number of digits. Sorting odd and even digits dominates.
  • 🧺 Space complexity: O(n), for storing digits and sorted lists.