Leetcode 1624: Largest Substring Between Two Equal Characters

grid47
grid47
Exploring patterns and algorithms
May 28, 2024 4 min read

Given a string s, find the length of the longest substring between two equal characters, excluding the two characters themselves. If no such substring exists, return -1.
Problem
Approach
Steps
Complexity
Input: You are given a string s (1 <= s.length <= 300) consisting of lowercase English letters.
Example: s = "zz"
Constraints:
• 1 <= s.length <= 300
• s contains only lowercase English letters.
Output: Return the length of the longest substring between two equal characters, excluding the two characters themselves. If no such substring exists, return -1.
Example: Output: 0
Constraints:
• If no such substring exists, return -1.
Goal: To find the longest substring between two equal characters and calculate its length.
Steps:
• Use a map to store the first occurrence of each character as you iterate through the string.
• When encountering a character that has been seen before, calculate the length of the substring between the two occurrences.
• Update the maximum length if a longer substring is found.
Goal: The string is guaranteed to be non-empty and consist only of lowercase English letters.
Steps:
• 1 <= s.length <= 300
• s contains only lowercase English letters.
Assumptions:
• The input string will not be empty and will only contain lowercase English letters.
Input: s = "zz"
Explanation: The optimal substring here is an empty substring between the two 'z's.

Input: s = "xyzxy"
Explanation: The optimal substring here is "yzx" between the two 'x's.

Input: s = "abcdef"
Explanation: There are no repeated characters, so no valid substring exists.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus