Leetcode 3090. Maximum Length Substring With Two Occurrences
You are given a string, and you are required to find the maximum length of the substring that contains exactly two distinct occurrences of the same character (that is, one character appears at least twice).
Input Constraints: Are there any constraints on the length of the string or the characters it can contain?
Output Format: Should we return the length of such a substring, or the actual substring itself?
import java.util.HashMap;
public class MaxLengthSubstringTwoOccurrences {
public static int maxLengthSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
HashMap<Character, Integer[]> charPositions = new HashMap<>();
int maxLength = 0;
// Populate the HashMap with character positions.
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (!charPositions.containsKey(currentChar)) {
charPositions.put(currentChar, new Integer[] {i, i});
} else {
charPositions.get(currentChar)[1] = i;
}
}
// Calculate the maximum length.
for (Integer[] positions : charPositions.values()) {
if (positions[0] != positions[1]) { // The character has appeared more than once.
int length = positions[1] - positions[0] + 1;
maxLength = Math.max(maxLength, length);
}
}
return maxLength;
}
public static void main(String[] args) {
String testString = "ababc";
System.out.println("Maximum Length: " + maxLengthSubstring(testString)); // Output should be 5.
}
}
O(n)
, where n
is the length of the string. We make a single pass over the input string to populate the HashMap and another pass over the HashMap entries to compute the maximum length.O(1)
auxiliary space for the character positions, but with the added space for the HashMap, it becomes O(k)
, where k
is the number of distinct characters (at most 26 for lowercase English letters).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?