DEV Community

Cover image for πŸ”’ Beginner-Friendly Guide "Maximize the Digit Swap Difference" – LeetCode 1432 (C++ | Python | JavaScript)
Om Shree
Om Shree

Posted on

πŸ”’ Beginner-Friendly Guide "Maximize the Digit Swap Difference" – LeetCode 1432 (C++ | Python | JavaScript)

A Fun String Manipulation + Greedy Problem


Hey Devs! πŸ‘‹

Let’s decode another cool number-manipulation problem today: 1432. Max Difference You Can Get From Changing an Integer.

This one is about finding the maximum possible difference by replacing digits β€” twice, independently!


πŸ“ Problem Summary

You're given an integer num. You perform this operation twice:

  1. Choose a digit x and replace all occurrences of it with another digit y (0–9, can be the same).
  2. Do this twice independently to form two new numbers a and b.

Your task:
Return the maximum difference between a and b.

🚫 No leading zeroes allowed
🚫 Final numbers must not be 0


🧩 Example

Input: num = 555
Output: 888

Explanation:

  • For maximum number: Replace 5 β†’ 9 β†’ 999
  • For minimum number: Replace 5 β†’ 1 β†’ 111
  • Difference: 999 - 111 = 888

πŸ’‘ Intuition & Strategy

To get:

  • Maximum value: Replace the first non-9 digit with 9
  • Minimum value:

    • If the first digit isn’t 1, replace it with 1
    • Else, find another digit (not the first) to replace with 0

We need to avoid leading zeroes, so we're careful not to start b with 0.


βš™οΈ C++ Implementation

class Solution {
public:
    int maxDiff(int num) {
        string t = to_string(num);  // for max
        string p = to_string(num);  // for min
        char c;

        // For max: Replace first non-9 digit with '9'
        for (char ch : t) {
            if (ch != '9') {
                c = ch;
                break;
            }
        }
        for (char& ch : t)
            if (ch == c)
                ch = '9';

        // For min:
        bool changed = false;
        char first = p[0];
        if (first != '1') {
            for (char& ch : p) {
                if (ch == first)
                    ch = '1';
            }
        } else {
            for (int i = 1; i < p.size(); ++i) {
                if (p[i] != '0' && p[i] != first) {
                    char c3 = p[i];
                    for (int j = 1; j < p.size(); ++j)
                        if (p[j] == c3)
                            p[j] = '0';
                    break;
                }
            }
        }

        return stoi(t) - stoi(p);
    }
};
Enter fullscreen mode Exit fullscreen mode

🌐 JavaScript Version

var maxDiff = function(num) {
    const s = num.toString().split('');

    // Get max
    let maxS = [...s];
    let replaceDigit = maxS.find(d => d !== '9');
    maxS = maxS.map(d => d === replaceDigit ? '9' : d);

    // Get min
    let minS = [...s];
    if (minS[0] !== '1') {
        minS = minS.map(d => d === minS[0] ? '1' : d);
    } else {
        for (let i = 1; i < minS.length; i++) {
            if (minS[i] !== '0' && minS[i] !== minS[0]) {
                let target = minS[i];
                minS = minS.map((d, idx) => (d === target && idx !== 0 ? '0' : d));
                break;
            }
        }
    }

    return parseInt(maxS.join('')) - parseInt(minS.join(''));
};
Enter fullscreen mode Exit fullscreen mode

🐍 Python Version

def maxDiff(num: int) -> int:
    s = list(str(num))

    # Max version
    for d in s:
        if d != '9':
            max_s = [c if c != d else '9' for c in s]
            break
    else:
        max_s = s[:]

    # Min version
    if s[0] != '1':
        min_s = [c if c != s[0] else '1' for c in s]
    else:
        min_s = s[:]
        for i in range(1, len(s)):
            if s[i] != '0' and s[i] != s[0]:
                target = s[i]
                min_s = [c if i == 0 or c != target else '0' for i, c in enumerate(s)]
                break

    return int("".join(max_s)) - int("".join(min_s))
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Test Cases

Input: num = 555
Output: 888   // 999 - 111

Input: num = 9
Output: 8     // 9 - 1

Input: num = 1009
Output: 9009  // 9999 - 99

Input: num = 123456
Output: 820000 // 923456 - 103456
Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity

Time: O(n) β€” where n is the number of digits
Space: O(n) β€” due to new strings created
Enter fullscreen mode Exit fullscreen mode

βœ… Final Thoughts

This problem trains your skills in:

  • Greedy digit replacement
  • Handling leading zeroes
  • Working with strings instead of raw numbers

πŸ“Œ Tip: When dealing with number digit changes, converting to string gives you total control!

If you liked this breakdown, leave a ❀️ and follow for more practical algorithm guides!

Happy coding! πŸ› οΈ

Top comments (2)

Collapse
 
thedeepseeker profile image
Anna kowoski

Good

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Anna

Some comments may only be visible to logged-in visitors. Sign in to view all comments.