Skip to content
Related Articles

Related Articles

Python Program to get the Longest Alphabetic order of Kth index from list values

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 24 Aug, 2022
View Discussion
Improve Article
Save Article

Given a string list, the task is to write a Python program to extract Strings that form the longest increasing alphabetic order at the Kth index. K should be less than the minimum length of all strings. 

Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”, “and”, “cs”], K = 0 
Output : [‘best’, ‘for’, ‘geeks’] 
Explanation : Longest subsequence extracted by comparing 0th index. At 0th index, b < f < g. Longest possible consecution. Next being ‘a’ becomes smaller than ‘g’, hence streak breaks.

Input : test_list = [“gfg”, “is”, “geeks”, “and”, “cs”], K = 0 
Output : [‘gfg’, ‘is’] 
Explanation : Longest subsequence extracted by comparing 0th index. 

Input : test_list = [“gfg”, “is”, “geeks”, “and”, “cs”], K = 4
Output : []
Explanation : Smallest lengths in string, is 2 of ‘is’ and ‘cs’. Since K >= min_length, No result.

Method: Using loop with sliding window

In this, we keep checking for increasing the longest substrings using the sliding window technique and keep updating the maximum of substrings sequence and updating the result list.

At last, the result is printed accordingly.

Example:

Python3




# Python3 code to demonstrate working of
# Longest Alphabetic order of Kth index
# Using loop with sliding window
 
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks", "and", "cs"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
res = []
curr = test_list[:1]
for idx in range(1, len(test_list)):
 
    # checking for greater element
    if test_list[idx][K] <= test_list[idx - 1][K]:
 
        # comparing current with maximum length
        if len(curr) > len(res):
            res = curr
        curr = [test_list[idx]]
    else:
        curr.append(test_list[idx])
if len(curr) > len(res):
    res = curr
 
# printing result
print("Longest increasing Alphabetic order : " + str(res))

Output

The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
Longest increasing Alphabetic order : ['geeks', 'and', 'cs']

Time Complexity: O(n), where n is the length of the given list.
Auxiliary Space: O(n) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!