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
Finding longest substring between two same characters JavaScript
In this problem, we need to find the longest substring between two same characters in a string using JavaScript. We'll use a Map to track character positions and calculate distances between matching characters.
Problem Explanation
Given a string like 'abcdefa', we have two 'a' characters with 'bcdef' between them (5 characters). This becomes our longest substring between same characters.
Algorithm Steps
Step 1 ? Define function longestSubstring with parameter 'str'.
Step 2 ? Initialize maxLength = 0 and begin = -1 to track the longest substring.
Step 3 ? Create a Map called charMap to store character positions.
Step 4 ? Loop through each character in the string.
Step 5 ? For each character, check if it was seen before in the map.
Step 6 ? If found, calculate distance between current and previous position. Update maxLength and begin if this distance is larger.
Step 7 ? Return the longest substring found between same characters.
Implementation
function longestSubstring(str) {
let maxLength = 0;
let begin = -1;
let charMap = new Map();
for (let i = 0; i < str.length; i++) {
const char = str[i];
// Check if character has been seen before
if (charMap.has(char)) {
const previousIndex = charMap.get(char);
const len = i - previousIndex - 1; // Distance between same characters
if (len > maxLength) {
maxLength = len;
begin = previousIndex + 1;
}
}
// Always update the character's latest position
charMap.set(char, i);
}
if (begin === -1) {
return "";
}
return str.substring(begin, begin + maxLength);
}
// Test the function
const str = "abcaabcdaaaefghij";
const longSubstr = longestSubstring(str);
console.log("Input string:", str);
console.log("The longest substring between same characters:");
console.log(longSubstr);
Input string: abcaabcdaaaefghij The longest substring between same characters: abcdaa
How It Works
The algorithm tracks each character's position in a Map. When it encounters a character again, it calculates the substring length between the two occurrences. The key insight is that we always update the character's position to find the longest possible substring for each character pair.
Additional Example
// Test with different strings
const testStrings = ["abba", "abcdef", "aabbcc", "programming"];
testStrings.forEach(str => {
const result = longestSubstring(str);
console.log(`String: "${str}" ? Result: "${result}"`);
});
String: "abba" ? Result: "bb" String: "abcdef" ? Result: "" String: "aabbcc" ? Result: "abbc" String: "programming" ? Result: "ogrammin"
Complexity Analysis
Time Complexity: O(n) where n is the length of the input string. We iterate through the string once, performing constant-time operations for each character.
Space Complexity: O(m) where m is the number of unique characters in the string. The Map stores at most one entry per unique character.
Conclusion
This solution efficiently finds the longest substring between two same characters using a single pass through the string. The Map data structure provides optimal character position tracking for this problem.
