Last Substring in Lexicographical Order — LeetCode 1163 Python Solution

HardTwo PointersString
Problem
#1163
Reading time
3 min

The problem

Given a string s, return the last substring of s in lexicographical order.

Example

Input
s = "abab"
Output
"bab"
Explanation
The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".

Python solution

Python
class Solution:
    def lastSubstring(self, s: str) -> str:
        i, j, k = 0, 1, 0
        while j + k < len(s):
            if s[i + k] == s[j + k]:
                k += 1
            elif s[i + k] < s[j + k]:
                i += k + 1
                k = 0
                if i >= j:
                    j = i + 1
            else:
                j += k + 1
                k = 0
        return s[i:]

Complexity

MeasureComplexity
TimeO(n), where n is the length of string s
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1163. Last Substring in Lexicographical Order is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1163. Last Substring in Lexicographical Order?
LeetCode 1163. Last Substring in Lexicographical Order is rated Hard on LeetCode.
What is the time complexity of LeetCode 1163. Last Substring in Lexicographical Order?
The Python solution on this page runs in O(n), where n is the length of string s.
What is the space complexity of LeetCode 1163. Last Substring in Lexicographical Order?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1163. Last Substring in Lexicographical Order cover?
LeetCode 1163. Last Substring in Lexicographical Order is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview