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 an integer array and a fixed window size k. The task is to find the contiguous subarray of length k that has the maximum average value. Which algorithmic approach guarantees an optimal solution with linear time complexity?
easy
A. Sliding window technique maintaining a running sum of the current window
B. Brute force nested loops checking all subarrays of size k
C. Dynamic programming with memoization of subproblems
D. Greedy approach selecting the largest elements regardless of position

Solution

  1. Step 1: Understand problem constraints

    The problem requires finding the maximum average of any contiguous subarray of fixed size k, which suggests examining all windows of size k.
  2. Step 2: Identify optimal approach

    Sliding window maintains a running sum by adding the new element and removing the oldest, achieving O(n) time. Brute force is O(n*k), DP and greedy do not fit this fixed-size window problem optimally.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sliding window updates sum in O(1) per step, total O(n) time [OK]
Hint: Sliding window updates sum in O(1) per step [OK]
Common Mistakes:
  • Thinking greedy works without considering window contiguity
  • Assuming DP is needed for fixed-size windows
2. Consider the following Python function implementing the sliding window approach to find the maximum sum subarray of size k. What is the value of window_sum after the second iteration of the for-loop when called with arr = [1, 3, 2, 6] and k = 2?
def max_sum_subarray_sliding_window(arr, k):
    n = len(arr)
    window_sum = sum(arr[:k])
    max_sum = window_sum
    for i in range(k, n):
        window_sum += arr[i] - arr[i - k]
        if window_sum > max_sum:
            max_sum = window_sum
    return max_sum
easy
A. 8
B. 9
C. 5
D. 7

Solution

  1. Step 1: Initialize variables

    window_sum = sum(arr[:2]) = 1 + 3 = 4, max_sum = 4
  2. Step 2: Iterate and update window_sum

    First iteration (i=2): window_sum = 4 + arr[2] - arr[0] = 4 + 2 - 1 = 5 Second iteration (i=3): window_sum = 5 + arr[3] - arr[1] = 5 + 6 - 3 = 8
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    window_sum after second iteration is 8 [OK]
Hint: Track window_sum updates carefully per iteration [OK]
Common Mistakes:
  • Off-by-one errors in loop index
  • Confusing window_sum with max_sum
  • Forgetting to subtract the element leaving the window
3. The following code attempts to find all anagrams of p in s using a sliding window with count matching optimization. Which line contains a subtle bug that can cause incorrect results or runtime errors?
medium
A. Line missing decrement of window_count[left_index] when shrinking window
B. Line checking if window_count[index] == p_count[index] + 1 to decrement matches
C. Line incrementing window_count[index] when adding right character
D. Line appending left index to result when matches == 26

Solution

  1. Step 1: Identify window shrinking logic

    When window size exceeds p length, left character count must be decremented.
  2. Step 2: Locate missing decrement

    The code does not decrement window_count[left_index] before moving left pointer, causing incorrect counts.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing decrement breaks frequency tracking [OK]
Hint: Always decrement count when shrinking window [OK]
Common Mistakes:
  • Forgetting to decrement frequency on window shrink
  • Incorrect matches update logic
  • Appending wrong indices
4. What is the time complexity of the sliding window approach for the Minimum Size Subarray Sum problem, and why might some candidates incorrectly think it is O(n²)?
medium
A. O(n log n) due to sorting or binary search inside the loop
B. O(n²) because of nested loops implied by two pointers
C. O(n) because each element is visited at most twice by left and right pointers
D. O(n) but with O(n) auxiliary space for prefix sums

Solution

  1. Step 1: Identify pointer movements

    Right pointer moves forward once per iteration; left pointer moves forward only when shrinking window, each element visited at most twice.
  2. Step 2: Analyze total operations

    Since both pointers only move forward, total operations are proportional to 2n = O(n), no nested repeated scanning.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Two-pointer sliding window is classic O(n) approach [OK]
Hint: Two pointers each move forward once -> O(n) [OK]
Common Mistakes:
  • Assuming nested loops cause O(n²)
  • Confusing prefix sums with sliding window
  • Thinking auxiliary space affects time complexity
5. Suppose the problem is modified so that elements in the array can be reused any number of times to form contiguous subarrays (i.e., subarrays can wrap around or repeat elements). Which of the following statements about adapting the sliding window algorithm is correct?
hard
A. The original sliding window algorithm works without changes because product updates remain valid with repeated elements.
B. Using a max-heap to track products allows efficient counting of repeated-element subarrays.
C. The sliding window approach fails because the window can grow indefinitely due to element reuse, requiring a different approach like dynamic programming.
D. We can fix the sliding window by resetting the window whenever product exceeds k, but counting subarrays remains the same.

Solution

  1. Step 1: Understand element reuse impact

    Allowing reuse means subarrays can be infinitely long by repeating elements, so the window can grow without bound.
  2. Step 2: Sliding window limitation

    Sliding window relies on finite array length and shrinking window when product exceeds k; infinite repetition breaks this logic.
  3. Step 3: Alternative approach needed

    Dynamic programming or other methods are needed to handle infinite or repeated elements properly.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Infinite growth breaks sliding window assumptions -> need different approach [OK]
Hint: Infinite repetition breaks sliding window shrinking logic [OK]
Common Mistakes:
  • Assuming sliding window works unchanged
  • Trying to fix by resets only
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