|
| 1 | +/** |
| 2 | + * @param {string} s |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | + |
| 6 | +// 🌟 sliding window technique |
| 7 | + |
| 8 | +// Time Complexity: O(n) |
| 9 | +// Why it's O(n) |
| 10 | +// - The end pointer iterates over the string exactly once (O(n)). |
| 11 | +// - The start pointer also only moves forward without re-processing elements (O(n)). |
| 12 | +// - Therefore, the total amount of work done is proportional to the length of the string (n). |
| 13 | +// - So, even though there is a while loop inside the for loop, the total work done (number of operations) is still linear, O(n), because the start and end pointers together move across the string just once. |
| 14 | +// - This is the key reason why the time complexity is O(n), even with nested loops. |
| 15 | + |
| 16 | +// Space Complexity: O(k), where k k is the length of the longest substring without repeating characters. |
| 17 | +// In the worst case, k = n, so O(n) |
| 18 | + |
| 19 | +var lengthOfLongestSubstring = function (s) { |
| 20 | + let start = 0; |
| 21 | + let longest = 0; |
| 22 | + let subString = new Set(); |
| 23 | + |
| 24 | + for (let end = 0; end < s.length; end++) { |
| 25 | + while (subString.has(s[end])) { |
| 26 | + // Shrink the window by moving start |
| 27 | + subString.delete(s[start]); |
| 28 | + start += 1; |
| 29 | + } |
| 30 | + |
| 31 | + subString.add(s[end]); |
| 32 | + longest = Math.max(longest, end - start + 1); |
| 33 | + } |
| 34 | + |
| 35 | + return longest; |
| 36 | +}; |
| 37 | + |
| 38 | +// 🛠️ Solution 1 |
| 39 | +// Time Complexity: O(n^2), where n is the length of the string s |
| 40 | +// Space Complexity: O(k), where k is the length of the longest substring without repeating characters (k ≤ n) |
| 41 | + |
| 42 | +// why the space complexity is not just O(n): |
| 43 | +// - Saying O(n) is technically correct in the worst case, |
| 44 | +// - but it hides the fact that the actual space usage is proportional to the length of the longest substring without repeats, |
| 45 | +// - which could be much smaller than n in many practical cases (e.g., for a string like "aaabbbccc"). |
| 46 | + |
| 47 | +// var lengthOfLongestSubstring = function (s) { |
| 48 | +// let longest = 0; |
| 49 | + |
| 50 | +// for (let i = 0; i < s.length; i++) { |
| 51 | +// let subString = new Set(); |
| 52 | + |
| 53 | +// for (let j = i; j < s.length; j++) { |
| 54 | +// if (subString.has(s[j])) { |
| 55 | +// break; |
| 56 | +// } else { |
| 57 | +// subString.add(s[j]); |
| 58 | +// longest = Math.max(longest, j - i + 1); |
| 59 | +// } |
| 60 | +// } |
| 61 | +// } |
| 62 | +// return longest; |
| 63 | +// }; |
| 64 | + |
0 commit comments