Skip to content

Latest commit

 

History

History
56 lines (46 loc) · 2.97 KB

File metadata and controls

56 lines (46 loc) · 2.97 KB

2566. Maximum Difference by Remapping a Digit (Easy)

Link: https://leetcode.com/problems/maximum-difference-by-remapping-a-digit?envType=daily-question&envId=2025-06-14


Date Stopwatch Y/N Feedback
Jun 15, 2025 36m 21s Y

Walk-through:

Convert num to string, so we can access num by index. Use hashmaps to map each digit with digit, then find the first non-9 digit from num and the first non-0 digit from num as well, change the value to 9 for the max and change to 0 for min. Finally, follow num again to find max_str and min_str from hashmaps. Convert to int() and calculate the difference.


Python:

class Solution:
    def minMaxDifference(self, num: int) -> int:
        # Q: Return difference of max and min by remappping 1 digit
        # S: Create hashmap to map each digit with each digit. Loop over num to find max, if num[0] != '9', change the value of num[0] in hashmap to 9. Otherwise, find the non9 element and change the value to 9
        # Min: same thing, but change from 9 to 0
        # Finally, follow num to get the max digit and min digit
        # TC: O(n), n=len(num), SC: O(n)

        num = str(num)
        max_hashmap, min_hashmap = {}, {}
        # map digits into hashmaps
        for c in num:
            max_hashmap[c] = c
            min_hashmap[c] = c
        # Change the first non-nine element to 0
        for c in num:
            if c != '9':
                max_hashmap[c] = '9'
                break
        # Change the first non-zero element to 0
        for c in num:
            if c != '0':
                min_hashmap[c] = '0'
                break
        # Recover new two ints
        a, b = "", ""
        for c in num:
            a += max_hashmap[c]
            b += min_hashmap[c]
        return int(a) - int(b)

Time Complexity: $O(n)$
Space Complexity: $O(n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms