Bird
Raised Fist0
Interview Prepsliding-windowmediumAmazonFacebookGoogleMicrosoftBloomberg

Longest Substring Without Repeating Characters

Choose your preparation mode4 modes available
📋
Problem

Imagine you're typing a password and want to find the longest sequence of characters you've typed without repeating any letter, to ensure maximum complexity.

Given a string s, find the length of the longest substring without repeating characters. Input: A string s consisting of English letters, digits, symbols, and spaces. Output: An integer representing the length of the longest substring without any repeated characters.

1 ≤ length of s ≤ 10^5s consists of English letters, digits, symbols, and spaces
Edge cases: Empty string → 0String with all unique characters → length of entire stringString with all identical characters → 1
</>
IDE
def lengthOfLongestSubstring(s: str) -> int:public int lengthOfLongestSubstring(String s)int lengthOfLongestSubstring(string s)function lengthOfLongestSubstring(s)
def lengthOfLongestSubstring(s: str) -> int:
    # Write your solution here
    pass
class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Write your solution here
        return 0;
    }
}
#include <string>
using namespace std;

int lengthOfLongestSubstring(string s) {
    // Write your solution here
    return 0;
}
function lengthOfLongestSubstring(s) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for non-empty strings due to missing base case or incorrect initialization.✅ Initialize max length to 0 and return 0 only if input string is empty.
Wrong: Length of entire string even if duplicates existNot shrinking window or not detecting duplicates properly.✅ Use a hash set or map to detect duplicates and move start pointer accordingly.
Wrong: Incorrect length due to off-by-one errorCalculating window length as right - left instead of right - left + 1.✅ Calculate window length as end index - start index + 1.
Wrong: Fails on duplicate characters by resetting window incorrectlyGreedy approach that resets window start to next character instead of jumping past last duplicate index.✅ Track last seen indices and update start pointer to max of current start and last duplicate index + 1.
Wrong: TLE on large inputUsing brute force or nested loops leading to O(n^2) or worse complexity.✅ Implement sliding window with hash map for O(n) time complexity.
✓
Test Cases
t1_01basic
Input{"s":"abcabcbb"}
Expected3

The longest substring without repeating characters is 'abc' with length 3.

t1_02basic
Input{"s":"pwwkew"}
Expected3

The longest substring without repeating characters is 'wke' with length 3.

t2_01edge
Input{"s":""}
Expected0

Empty string has no substrings, so length is 0.

t2_02edge
Input{"s":"a"}
Expected1

Single character string has longest substring length 1.

t2_03edge
Input{"s":"abcdef"}
Expected6

All characters unique, so longest substring is entire string length 6.

t3_01corner
Input{"s":"abba"}
Expected2

Longest substring without repeating characters is 'ab' or 'ba', length 2.

t3_02corner
Input{"s":"dvdf"}
Expected3

Longest substring without repeating characters is 'vdf' with length 3.

t3_03corner
Input{"s":"tmmzuxt"}
Expected5

Longest substring without repeating characters is 'mzuxt' with length 5.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input length n=100000; solution must run in O(n) time to complete within 2 seconds.

Practice

(1/5)
1. You are given two strings s and p. You need to find all start indices in s where a substring is an anagram of p. Which algorithmic approach guarantees an optimal solution with linear time complexity?
easy
A. Brute force checking all substrings of length equal to p and comparing frequency maps.
B. Sliding window with frequency map comparison and count matching optimization.
C. Dynamic programming to build a table of substring matches based on character counts.
D. Greedy approach by sorting each substring and comparing with sorted p.

Solution

  1. Step 1: Understand problem constraints

    The problem requires finding all anagrams of p in s efficiently, ideally in linear time.
  2. Step 2: Evaluate algorithmic approaches

    Brute force (checking all substrings) is O(n*m), sorting each substring is O(n*m log m), and DP is not naturally suited here. Sliding window with frequency map and count matching optimizes to O(n) time.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Sliding window with count matching is known optimal for fixed-size anagram search [OK]
Hint: Sliding window with count matching -> O(n) time [OK]
Common Mistakes:
  • Thinking sorting each substring is efficient enough
  • Assuming DP applies directly
  • Using brute force for large inputs
2. Consider the following Python code implementing the sliding window with count matching optimization to find all anagrams of p in s. What is the final returned list when s = "cbaebabacd" and p = "abc"?
easy
A. [0, 1, 6]
B. [0, 6, 7]
C. [0, 6, 8]
D. [0, 6]

Solution

  1. Step 1: Trace first window (indices 0 to 2)

    Substring "cba" is an anagram of "abc", so index 0 is added.
  2. Step 2: Slide window and check matches

    Next valid anagram found at index 6 ("bac"). No other windows match all counts.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Known example output matches [0, 6] [OK]
Hint: Anagrams appear at indices 0 and 6 only [OK]
Common Mistakes:
  • Including indices where substring is not full anagram
  • Off-by-one errors in window boundaries
3. You are given two strings s and t. Your task is to find the shortest substring in s that contains all characters of t including duplicates. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Dynamic programming to build a table of minimum substrings for all prefixes of s and t
B. Greedy approach that expands the window until all characters are found, then shrinks it from the left without tracking counts
C. Sliding window with two pointers and frequency maps to track counts of characters in the current window
D. Sorting both strings and using two pointers to find matching characters in order

Solution

  1. Step 1: Understand problem requirements

    The problem requires finding the shortest substring containing all characters of t with correct counts, which demands tracking character frequencies.
  2. Step 2: Evaluate algorithm suitability

    Greedy without frequency tracking can miss duplicates; DP is inefficient and not straightforward here; sorting breaks substring order. Sliding window with frequency maps efficiently tracks counts and adjusts window size optimally.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sliding window with frequency maps is the classic optimal approach [OK]
Hint: Track counts with two pointers for optimal substring [OK]
Common Mistakes:
  • Assuming greedy without counts works
  • Confusing DP with substring problems
  • Sorting breaks substring order
4. Consider the following Python code implementing the sliding window maximum using a monotonic deque. What is the returned result when calling maxSlidingWindow([2, 1, 3], 2)?
easy
A. [2, 3]
B. [2, 1, 3]
C. [3]
D. [1, 3]

Solution

  1. Step 1: Trace the deque and result for each iteration

    i=0: dq=[0], result=[]; i=1: nums[1]=1 < nums[0]=2, dq=[0,1], result=[]; i=2: nums[2]=3 > nums[1]=1 pop 1, nums[2]=3 > nums[0]=2 pop 0, dq=[2]; after i=1 (window [2,1]) result append nums[0]=2; after i=2 (window [1,3]) result append nums[2]=3.
  2. Step 2: Collect final result

    Result after full iteration is [2, 3].
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Output matches expected sliding window maximum for windows [2,1] and [1,3] [OK]
Hint: Deque stores indices of max candidates, popping smaller elements [OK]
Common Mistakes:
  • Appending result before window is full
  • Not removing indices outside the window
  • Confusing values and indices in deque
5. Identify the bug in the following code snippet for the Maximum Points You Can Obtain from Cards problem:
medium
A. Line 7: Loop range should start from k instead of window_size.
B. Line 4: Incorrect initial sum calculation; should sum last k elements instead of first window_size.
C. Line 9: The condition should be current_sum > min_subarray_sum instead of <.
D. Line 3: Incorrect calculation of window_size; should be n - k instead of k.

Solution

  1. Step 1: Understand window size meaning

    The window represents the subarray to exclude, which must be length n - k, not k.
  2. Step 2: Identify impact of wrong window size

    Using k as window size causes the algorithm to exclude wrong subarray length, leading to incorrect results.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct window size is n - k for the sliding window [OK]
Hint: Window size must be n - k, not k [OK]
Common Mistakes:
  • Confusing window size with k instead of n-k
  • Incorrect loop boundaries
  • Wrong comparison operator in min update
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard