Problem Description
Given a string s, return the last substring of s in lexicographical order. The challenge is to find an efficient method to compute the answer without generating and comparing all possible substrings.
Key Insights
- The problem is to determine the lexicographically largest substring.
- A brute-force approach generating all substrings would be too slow given the input constraints.
- A two-pointer approach can efficiently compare candidate substrings without extra space.
- The idea is to use one pointer as the start of the current best candidate and another pointer to scan possible candidates.
- When comparing equal characters, use a counter to determine differences, then adjust pointers based on the comparison outcome.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The solution uses a two-pointer technique. One pointer (start) designates the beginning of the current best candidate substring, while another pointer (i) scans through the string. A counter (k) is used to compare characters of the candidate substrings. If the character at the candidate pointer is less than the character at the current pointer, update the start pointer and reset the counter. Otherwise, skip ahead appropriately. This method avoids the need to generate all substrings and operates in linear time with constant extra space.