Skip to content

Commit ecb222f

Browse files
committed
solve: longest substring without repeating characters
1 parent bcae4b6 commit ecb222f

File tree

1 file changed

+36
-0
lines changed
  • longest-substring-without-repeating-characters

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {string} str
3+
* @return {number}
4+
*/
5+
var lengthOfLongestSubstring = function (str) {
6+
let maxLength = 0;
7+
let left = 0;
8+
const lastSeenCharIndexMap = {};
9+
10+
for (let right = 0; right < str.length; right++) {
11+
const currentChar = str[right];
12+
13+
// If the current character was seen before, update the left pointer
14+
if (lastSeenCharIndexMap[currentChar] >= left) {
15+
left = lastSeenCharIndexMap[currentChar] + 1;
16+
}
17+
18+
lastSeenCharIndexMap[currentChar] = right;
19+
20+
maxLength = Math.max(maxLength, right - left + 1);
21+
}
22+
23+
return maxLength;
24+
};
25+
26+
/**
27+
* Time Complexity: O(n)
28+
* - The right pointer iterates through the string once, making it O(n).
29+
* - The left pointer only moves when a duplicate character is found, ensuring each character is processed at most twice.
30+
* - Thus, the total time complexity is O(n).
31+
*
32+
* Space Complexity: O(min(n, m))
33+
* - The space complexity is determined by the size of the character map, which stores the indices of characters in the current window.
34+
* - In the worst case, the map could store all unique characters in the string.
35+
* - Thus, the space complexity is O(min(n, m)), where n is the length of the string and m is the character set size.
36+
*/

0 commit comments

Comments
 (0)