Last Substring in Lexicographical Order - Problem

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

A substring is a contiguous sequence of characters within a string. Lexicographical order is the order used in dictionaries - for strings, this means comparing character by character from left to right using their ASCII values.

The last substring lexicographically is the one that would appear last if all possible substrings were sorted in dictionary order.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcab"
Output: "cab"
💡 Note: All substrings: "a", "ab", "abc", "abca", "abcab", "b", "bc", "bca", "bcab", "c", "ca", "cab", "a", "ab", "b". The lexicographically largest is "cab".
Example 2 — Single Character
$ Input: s = "leetcode"
Output: "tcode"
💡 Note: Starting from 't' gives us "tcode" which is lexicographically larger than any substring starting with earlier characters like "l" or "e".
Example 3 — Descending Order
$ Input: s = "zab"
Output: "zab"
💡 Note: The string starts with the largest character 'z', so the entire string "zab" is the lexicographically largest substring.

Constraints

  • 1 ≤ s.length ≤ 4 × 105
  • s contains only lowercase English letters

Visualization

Tap to expand
Last Substring in Lexicographical Order INPUT String s = "abcab" a 0 b 1 c 2 a 3 b 4 All Possible Substrings: "a", "ab", "abc", "abca", "abcab" "b", "bc", "bca", "bcab" "c", "ca", "cab" "a", "ab" "b" Lexicographical Order: a < ab < abc < ... < b < bc < ... < c < ca < cab (LAST) ALGORITHM STEPS 1 Initialize Pointers i=0 (candidate), j=1 (compare) 2 Compare Characters s[i+k] vs s[j+k] for offset k i j Compare Action 0 1 a < b i=1 1 2 b < c i=2 2 3 c > a j=4 3 Update Pointers If s[i+k]<s[j+k]: i=i+k+1 If s[i+k]>s[j+k]: j=j+k+1 4 Return Result s.substring(i) when j >= n Final: i=2, return s[2:] FINAL RESULT Starting index: i = 2 a b c a b Output: "cab" OK - Verified! "cab" is the last substring in lexicographical order Sorted: a, ab, abc... b, bc... c, ca, cab (LAST) Key Insight: The optimal O(n) solution uses two pointers to track the best candidate substring. The lexicographically largest substring always starts with the largest character. We compare substrings character by character, updating pointers to skip impossible candidates. TutorialsPoint - Last Substring in Lexicographical Order | Optimal Two-Pointer Approach
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen