Created
June 4, 2025 17:38
-
-
Save SuryaPratapK/3b81d800fe5f3399e4e2fffd6a907fd1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string answerString(string word, int numFriends) { | |
int n = word.size(); | |
if(numFriends==1) return word; | |
int i = 0; | |
int j = 1; | |
int gap = 0; | |
//Find largest suffix | |
while(j+gap < n){ | |
if(word[i+gap]==word[j+gap]) gap++; | |
else if(word[i+gap]<word[j+gap]){ | |
int save = i; | |
i = j; | |
j = max(j+1,save+gap+1); | |
gap = 0; | |
}else{ | |
j = j+gap+1; | |
gap = 0; | |
} | |
} | |
return word.substr(i,n-numFriends+1); | |
} | |
}; | |
/* | |
//JAVA | |
class Solution { | |
public String answerString(String word, int numFriends) { | |
int n = word.length(); | |
if (numFriends == 1) return word; | |
int i = 0; | |
int j = 1; | |
int gap = 0; | |
// Find largest suffix | |
while (j + gap < n) { | |
if (word.charAt(i + gap) == word.charAt(j + gap)) { | |
gap++; | |
} else if (word.charAt(i + gap) < word.charAt(j + gap)) { | |
int save = i; | |
i = j; | |
j = Math.max(j + 1, save + gap + 1); | |
gap = 0; | |
} else { | |
j = j + gap + 1; | |
gap = 0; | |
} | |
} | |
return word.substring(i, i + n - numFriends + 1); | |
} | |
} | |
#python | |
class Solution: | |
def answerString(self, word: str, numFriends: int) -> str: | |
n = len(word) | |
if numFriends == 1: | |
return word | |
i = 0 | |
j = 1 | |
gap = 0 | |
# Find largest suffix | |
while j + gap < n: | |
if word[i + gap] == word[j + gap]: | |
gap += 1 | |
elif word[i + gap] < word[j + gap]: | |
save = i | |
i = j | |
j = max(j + 1, save + gap + 1) | |
gap = 0 | |
else: | |
j = j + gap + 1 | |
gap = 0 | |
return word[i:i + n - numFriends + 1] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment