1. Nested Checking All Substrings
Intuition
For every start index i from 0 to n - 1, and every end index j from i to n - 1: verify if all characters in s[i...j] are distinct using a hash set. Track the maximum length found.
When to apply: Basic naive conceptual baseline.
Algorithm
- Initialize
maxLen = 0. - Loop
ifrom 0 ton - 1: - Initialize
set. - Loop
jfromiton - 1: - If
set.contains(s[j]): break. -
set.add(s[j]) -
maxLen = max(maxLen, j - i + 1) - Return
maxLen.
Nested Checking All Substrings
2 of 2 questions left todayObservation: Outer pointer $i = 0$
Observation: Outer pointer i = 0. Expand inner pointer j: characters 'a', 'b', 'c' are all unique.
Decision: At j = 3, character 'a' repeats. Expansion stops; update maxLen = 3.
Invariant: A substring without duplicates cannot contain any character with frequency > 1.
#include <iostream>#include <string>#include <unordered_set>#include <algorithm> class Solution {public: int lengthOfLongestSubstring(std::string s) { int n = s.size(); int maxLen = 0; for (int i = 0; i < n; ++i) { std::unordered_set<char> seen; for (int j = i; j < n; ++j) { if (seen.count(s[j])) break; seen.insert(s[j]); maxLen = std::max(maxLen, j - i + 1); } } return maxLen; }}; int main() { Solution sol; std::cout << sol.lengthOfLongestSubstring("abcabcbb") << std::endl; // 3 std::cout << sol.lengthOfLongestSubstring("bbbbb") << std::endl; // 1 std::cout << sol.lengthOfLongestSubstring("pwwkew") << std::endl; // 3 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Tests all N * (N + 1) / 2 substring pairs. - Space complexity:
O(M) where M is distinct characters count
Why Brute Force Doesn't Scale:
Directly jumping the left pointer reduces inner while loop steps to O(1).
Using a static 256-element array allocates fixed stack memory with O(1) space complexity.