888463. Lexicographical maximum substring of String

Easy

Lexicographical maximum substring of String

Summary

This problem is about finding the lexicographically (lexicographically) maximum substring in a given string. The key concept involved is string manipulation, and we will use dynamic programming to solve this problem.

Detailed Explanation

We can approach this problem by using dynamic programming. First, we initialize an array dp of size n+1, where n is the length of the string. We then iterate over the string, and for each character, we update dp[i] to be the maximum substring ending at index i.

Here's a step-by-step breakdown:

  1. Initialize dp[0] = 0.
  2. Iterate over the string from left to right:
    • For each character c, if dp[i-1] + 1 > dp[i], update dp[i] to be dp[i-1] + 1. This is because we found a longer substring ending at index i.
    • If the current character c is greater than or equal to the last character of the previous maximum substring, update dp[i] to be dp[i-1] + 1. This is because the current character extends the previous maximum substring.
  3. Find the maximum value in dp, which represents the length of the lexicographically maximum substring.

Time complexity: O(n), where n is the length of the string. Space complexity: O(n), for the dynamic programming array dp.

Optimized Solutions

Java

View on GeeksforGeeks
public String lexicographicalMaxSubstring(String s) {
    int n = s.length();
    int[] dp = new int[n+1];
    int maxLen = 0;
    char prevChar = '\0';
    
    for (int i = 0; i < n; i++) {
        if (s.charAt(i) >= prevChar) {
            dp[i] = dp[i-1] + 1;
        } else {
            dp[i] = 1;
        }
        prevChar = s.charAt(i);
        maxLen = Math.max(maxLen, dp[i]);
    }
    
    return s.substring(maxLen-1, n);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.