Saturday, May 31, 2025

๐Ÿ’ผ Interview Question: - Longest Substring Without Repeating Characters

  Python implementation of the "Longest Substring Without Repeating Characters" problem using the sliding window technique:

def longest_substring(s):

    char_index_map = {}  # Stores the index of characters

    left = 0  # Left boundary of the sliding window

    max_length = 0  # Maximum length found


    for right in range(len(s)):

        if s[right] in char_index_map:

            left = max(left, char_index_map[s[right]] + 1)  # Move left boundary

        char_index_map[s[right]] = right  # Update index of character

        max_length = max(max_length, right - left + 1)  # Update max length


    return max_length


# Example usage:

s = "abcabcbb"

print(longest_substring(s))  # Output: 3

This algorithm efficiently finds the longest substring without repeating characters in O(n) time using a sliding window approach. The char_index_map dictionary keeps track of the last index of each character to avoid unnecessary repetitions.

๐Ÿง  : 2nd example:

Prompt

Given a string s, find the length of the longest substring without repeating characters.

def length_of_longest_substring(s: str) -> int:


Input: s = "abcabcbb"  
Output: 3  
Explanation: The answer is "abc", with the length of 3.

✅ What It's Testing:

  1. Sliding Window Technique – Efficient string traversal.

  2. Hashing/Data Structures – Using sets or dictionaries to track characters.

  3. Edge Case Thinking – Empty strings, all identical characters, etc.

  4. Time Complexity Awareness – Naive solutions may be O(n²); optimal is O(n).


def length_of_longest_substring(s: str) -> int:
    char_index = {}
    left = 0
    max_length = 0

    for right in range(len(s)):
        if s[right] in char_index and char_index[s[right]] >= left:
            left = char_index[s[right]] + 1
        char_index[s[right]] = right
        max_length = max(max_length, right - left + 1)

    return max_length

๐Ÿ“Š Time and Space Complexity:

  • Time Complexity: O(n), where n is the length of the string.

  • Space Complexity: O(min(n, m)), where m is the character set size.


No comments:

virtual representations of physical objects or systems.

Digital Twins - Virtual Replicas of Cities, Factories, or Human Organs for Simulations How virtual copies are revolutionizing the phys...