Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Longest String in list

Python | Longest String in list

Sometimes, while working with Python Lists, we can have a problem in which we receive Strings as elements and wish to compute the String which has maximum length. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using loop This is the brute method in which we perform this task. In this, we run a loop to keep a memory of longest string length and return the string which has max length in list. 

Python3




# Python3 code to demonstrate working of
# Longest String in list
# using loop
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
 
# printing original list
print("The original list : " + str(test_list))
 
# Longest String in list
# using loop
max_len = -1
for ele in test_list:
    if len(ele) > max_len:
        max_len = len(ele)
        res = ele
 
# printing result
print("Maximum length string is : " + res)


Output : 

The original list : ['gfg', 'is', 'best', 'for', 'Lazyroar']
Maximum length string is : Lazyroar

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using max() + key This method can also be used to solve this problem. In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length. 

Python3




# Python3 code to demonstrate working of
# Longest String in list
# using max() + key
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
 
# printing original list
print("The original list : " + str(test_list))
 
# Longest String in list
# using max() + key
res = max(test_list, key = len)
 
# printing result
print("Maximum length string is : " + res)


Output : 

The original list : ['gfg', 'is', 'best', 'for', 'Lazyroar']
Maximum length string is : Lazyroar

Time Complexity: O(n) where n is the number of elements in the string list. The max() + key is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is created.

Method #3 : Using reduce() + lambda
In this method, we use the reduce() function from the functools module, and pass a lambda function as the first argument, which compares the length of the current and next elements and returns the element with the maximum length.

Python3




# Python3 code to demonstrate working of
# Longest String in list
# using reduce() + lambda
 
from functools import reduce
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
   
# printing original list
print("The original list : " + str(test_list))
   
# Longest String in list
# using reduce() + lambda
res = reduce(lambda x, y: x if len(x) > len(y) else y, test_list)
   
# printing result
print("Maximum length string is : " + res)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : ['gfg', 'is', 'best', 'for', 'Lazyroar']
Maximum length string is : Lazyroar

Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(1) as it uses only a single variable to store the result.

Method #4: Using recursive function. 

This method can also be used to solve this problem. In this, we use recursive function to extract the string with the maximum length. 

Python3




# Python3 code to demonstrate working of
# Longest String in list
# using recursive function
 
#defining recursive function
def find_maximum(lst,start=0,max_word=''):
  if start==len(lst):  #base condition
    return max_word
  if len(lst[start])>len(max_word): 
    max_word=lst[start]
  return find_maximum(lst,start+1,max_word)  #calling recursive function
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
   
# printing original list
print("The original list : " + str(test_list))
   
# Longest String in list
# using recursive function
res = find_maximum(test_list)
   
# printing result
print("Maximum length string is : " + res)
#This code is contributed by tvsk


Output

The original list : ['gfg', 'is', 'best', 'for', 'Lazyroar']
Maximum length string is : Lazyroar

Time Complexity: O(n) 
Auxiliary Space: O(n) 

Method #4:Using a list comprehension

step-by-step algorithm for implementing the approach:

Initialize the list of strings.

Use a list comprehension to create a new list of string lengths. This iterates through each string in the original list and applies the len() function to get the length of each string.

Use the index() method on the lengths list to find the index of the longest string. The max() function returns the largest length, and the index() method returns the index of the first occurrence of that length.

Use the index of the longest string to retrieve the string from the original list.

Print the longest string.

Python3




test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
 
# create a new list of string lengths using a list comprehension
lengths = [len(s) for s in test_list]
 
# find the index of the longest string in the original list
longest_index = lengths.index(max(lengths))
 
# use the index to get the longest string from the original list
longest_string = test_list[longest_index]
 
# print the longest string
print("Longest string is : " + longest_string)


Output

Longest string is : Lazyroar

time complexity: O(n), where n is the length of the test_list.

 auxiliary space complexity: O(n), because we create a new list to store the lengths of each string in the test_list. However, since the lengths list is only used to find the maximum length and then discarded, the space complexity is effectively O(1) in practice.

Method #4:Using the heapq module : 

Algorithm:

1.Initialize a list test_list with strings.
2.Use the heapq.nlargest() function to get the index of the largest element in the list based on the length of each string.
3.Use the index obtained in step 2 to get the corresponding string from the test_list.
4.Print the longest string.

Python3




import heapq
 
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
 
# get the index of the largest element in the list
index = heapq.nlargest(1, range(len(test_list)), key=lambda x: len(test_list[x]))[0]
 
# use the index to get the corresponding string
longest_string = test_list[index]
 
print("Longest string is: " + longest_string)
#This code is contributed by Jyothi pinjala


Output

Longest string is: Lazyroar

Time Complexity:

The time complexity of this algorithm is O(n log k), where n is the length of the list and k is the number of elements to be returned. In this case, we are only returning the single longest string, so k = 1, and the time complexity simplifies to O(n log 1) = O(n). This is because the heapq.nlargest() function has a time complexity of O(n log k) to find the k largest elements.
Space Complexity:

The space complexity of this algorithm is O(1), as we are only using a few variables to store the list of strings, the index of the largest string, and the longest string itself. We are not using any additional data structures that depend on the input size.

 Method #7: Using a sorted() function with a custom key

  • Initialize the list
  • Sort the list in descending order based on the length of each string
  • The first element in the sorted list will be the longest string
  • Print the result

Python3




# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'Lazyroar']
 
# print original list
print("The original list: " + str(test_list))
 
# Longest string in list using sorted() with a custom key
res = sorted(test_list, key=len, reverse=True)[0]
 
# print result
print("Maximum length string is: " + res)


Output

The original list: ['gfg', 'is', 'best', 'for', 'Lazyroar']
Maximum length string is: Lazyroar

Time complexity: O(n log n) – sorting the list takes O(n log n) time in the worst case.
Auxiliary space: O(n) – we need to create a sorted copy of the list.

RELATED ARTICLES

Most Popular

Recent Comments