714166. Maximum Length

Medium

Maximum Length

Slug: maximum-length--170647 Difficulty: Medium Id: 714166 Topic Tags: Strings, Data Structures Company Tags: None

Summary

Given a string, we need to find the maximum length of any substring that has at least one repeated character. This problem involves working with strings and data structures.

Detailed Explanation

To solve this problem, we can use a simple algorithm. We iterate through the string and for each character, we check if it is already present in our current substring (or window). If it is not, we add it to the substring and update our maximum length. If it is already present, we update our maximum length accordingly.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string max_str and an integer max_len set to 0.
  2. Iterate through the input string s.
  3. For each character c in s, check if it is already present in max_str. If not, add it to max_str and update max_len accordingly.
  4. Update max_len whenever a repeated character is found.
  5. Return max_len.

Time complexity: O(n), where n is the length of the input string.

Space complexity: O(1), since we only need a constant amount of space to store our maximum substring and its length.

Optimized Solutions

Here are some optimized solutions in various programming languages:

Java

View on GeeksforGeeks
public int maximumLength(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }
    
    int max_len = 0;
    String max_str = "";
    
    for (int i = 0; i < s.length(); i++) {
        boolean found = false;
        for (int j = i + 1; j <= s.length(); j++) {
            if (s.substring(i, j).contains(String.valueOf(s.charAt(j - 1)))) {
                found = true;
                break;
            }
        }
        
        if (!found) {
            max_len = Math.max(max_len, j - i);
            max_str = s.substring(i, j);
        }
    }
    
    return max_len;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.