Skip to main content
Back to problems
#1163
Hard Algorithms

Last substring in lexicographical order

Two Pointers String
35.0% acceptance
Feb 25, 2026
664
459
Given a string s, return the last substring of s in lexicographical order.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn last_substring(s: String) -> String {
    let b = s.as_bytes();
    let n = b.len();
    let (mut i, mut j, mut k) = (0usize, 1usize, 0usize);
    while j + k < n {
      if b[i + k] == b[j + k] {
        k += 1;
      } else if b[i + k] < b[j + k] {
        i += k + 1;
        if i >= j { j = i + 1; }
        k = 0;
      } else {
        j += k + 1;
        k = 0;
      }
    }
    s[i..].to_string()
  }
}