Python | Lexicographically smallest string in mixed list
Last Updated :
12 Apr, 2023
Sometimes, we can also encounter a problem in which we are given a mixed list and require to find the lexicographically smallest string that occur in list. This problem can find it’s application day-day programming. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using min() + isinstance() + list comprehension This task can be performed using the combination of above functions. In this, the min() functions performs the task of finding smallest string and isinstance() is used to check for string.
Python3
test_list = [ 1 , 2 , 4 , "GFG", 5 , "IS", 7 , "BEST"]
print ("The original list is : " + str (test_list))
res = min (sub for sub in test_list if isinstance (sub, str ))
print ("The Lexicographically smallest string is : " + str (res))
|
Output :
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using min() + lambda + filter() The combination of above functions can also be used to perform this particular task. In this we perform the task of list comprehension using filter() and lambda and min function is used to performed the usual task of finding smallest string.
Python3
test_list = [ 1 , 2 , 4 , "GFG", 5 , "IS", 7 , "BEST"]
print ("The original list is : " + str (test_list))
res = min ( filter ( lambda s: isinstance (s, str ), test_list))
print ("The Lexicographically smallest string is : " + str (res))
|
Output :
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST
Time Complexity: O(n*n) where n is the number of elements in the list “res_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
Method#3: Using Recursive method.
Algorithm:
- Define a recursive function that takes a list as input.
- If the list is empty, return a high-value string (e.g., ‘zzz’).
- If the first element of the list is a string, recursively call the function on the rest of the list and return the minimum of the first element and the result of the recursive call.
- If the first element of the list is not a string, recursively call the function on the rest of the list.
- Call the recursive function on the input list and return the result.
Python3
def recursive_min_string(test_list):
if not test_list:
return 'zzz'
elif isinstance (test_list[ 0 ], str ):
return min (test_list[ 0 ], recursive_min_string(test_list[ 1 :]))
else :
return recursive_min_string(test_list[ 1 :])
test_list = [ 1 , 2 , 4 , "GFG" , 5 , "IS" , 7 , "BEST" ]
print ( "The original list is : " + str (test_list))
res = recursive_min_string(test_list)
print ( "The Lexicographically smallest string is : " + str (res))
|
Output
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST
Time Complexity: O(n), where n is the length of the input list. The recursive function iterates over the entire list once, so the time complexity is linear in the length of the list.
Auxiliary Space: O(n), where n is the length of the input list. The recursive function creates a new stack frame for each element of the list, so the space complexity is linear in the length of the list.
Method#4: Using heapq:
Algorithm:
- Initialize the input list, test_list.
- Initialize an empty list, strings, to store all the string elements of the input list.
- Use list comprehension to get all the string elements from the input list.
- Use the heapq.nsmallest() method to get the lexicographically smallest string from the strings list.
- Print the lexicographically smallest string.
Python3
import heapq
test_list = [ 1 , 2 , 4 , "GFG" , 5 , "IS" , 7 , "BEST" ]
print ( "The original list is : " + str (test_list))
strings = [sub for sub in test_list if isinstance (sub, str )]
res = heapq.nsmallest( 1 , strings)[ 0 ]
print ( "The Lexicographically smallest string is : " + str (res))
|
Output
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST
Time Complexity:
Creating a list of all string elements using list comprehension takes O(n) time, where n is the length of the input list.
The heapq.nsmallest() method takes O(k log n) time, where k is the number of smallest elements to be retrieved and n is the length of the input list.
Here, k is 1, so the time complexity reduces to O(log n).
Thus, the overall time complexity of the code is O(n + log n), which can be simplified to O(n).
Space Complexity:
An empty list, strings, is created to store the string elements. This takes O(1) space.
The heapq.nsmallest() method creates a heap with the string elements, which takes O(k) space.
Here, k is 1, so the space complexity is O(1).
Thus, the overall space complexity of the code is O(1).
Similar Reads
Python3 Program to Find Lexicographically minimum string rotation | Set 1
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples: Input: GEEKSQUIZOutput: EEKSQUIZGInput: GFGOutput: FGGInput: GEEKSFORGEEKSOutput: EEKSFORGEEKSGFollowing is a simple solution.
2 min read
Python - Smallest Length String
To identify the smallest string by length in a list, we compare the lengths of all strings and select the shortest one. Using min()The most efficient way to do this is by using the min() function with the key parameter. This method directly calculates the smallest string based on its length, avoidin
3 min read
Python - Length of shortest string in string list
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have applications in many domains. Letâs discuss certain ways in which this task can be performed. Method #1 : Using min() + g
5 min read
Python3 Program to Find Lexicographically smallest rotated sequence | Set 2
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDADInput Constraint: 1 < n < 1000 Examples: Input: GEEKSQUIZOutput: EEKSQUIZGInput: GFGOutput: FGGInput : CAPABCQOutput : ABCQCAP We have discussed a O(n2Logn) solutio
2 min read
Python | Extract Score list of String
Sometimes, while programming we can have a problem in which we dedicate to each character of alphabets a particular score and then according to string, extract only those score for further computations. This can have application in gaming domain. Let's discuss certain ways in which this task can be
3 min read
Python | Alternate Sort in String list
Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
2 min read
Sort List of Lists by Lexicographic Value and then Length - Python
In this problem, sorting a list of lists by lexicographic value and then length means arranging the sublists first by their natural order (lexicographically) and then by their size. For example: For the list [[3, 2], [1, 4, 6], [1, 2], [3, 2, 1]], sorting by lexicographic value and then by length wo
3 min read
Python | Sort each String in String list
Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
4 min read
Python | Splitting list on empty string
Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Let's discuss certain ways in which this
4 min read
Python - Smallest K values in Dictionary
Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Letâs discuss several ways in which this task can be performed. Smallest K values in Dictionary u
4 min read