28 Sep 2023, 9:50 PM
28 Sep 2023, 9:50 PM

13. Longest Substring Without Repeating Characters

#leetcode/3

Given a string s, find the length of the longest substring without repeating characters.

Example:

Input: s = "abcabcbb"
Output: 3

Solution

Solution in C++ using two pointers and a hashmap

The idea is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (low and high) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.
Here's the process:

  1. The map stores characters as keys and their indices as values.
  2. We still maintain the low and high pointers and the maxSoFar variable.
  3. We iterate through the string using the high pointer.
  4. If the current character is not in the map or its index is less than left, it means it is a new unique character. Then. we update the map with the character's index and update the maxSoFar if necessary.
  5. If the character is repeating within the current substring, we move the low pointer to the next position after the last occurrence of the character.
  6. We update the index of the current character in the map and continue the iteration.
  7. At the end, we return maxSoFar as the length of the longest substring without repeating characters.
int lengthOfLongestSubstring(string s) {
	unordered_map<char, int> map;
	int maxHere = 0, maxSoFar = 0;
	for(int low = 0, high = 0; high < s.size(); high++) {
		char currChar = s[high];
		
		if(map.contains(currChar) && map[currChar] >= low)
			low = map[currChar] + 1;
		
		maxHere = high - low + 1;
		maxSoFar = max(maxSoFar, maxHere);
		map[currChar] = high;
	}
	return max(maxHere, maxSoFar);
}