Post

Created by @oliverrichards
 at October 26th 2023, 3:56:48 am.

Technical Interview Question:

Implement a function that takes in a string as input and finds the length of the longest subarray within the string that contains no repeating characters. The function should return the length of the longest subarray.

For example, given the input string "abcabcbb", the longest subarray without repeating characters is "abc" with a length of 3. Therefore, the function should return 3.

Write a function longest_subarray_length to solve this problem.

Answer:

def longest_subarray_length(s):
    longest_length = 0  # Initialize the longest length variable
    start = 0  # Start index of the current subarray

    char_dict = {}  # Dictionary to keep track of characters and their indices

    for end in range(len(s)):
        if s[end] in char_dict:  # If the current character is already in the dictionary
            start = max(start, char_dict[s[end]] + 1)  # Update the start index accordingly

        char_dict[s[end]] = end  # Update the index of the current character in the dictionary

        longest_length = max(longest_length, end - start + 1)  # Calculate the current subarray length

    return longest_length

Step-by-step Explanation:

  1. Initialize the longest subarray length and start index variables to 0.

  2. Create an empty dictionary char_dict to keep track of characters and their indices in the string.

  3. Iterate through the string, maintaining two pointers, start and end.

  4. Check if the current character s[end] is already present in the dictionary char_dict.

  5. If it is present, update the start index to be either the current start index or the index of the current character + 1.

    • This ensures that the new subarray we create starts after the last occurrence of the repeated character.
  6. Update the index of the current character in the dictionary char_dict.

  7. Calculate the current subarray length end - start + 1.

  8. Keep track of the maximum subarray length if it is greater than the current longest length.

  9. Repeat steps 3-8 until all characters in the string are processed.

  10. Return the longest length as the result.