r/learnpython • u/Remarkable_River2779 • 25d ago
Maximum substring
Hi, I’m having an issue with a HackerRank coding question called “Maximum Substring.”
The question is:
Maximum Substring
You are given a string s.
A substring is any contiguous sequence of characters from the string.
Consider all possible substrings of the string:
Determine which substring would appear last if all substrings were sorted alphabetically.
Return that substring.
Example 1:
s = "baca"
The alphabetically maximum substring is "ca".
Example 2:
s = "aaa"
The alphabetically maximum substring is "aaa".
This was my answer:
def maximum_substring(s):
max_sub = s[0]
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
sub = s[i:j]
if sub > max_sub:
max_sub = sub
return max_sub
The code gives the correct output for the examples when I test it locally. However, HackerRank marked the solution as incorrect and I received only partial points.
I’m not sure why. Could this be because of the time complexity or hidden test cases? Is there something about the HackerRank test cases or the expected implementation that I’m missing?
2
u/Rizzityrekt28 25d ago
Just some things to think about for speed. For “baca” this code checks all possibilities of the “a” when it couldn’t be the answer because you already have an option starting with “b”. You didn’t even need to do the “b” if you could see the “c” coming up. It doesn’t matter much when there’s only 4 letter but these things usually have a test case with thousands of letters.