| Date | Stopwatch | Y/N | Feedback |
|---|---|---|---|
| Jun 15, 2025 | 36m 21s | Y |
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.
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:
Space Complexity: