Given a String str and an integer k, find the lexicographically smallest and largest substring of length k
Lexicography order, also called as alphabetical order or dictionary order,
A < B <... < Y < Z < a < b <.. < y < z
Input : String: hello Size: 2 Distinct Substring: [el, he, ll, lo] Output : Smallest Substring: el Largest Substring: lo Input : String: geeksforgeeks Size: 3 Distinct Substring: [eek, eks, for, gee, ksf, org, rge, sfo] Output : Smallest Substring: eek Largest Substring: sfo
We initialize max and min as first substring of size k. We traverse remaining substrings, by removing first character of previous substring and adding last character of new string. We keep track of the lexicographically largest and smallest.
# Python 3 program to find lexicographically
# largest and smallest substrings of size k.
def getSmallestAndLargest(s, k):
# Initialize min and max as
# first substring of size k
currStr = s[:k]
lexMin = currStr
lexMax = currStr
# Consider all remaining substrings.
# We consider every substring ending
# with index i.
for i in range(k, len(s)):
currStr = currStr[1 : k] + s[i]
if (lexMax < currStr): lexMax = currStr if (lexMin >currStr):
lexMin = currStr
# Print result.
# Driver Code
if __name__ == ‘__main__’:
str1 = “GeeksForGeeks”
k = 3
# This code is contributed by
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- K-th lexicographically smallest unique substring of a given string
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Check if string can be made lexicographically smaller by reversing any substring
- Lexicographically smallest rotated sequence | Set 2
- Construct lexicographically smallest palindrome
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically smallest permutation of a string with given subsequences
- Make a lexicographically smallest palindrome with minimal changes
- Lexicographically largest sub-sequence of the given string
- Lexicographically smallest string obtained after concatenating array
- Find the lexicographically smallest string which satisfies the given condition
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest permutation with no digits at Original Index
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.