702740. Max Length Removal

Easy

Max Length Removal

Slug: max-length-removal0452 Difficulty: Easy Id: 702740 Topic Tags: Arrays, Strings, Data Structures

Summary

The problem is about removing characters from a given string until the length of the string becomes equal to or less than a certain maximum allowed length. The goal is to find the longest possible substring that can be obtained by removing characters.

Detailed Explanation

To solve this problem, we will use a straightforward algorithm. We iterate over the input string and count the number of characters in each substring until we reach the maximum allowed length. If the current substring's length exceeds the maximum allowed length, we update our answer with the longest possible substring found so far.

Here is the step-by-step breakdown:

  1. Initialize an empty string result to store the longest possible substring.
  2. Iterate over the input string from left to right.
  3. For each character, count the number of characters in the current substring (from the start of the string to the current position).
  4. If the length of the current substring exceeds the maximum allowed length, update result with the previous longest possible substring found.
  5. Continue this process until we have processed all characters in the input string.

Time complexity: O(n), where n is the length of the input string. Space complexity: O(1), as we only use a constant amount of space to store our result and variables.

Optimized Solutions

Java

View on GeeksforGeeks
public String maxLengthRemoval(String s, int maxLen) {
    if (s.length() <= maxLen) return s;
    StringBuilder result = new StringBuilder();
    int currentLen = 0;
    for (char c : s.toCharArray()) {
        currentLen++;
        if (currentLen > maxLen) {
            result.setLength(0);
            currentLen = 1;
        }
        result.append(c);
    }
    return result.toString();
}

DevExCode

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

© 2026 DevExCode. All rights reserved.