File: maximum-difference-by-remapping-a-digit/solution.py

Date: 2026-06-06

Time: 17:37

Purpose

This file is a self-contained LeetCode solution for LeetCode 2566: Maximum Difference by Remapping a Digit. It owns both the algorithm (diffMaxMin) and its test suite (TestDiffMaxMin). The problem asks: given an integer, you can pick one digit and remap all its occurrences to any other digit (once to maximize, once to minimize). Return the difference between the max and min achievable values.

Key Components

diffMaxMin(num: int) -> int

The sole algorithmic function. Contract:

TestDiffMaxMin

Nine unit tests covering LeetCode examples, edge cases (single digit, all-9s, all-same digits, 1, upper constraint 10^8).

Patterns

Greedy digit selection via string replacement. The algorithm converts the number to a string, then uses str.replace to simulate digit remapping. Two greedy choices:

1. Maximize: Find the first digit that isn't 9 and remap all its occurrences to 9. If the number is already all 9s, max_val stays as num.

2. Minimize: Always remap the leading digit (s[0]) to 0. This works because leading zeros are allowed in the "remapped" value (they collapse via int()), and remapping the leading digit guarantees the largest positional drop.

Self-contained module pattern: Solution + tests in one file, runnable via python solution.py or a test runner.

Dependencies

Flow

1. Convert num to string s.

2. Max path: Iterate through digits of s. On the first non-9 digit d, replace all occurrences of d with '9' and parse back to int. If all digits are 9, skip (max_val remains num).

3. Min path: Replace all occurrences of s[0] with '0', parse to int. Leading zeros vanish naturally via int().

4. Return maxval - minval.

For num = 11891: max remaps 1→999899, min remaps 1→0890. Result: 99009.

Invariants

Error Handling

None. The function trusts the caller to provide a valid positive integer per the LeetCode constraint. No input validation, no exceptions. int() on a string of all zeros returns 0, which is the correct behavior for the min case.

Topics to Explore

Beliefs