- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

"level"

3

- Related Questions & Answers
- Largest Substring Between Two Equal Characters in a string in JavaScript
- Finding longest substring between two same characters JavaScript
- How to get substring between two similar characters in JavaScript?
- Program to find largest merge of two strings in Python
- Program to find length of substring with consecutive common characters in Python
- Program to equal two strings of same length by swapping characters in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Program to find the largest product of two distinct elements in Python
- Python program to find difference between two timestamps
- Program to check two strings can be equal by swapping characters or not 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
- Program to find minimum operations needed to make two arrays sum equal in Python
- Program to find maximum equal frequency in Python

Advertisements