[Leetcode] 3403. Find the Lexicographically Largest String From the Box I

whitehousechef·2025년 6월 4일

https://leetcode.com/problems/find-the-lexicographically-largest-string-from-the-box-i/description/?envType=daily-question&envId=2025-06-04

initial

So my initial attempt of just getting the lexicographically largest alphabet in string and the index and

slicing word[index:index+n-friend+1] is wrong. btw that n-friend+1 is the pattern just think like u wan the longest possible substring

cuz if u have
print(answerString("nbjnc", 2)) # Output should be "nc"

my initial sol would be getting nbjn as the answer but nc is greater than that.

sol

instead we should compare for each index, the maxium possible width and slice that substring and see if it is greater than the stored tmp string variable.

One precaution is that
word = "gh" and friend = 1
print(word[1:3]) # Outputs: "h"

my sol would be getting h is the answer cuz h>gh. But actually if u have just 1 friend (alone), then word is the answer. So that is the edge case

ALSO V IMPT slicing string even if end index exceeds the length of string works fine. It slices up to the end of the string.

word = "gh" and friend = 1
print(word[1:3]) # Outputs: "h"

class Solution:
    def answerString(self, word: str, numFriends: int) -> str:
        n = len(word)
        width = n-numFriends+1
        ans=""
        if numFriends==1:
            return word
        for i in range(n):
            if word[i:i+width]>ans:
                ans= word[i:i+width]
        return ans

complexity

n time and space

0개의 댓글