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: "abcab" → "cab"Input String:abcab01234Possible Substrings:"abcab""bcab""cab""ab""b"↑ Lexicographically LargestTwo pointers efficiently find position 2Output: "cab"
Understanding the Visualization
1
Input
String s = "abcab"
2
Process
Find best starting position using two pointers
3
Output
Return suffix from best position: "cab"
Key Takeaway
🎯 Key Insight: Use two pointers to compare potential starting positions and eliminate inferior ones efficiently
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