13: Find the longest substring without repeating characters.
⏳⌚ 00:00:00

Question:-

Find the longest substring without repeating characters.
Example 1:
Input:
str = "hello"
Output: "hel"
Example 2:
Input:
str = "geeksforgeeks"
Output: "eksforg"

Steps to solve:-

1. Data Structures Used:- unordered_map char, int charIndex: An unordered map is used to store the index at which each character was last encountered in the input string. This map helps keep track of characters and their positions within the string.
2. Variables Initialization:-
maxLength: This variable keeps track of the length of the longest substring found without repeating characters.
startIndex: It represents the starting index of the current substring being examined.
maxStartIndex: This variable stores the starting index of the longest substring found so far.
3. Looping Through the Input String:- The code uses a for loop to iterate through each character in the input string s. The variable endIndex represents the index of the current character being examined.
4. Character Handling:- For each character c encountered in the input string: If the character c is already present in the charIndex map (i.e., charIndex.find(c) != charIndex.end()), and its index (charIndex[c]) is greater than or equal to the startIndex, it means that the character c has been encountered within the current substring. To avoid repeating characters, the startIndex is updated to the next index after the last occurrence of c. The index of the character c is updated in the charIndex map, indicating the most recent occurrence.
5. Calculating Substring Length:- After each character is processed, the code calculates the length of the current substring without repeating characters (currentLength) as the difference between endIndex and startIndex plus 1.
6. Updating Longest Substring:- If the currentLength is greater than the maxLength, the maxLength is updated to currentLength, and the maxStartIndex is updated to the current startIndex. This step ensures that we keep track of the longest substring found so far.
7. Returning the Result:- Finally, the code returns the longest substring without repeating characters by extracting it from the input string s using the substr function with the maxStartIndex and maxLength.
8. Main Function:- In the main function, the user is prompted to enter a string, which is then passed to the longestSubstring function. The result is printed, showing the longest substring without repeating characters.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(1)