Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 29 Jun, 2021

Given a string list, the task is to write a Python program to extract Strings that form the longest increasing alphabetic order at Kth index. K should be less than 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 longest substrings using sliding window technique and keep updating the maximum of substrings sequence, and updating the result list.



At last the resulted 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’]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :