def longest_unique_substring(s: str) -> str:
"""
Finds the longest substring without repeating characters.
Uses a sliding window and a table of last-seen indexes.
- last_seen[c] stores the most recent index of character c.
- left/right define the current window.
- When a duplicate appears inside the window, move left forward.
Time complexity: O(n)
"""
last_seen = [-1] * 256 # ASCII table
left = 0
best_start = 0
best_length = 0
for right, ch in enumerate(s):
c = ord(ch)
# If character was seen inside the current window, move left
if last_seen[c] >= left:
left = last_seen[c] + 1
# Update last-seen index
last_seen[c] = right
# Check if this window is the best so far
window_length = right - left + 1
if window_length > best_length:
best_length = window_length
best_start = left
return s[best_start:best_start + best_length]
if __name__ == "__main__":
s = "xwwwqfwwxqwyq"
result = longest_unique_substring(s)
print("Input:", s)
print("Longest substring without repeating characters:", result)
"""
run:
Input: xwwwqfwwxqwyq
Longest substring without repeating characters: xqwy
"""