Skip to content

Commit 8d163b8

Browse files
Solution: 3. Longest Substring Without Repeating Characters
1 parent 10cf496 commit 8d163b8

File tree

4 files changed

+121
-4
lines changed

4 files changed

+121
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,12 @@
1-
# Start here
1+
abcabcbb
2+
bbbbb
3+
pwwkew
4+
abcdef
5+
a
6+
aa
7+
abababab
8+
emptystringtest
9+
z
10+
!@#$%^&*()_+
11+
1234567890
12+
abba

CodingChallenges/LeetCode/longest-substring-without-repeating-characters/insight.md

+55-1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,58 @@ Given a string `s`, find the length of the longest **substring** (A substring is
2626
### Constraints
2727

2828
- `0 <= s.length <= 5 * 104`
29-
- `s` consists of English letters, digits, symbols and spaces.
29+
- `s` consists of English letters, digits, symbols, and spaces.
30+
31+
## Problem Breakdown
32+
33+
This problem is a classic example that utilizes the Sliding Window technique, which is particularly effective for challenges involving contiguous sequences of elements such as substrings or subarrays.
34+
35+
### Understanding the Problem
36+
37+
The goal is to identify the longest substring of `s` that contains no repeating characters. Key considerations include handling strings of varying lengths and compositions, from completely unique strings to those with repetitive characters.
38+
39+
### Edge Cases
40+
41+
- **Empty string**: Returns a length of 0.
42+
- **Uniform character string**: Such as "aaaa", should return 1 because there is only one unique character.
43+
- **All unique characters**: Returns the length of the string itself.
44+
45+
## Approach: Sliding Window
46+
47+
This technique involves two pointers to define a moving window of characters that expands and contracts based on the uniqueness of characters within it.
48+
49+
### Solution Explanation
50+
51+
- **Initialization**: Two pointers, `left` and `right`, start at the beginning of the string, with a set to track characters within the current window.
52+
- **Expansion**: The `right` pointer moves to the right, adding new characters to the set.
53+
- **Contraction**: When a duplicate character is found, the `left` pointer moves right until the duplicate is removed from the set, thereby making the substring unique again.
54+
- **Tracking Maximum**: The maximum length of the substring without repeating characters is updated continuously as the window adjusts.
55+
56+
### Example Walkthrough
57+
58+
- **Input**: "abcabcbb"
59+
- Expands to "abc", then encounters a duplicate 'a'.
60+
- Contracts by moving the left pointer to just past the first 'a'.
61+
- Continues until the end, updating the maximum length found.
62+
63+
## Applied Data Structure and Algorithm
64+
65+
- **Data Structure**: Uses a set to efficiently check for duplicates and to quickly clear items when necessary.
66+
- **Algorithm**: Implements the Sliding Window technique with dynamic adjustment of window boundaries based on the condition of uniqueness.
67+
68+
## Complexity Analysis
69+
70+
- **Time Complexity**: O(n), where `n` is the length of the string. Each character is processed at most twice (once added and once removed).
71+
- **Space Complexity**: O(min(m, n)), where `m` is the size of the character set, and `n` is the length of the string.
72+
73+
## What We've Learned
74+
75+
- The sliding window technique is incredibly effective for problems involving substrings or subarrays where the condition of the window changes dynamically based on the sequence content.
76+
- Using a set facilitates O(1) time complexity for adding and removing characters, making the solution efficient even for large strings.
77+
78+
## Key Notes
79+
80+
- The solution gracefully handles all types of strings by dynamically adjusting the window size.
81+
- It’s essential to consider how the data structure used (in this case, a set) can significantly impact the efficiency of the solution.
82+
83+
---
Original file line numberDiff line numberDiff line change
@@ -1 +1,12 @@
1-
# Start here
1+
3
2+
1
3+
3
4+
6
5+
1
6+
1
7+
2
8+
7
9+
1
10+
12
11+
10
12+
2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
11
class Solution:
22
def lengthOfLongestSubstring(self, s: str) -> int:
3-
pass
3+
char_set = set()
4+
left = 0
5+
max_length = 0
6+
7+
# Check for empty string
8+
if not s:
9+
return 0
10+
11+
for right in range(len(s)):
12+
# Continue to slide the window if duplicate is found
13+
while s[right] in char_set:
14+
char_set.remove(s[left])
15+
left += 1
16+
char_set.add(s[right])
17+
# Update max_length after ensuring s[right] is added to the set
18+
max_length = max(max_length, right - left + 1)
19+
20+
return max_length
21+
22+
# For testing
23+
class Test:
24+
def test(self):
25+
solution = Solution()
26+
with open('input.txt', 'r') as input_file, open('output.txt', 'r') as output_file:
27+
passed = True
28+
for input_line, expected_output_line in zip(input_file, output_file):
29+
input_str = input_line.strip()
30+
expected_output = int(expected_output_line.strip()) # Expected output is an integer
31+
actual_output = solution.lengthOfLongestSubstring(input_str)
32+
if actual_output == expected_output:
33+
print(f"Passed: {input_str} -> {actual_output}")
34+
else:
35+
print(f"Failed: {input_str} -> {actual_output} (Expected: {expected_output})")
36+
passed = False
37+
if passed:
38+
print("All test cases passed!")
39+
else:
40+
print("Some test cases failed.")
41+
42+
if __name__ == "__main__":
43+
test_code = Test()
44+
test_code.test()

0 commit comments

Comments
 (0)