Problem 1163

Abstract / Summary

Given a string, find the last substring in dictionary order when listing all possible substrings.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1163.py

class Solution:
    def lastSubstring(self, s: str) -> str:
        result = ""

        # first letter
        first  = max(s)
        pos    = s.find(first)
        while pos != -1:
            result = max(result, s[pos : ])
            pos    = s.find(first, pos + 1)

        return result
12 lines | 307 bytes | submitted May 8, 2024 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 35% (100k+ submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The lastSubstring method receives a string s and returns the lexicographically greatest substring that can be obtained from s. It works by first identifying the highest-valued character in the entire string, then examining every occurrence of that character as a potential start of the optimal substring. For each start position it extracts the suffix beginning there and keeps the maximum suffix seen so far. The final value of result is the desired substring.

Determining the Highest Character

The algorithm begins by locating the character with the greatest lexical value in the input. This is achieved with the built-in max function applied to the whole string.

first = max(s)

By focusing only on the maximal character, the method narrows the search space to those positions that could possibly lead to the overall greatest substring, because any substring that starts with a lower character can never outrank a substring that starts with the highest character.

Enumerating All Occurrences of the Maximal Character

Having identified the maximal character, the code searches for every index where it appears. The str.find method is used in a loop, advancing the search position after each match.

pos = s.find(first)
while pos != -1:
    ...
    pos = s.find(first, pos + 1)

The loop continues until find returns -1, indicating that no further occurrences exist. This systematic enumeration guarantees that every candidate suffix beginning with the maximal character is examined.

Comparing Candidate Suffixes

Inside the loop, the substring from the current position to the end of the string is extracted and compared with the best result found so far. The built-in max function performs the lexical comparison.

result = max(result, s[pos:])

If the newly extracted suffix is lexicographically larger than the current result, it replaces result. Because result is initialized to the empty string, the first candidate automatically becomes the provisional answer.

Returning the Final Substring

After all occurrences have been processed, the method returns the stored result, which now holds the lexicographically greatest suffix.

return result

Edge Cases Handled by the Logic

When the input string consists of a single repeated character, every position yields an identical suffix, and the loop still processes each occurrence without error, ultimately returning the full string. If the maximal character appears only once, the loop executes a single iteration, and the suffix starting at that unique position is returned. The use of str.find with a start index ensures that overlapping occurrences are correctly handled, and the while-loop termination condition cleanly exits when no further matches exist.

Implicit Performance Optimizations

The implementation leverages Python’s highly optimized built-in functions. Computing the maximal character with max(s) runs in linear time and avoids manual scanning. The str.find method is implemented in C and provides fast substring search, reducing overhead compared to a manual character-by-character scan. By restricting the candidate set to suffixes that begin with the highest character, the algorithm eliminates unnecessary comparisons with substrings that could never be optimal, thereby cutting down the number of lexical comparisons performed. The repeated use of max for string comparison also benefits from C-level optimizations for lexicographic ordering.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of building blocks, and each block has a different letter written on it. This code acts like a very clever helper whose job is to find the biggest word hiding inside that row.

First, the helper looks at all the blocks to see which letter comes last in the alphabet. If the letters were dancing, the letter closest to the end of the alphabet would be the winner. The helper marks every spot where it finds that winning letter.

Next, the helper starts a little game of comparison at each of those spots. It looks at the string of letters starting from each of those winning spots and compares them to see which string is the absolute biggest. Just like when you compare two numbers to see which is higher, the computer compares the letters to see which arrangement is the mightiest. By looking at all these pieces, the helper discovers exactly which slice of the row is the greatest one.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.00 | σ = 1.68

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
24 links | 13 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 medium 1 hard
4 solutions   May 8, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality