Nth Lexicographical Substrings
Problem Description:
Given a string S
and two integers K
and N
, find the Nth lexicographically smallest and Nth lexicographically largest substrings of length K
from the string S
. If there are fewer than N
substrings, return "INVALID" for that case.
Input Format:
- The first line contains a string
S
consisting of lowercase English letters (1 ≤ |S| ≤ 1000). - The second line contains two integers
K
andN
(1 ≤ K ≤ |S|, 1 ≤ N).
Output Format:
- The first line should contain the Nth lexicographically smallest substring of length
K
, or "INVALID" if there are fewer thanN
substrings. - The second line should contain the Nth lexicographically largest substring of length
K
, or "INVALID" if there are fewer thanN
substrings.
Example Input 1:
Example Output 1:
Example Input 2:
Example Output 2:
Explanation:
For the first example:
- All possible substrings of length 3 are: [enjo, njoy, joyj, oyja, yjav, java]
- Sorted substrings in lexicographical order:
ava
, [enjo, java, joyj, njoy, oyja, yjav]- 3rd smallest: joyj
- 3rd largest: njoy
For the second example:
- All possible substrings of length 4 are: [mah, ahe, hen, end, ndr, dra, ras, asi, sin, ing, ngh, ghd, hdh, dho, hon, oni]
- Sorted substrings in lexicographical order: [ahe, asi, dho, dra, end, ghd, hdh, hen, hon, ing, mah, ndr, ngh, oni, ras, sin]
- 7th smallest: hdh
- 7th largest: ing
For the third example:
- All possible substrings of length 2 are: [chennaisuper, hennaisuperk, ennaisuperki, nnaisuperkin, naisuperking, aisuperkings]
- Sorted substrings in lexicographical order: [aisuperkings, chennaisuper, ennaisuperki, hennaisuperk, naisuperking, nnaisuperkin]
- 7th smallest: INVALID
- 7th largest: INVALID
Java Code:
Comments
Post a Comment