DEV Community

Cover image for 🧮 Beginner’s Guide to "Maximum Difference by Remapping a Digit" – LeetCode 2566 (C++ | JavaScript | Python)
Om Shree
Om Shree

Posted on

5 3 3 4 2

🧮 Beginner’s Guide to "Maximum Difference by Remapping a Digit" – LeetCode 2566 (C++ | JavaScript | Python)

Hey Devs! 👋

Let’s break down a fun greedy + string manipulation problem — 2566: Maximum Difference by Remapping a Digit. This one is perfect for sharpening your skills in character replacement and greedy thinking.


📝 Problem Statement

Given a number num, Bob is allowed to remap exactly one digit (0–9) to any other digit (including itself). All occurrences of the selected digit are changed.

Your job:
Return the maximum difference between the largest and smallest number Bob can create by remapping one digit.

✅ Leading zeroes are allowed after remapping.


🧩 Example

Input: num = 11891
Output: 99009

Explanation:

  • For maximum value: Replace '1' → '9' → becomes 99899
  • For minimum value: Replace '1' → '0' → becomes 890
  • Difference = 99899 - 890 = 99009

💡 Strategy & Intuition

To get:

  • Maximum value: Change the first non-'9' digit to '9'
  • Minimum value: Change the first digit to '0'

Why?

  • Changing leftmost significant digits impacts the number most.
  • Changing the same digit in all its occurrences ensures a larger shift.

⚙️ C++ Implementation

class Solution {
 public:
  int minMaxDifference(int num) {
    const string s = to_string(num);
    const char to9 = s[firstNotNineIndex(s)];
    const char to0 = s[0];
    return getMax(s, to9) - getMin(s, to0);
  }

 private:
  int firstNotNineIndex(const string& s) {
    for (int i = 0; i < s.length(); ++i)
      if (s[i] != '9')
        return i;
    return 0;
  }

  int getMax(string s, char to9) {
    for (char& c : s)
      if (c == to9)
        c = '9';
    return stoi(s);
  }

  int getMin(string s, char to0) {
    for (char& c : s)
      if (c == to0)
        c = '0';
    return stoi(s);
  }
};
Enter fullscreen mode Exit fullscreen mode

🌐 JavaScript Version

var minMaxDifference = function(num) {
    let s = num.toString();
    const to9 = [...s].find(c => c !== '9') || s[0];
    const to0 = s[0];

    const getMax = s => parseInt(s.replaceAll(to9, '9'));
    const getMin = s => parseInt(s.replaceAll(to0, '0'));

    return getMax(s) - getMin(s);
};
Enter fullscreen mode Exit fullscreen mode

🐍 Python Version

def minMaxDifference(num: int) -> int:
    s = str(num)
    to9 = next((c for c in s if c != '9'), s[0])
    to0 = s[0]

    max_val = int(s.replace(to9, '9'))
    min_val = int(s.replace(to0, '0'))

    return max_val - min_val
Enter fullscreen mode Exit fullscreen mode

🧪 Test Cases

Input: num = 11891
Output: 99009

Input: num = 90
Output: 99

Input: num = 999
Output: 999 - 0 = 999

Input: num = 1000
Output: 9000 - 0 = 9000
Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity

Time Complexity: O(n) — One pass for replacement (n = number of digits)
Space Complexity: O(1) — Only a few variables used
Enter fullscreen mode Exit fullscreen mode

✅ Conclusion

This problem is an excellent exercise in greedy digit manipulation and reinforces string traversal techniques.

Remember:

  • Maximize by turning first non-9 into 9
  • Minimize by turning first digit into 0

Drop a ❤️ if this helped, and stay tuned for more bitesize breakdowns!

Happy coding, folks! 🚀


A Layered Approach to Mobile App Protection

A Layered Approach to Mobile App Protection

Attackers use static analysis to understand how your app functions and the data it contains. By using multiple layers of protections like code obfuscation and string encryption, you can prevent attackers from accessing your app.

Read more

Top comments (6)

Collapse
 
thedeepseeker profile image
Anna kowoski

Good Explanation

Collapse
 
om_shree_0709 profile image
Om Shree

thanks anna

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Honestly love how this is laid out makes me wanna go solve a few myself

Collapse
 
om_shree_0709 profile image
Om Shree

Glad you liked it sir ❤️

Collapse
 
parag_nandy_roy profile image
Parag Nandy Roy

Super clean breakdown..

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

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

Announcing the First DEV Education Track: "Build Apps with Google AI Studio"

The moment is here! We recently announced DEV Education Tracks, our new initiative to bring you structured learning paths directly from industry experts.

Dive in and Learn

DEV is bringing Education Tracks to the community. Dismiss if you're not interested. ❤️