Prasad
2 min readMay 10, 2023

Write a Python function that takes a string as input and returns the longest substring without repeating characters. If there are multiple longest substrings, the function should return the first one it encounters.

if the input string is “abcabcbb”, the function should return “abc”, which is the longest substring without repeating characters. If the input string is “bbbbb”, the function should return “b”, which is the longest substring without repeating characters.

def longest_substring_without_repeating_characters(s):
start = 0
max_length = 0
char_dict = {}
for i in range(len(s)):
if s[i] in char_dict and char_dict[s[i]] >= start:
start = char_dict[s[i]] + 1
else:
max_length = max(max_length, i - start + 1)
char_dict[s[i]] = i
return s[start:start+max_length]

# Example usage:
s = "abcabcbb"
result = longest_substring_without_repeating_characters(s)
print(result) # Output: "abc"

if the input string is “the quick brown fox jumps over the lazy dog”, the function should return the list [“the”] because “the” appears twice in the string.

def repeated_words(string):
words = string.split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
repeated_words = [word for word, count in word_counts.items() if count > 1]
return repeated_words
my_string = "the quick brown fox jumps over the lazy dog"
result = repeated_words(my_string)
print(result) # Output: ["the"]

if the input list is [10, 22, 9, 33, 21, 50, 41, 60, 80], the function should return 6 because the longest increasing subsequence in the list is [10, 22, 33, 50, 60, 80].

def longest_increasing_subsequence(arr):
# Initialize a list to keep track of the length of the LIS ending at each index
lis_lengths = [1] * len(arr)

# Loop through the list, starting at the second element
for i in range(1, len(arr)):
# Check all previous elements to see if they are less than the current element
for j in range(i):
if arr[j] < arr[i]:
# If the jth element is less than the ith element, update the LIS length for the ith element
lis_lengths[i] = max(lis_lengths[i], lis_lengths[j] + 1)

# Return the maximum LIS length
return max(lis_lengths)
my_list = [10, 22, 9, 33, 21, 50, 41, 60, 80]
result = longest_increasing_subsequence(my_list)
print(result) # Output: 6

if the input list is [1, 5, 2, 6, 3, 7, 8, 4, 9, 10], the function should return the tuple (0, 3) because the longest increasing subsequence of integers is [1, 5, 6], and the starting index of that subsequence is 0 and the ending index is 3.

def longest_increasing_subsequence(lst):
n = len(lst)
dp = [1] * n
for i in range(n):
for j in range(i):
if lst[i] > lst[j]:
dp[i] = max(dp[i], dp[j] + 1)
max_len = max(dp)
end_index = dp.index(max_len)
start_index = end_index - max_len + 1
return (start_index, end_index)
Prasad
Prasad

Written by Prasad

I am a OpenSource Enthusiast|Python Lover who attempts to find simple explanations for questions and share them with others

No responses yet