[Leetcode] 2566. Maximum Difference by Remapping a Digit

whitehousechef·2025년 6월 16일

https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/description/

initial

i fucking didnt read the q properly. It said one mapping only. But i thought its continuous mapping. So its very straight forward. Once we find an integer that isnt 9 we map that digit to 9 for the entire string. Same for the min Val.

sol

class Solution:
    def minMaxDifference(self, num: int) -> int:
        maxVal,minVal=9,0
        for i in str(num):
            i=int(i)
            if i!=9:
                maxVal=i
                break
        for i in str(num):
            i=int(i)
            if i!=0:
                minVal=i
                break
        numCopy1 = str(num)
        numCopy2 = str(num)
        maxAns= int(str(numCopy1).replace(str(maxVal),'9'))
        minAns =  int(str(numCopy2).replace(str(minVal),'0'))
        return maxAns-minAns

much more succinct using next()

btw replace() doesnt modify original string so u have to create new strings like my prev sol!

next() is finding any d that comes first that isnt digit 9 or 0. The default parameter can be set as '9' or '0' to fit in the logic.

class Solution:
    def minMaxDifference(self, num: int) -> int:
        s = str(num)
        
        # Find first non-9 digit for max, first non-0 digit for min
        max_digit = next((d for d in s if d != '9'), '9')
        min_digit = next((d for d in s if d != '0'), '0')
        
        # Replace and convert
        max_val = int(s.replace(max_digit, '9'))
        min_val = int(s.replace(min_digit, '0'))
        
        return max_val - min_val

complexity

i thought replace() is time nm so I was gonna say nm

but the character that we are replacing is just 1 character instead of a string. So it is o(n)

overall time = n
space = n

0개의 댓글