LeetCode 1624: Largest Substring Between Two Equal Characters Solution

Master LeetCode problem 1624 (Largest Substring Between Two Equal Characters), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1624. Largest Substring Between Two Equal Characters

Problem Explanation

Explanation

To solve this problem, we can iterate over the given string s and keep track of the first and last occurrence of each character. For each character, we calculate the length of the substring between its first and last occurrence. We update the maximum length found so far. If no substring is found, we return -1.

  • We can use a hashmap to store the first occurrence of each character.
  • We iterate over the string to update the last occurrence of each character.
  • For each character, we calculate the length of the substring between its first and last occurrence.
  • We update the maximum length found so far.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string s.

Space Complexity

The space complexity of this solution is O(1) since the hashmap stores at most 26 lowercase English letters.

Solution Code

class Solution {
    public int maxLengthBetweenEqualCharacters(String s) {
        int[] firstIndex = new int[26];
        int maxLength = -1;
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (firstIndex[c - 'a'] == 0) {
                firstIndex[c - 'a'] = i + 1;
            } else {
                maxLength = Math.max(maxLength, i - firstIndex[c - 'a']);
            }
        }
        
        return maxLength;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1624 (Largest Substring Between Two Equal Characters)?

This page provides optimized solutions for LeetCode problem 1624 (Largest Substring Between Two Equal Characters) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1624 (Largest Substring Between Two Equal Characters)?

The time complexity for LeetCode 1624 (Largest Substring Between Two Equal Characters) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1624 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1624 in Java, C++, or Python.

Back to LeetCode Solutions