
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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".
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
Example (Python)
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))
Input
"level"
Output
3
- Related Articles
- Largest Substring Between Two Equal Characters in a string in JavaScript
- Program to find length of substring with consecutive common characters in Python
- How to get substring between two similar characters in JavaScript?
- Finding longest substring between two same characters JavaScript
- Program to equal two strings of same length by swapping characters in Python
- Program to find largest merge of two strings in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Program to check two strings can be equal by swapping characters or not in Python
- Program to find the largest product of two distinct elements in Python
- Program to find longest awesome substring in Python
- Program to find the largest sum of the path between two nodes in a binary tree in Python
- Program to find largest distance pair from two list of numbers in Python
- Longest Substring Without Repeating Characters in Python
- Program to find out the length of the substring where two times the number of zeroes in substring is lesser than or equal to three times the number of ones in the substring in Python
- Program to find the length of longest substring which has two distinct elements in Python

Advertisements