Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find largest substring between two equal characters in Python
Suppose we have a string s, we have to find the length of the longest substring between two equal letters or elements, excluding the two characters. If we cannot find such substring, then return -1.
So, if the input is like s = "level", then the output will be 3 as optimal substrings can be either "lev" or "vel".
Algorithm
To solve this, we will follow these steps −
memo := a new map
-
for i in range 0 to size of s - 1, do
-
if s[i] is in memo, then
insert i at the end of memo[s[i]]
-
otherwise,
memo[s[i]] := a list with only one element i
-
best := 0
-
for each key in memo, do
best := maximum of best and (last element of memo[key] - first element of memo[key])
return best - 1
Implementation
def solve(s):
memo = {}
for i in range(len(s)):
if s[i] in memo:
memo[s[i]].append(i)
else:
memo[s[i]] = [i]
best = 0
for key in memo:
best = max(best, memo[key][-1] - memo[key][0])
return best - 1
s = "level"
print(solve(s))
The output of the above code is −
3
How It Works
The algorithm works by tracking all positions of each character in a dictionary. For each character that appears multiple times, it calculates the distance between its first and last occurrence, then subtracts 1 to exclude the matching characters themselves.
Example with Different Input
def solve(s):
memo = {}
for i in range(len(s)):
if s[i] in memo:
memo[s[i]].append(i)
else:
memo[s[i]] = [i]
best = 0
for key in memo:
best = max(best, memo[key][-1] - memo[key][0])
return best - 1
# Test with different strings
test_cases = ["level", "abcba", "abc", "aa"]
for s in test_cases:
result = solve(s)
print(f"String: '{s}' ? Length: {result}")
String: 'level' ? Length: 3 String: 'abcba' ? Length: 3 String: 'abc' ? Length: -1 String: 'aa' ? Length: -1
Conclusion
This solution efficiently finds the longest substring between two equal characters using a dictionary to track character positions. The time complexity is O(n) where n is the length of the string.
