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:
Initialize the longest subarray length and start index variables to 0.
Create an empty dictionary char_dict
to keep track of characters and their indices in the string.
Iterate through the string, maintaining two pointers, start
and end
.
Check if the current character s[end]
is already present in the dictionary char_dict
.
If it is present, update the start
index to be either the current start
index or the index of the current character + 1.
Update the index of the current character in the dictionary char_dict
.
Calculate the current subarray length end - start + 1
.
Keep track of the maximum subarray length if it is greater than the current longest length.
Repeat steps 3-8 until all characters in the string are processed.
Return the longest length as the result.