# Program to find lexicographically smallest subsequence of size k in Python

Suppose we have a list of numbers called nums and another value k, we have to find the lexicographically smallest subsequence of size k.

So, if the input is like nums = [2, 3, 1, 10, 3, 4] k = 3, then the output will be [1, 3, 4]

To solve this, we will follow these steps −

• l := size of nums, r := k - 1
• out := a new list
• for j in range 0 to k, do
• mn := nums[complement of r]
• for i in range r to l, do
• if mn >= nums[complement of i], then
• mn := nums[complement of i]
• l := i
• r := r - 1
• insert mn at the end of out
• return out

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution:
def solve(self, nums, k):
l, r = len(nums), k - 1
out = []
for j in range(k):
mn = nums[~r]
for i in range(r, l):
if mn >= nums[~i]:
mn = nums[~i]
l = i
r -= 1
out.append(mn)
return out
ob = Solution()
nums = [2, 3, 1, 10, 3, 4]
k = 3
print(ob.solve(nums, k))

## Input

[2, 3, 1, 10, 3, 4], 3

## Output

[1, 3, 4]
{"ft_lang_label":"__label__en","ft_lang_prob":0.70081687,"math_prob":0.99957293,"size":2943,"snap":"2023-14-2023-23","text_gpt3_token_len":798,"char_repetition_ratio":0.22286493,"word_repetition_ratio":0.1005386,"special_character_ratio":0.27862725,"punctuation_ratio":0.09727626,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.999716,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-28T18:44:15Z\",\"WARC-Record-ID\":\"<urn:uuid:b6deb99a-fbe1-498f-8111-dada4ed660b2>\",\"Content-Length\":\"38682\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7c7f8a19-3571-4504-8641-bb967dbc4757>\",\"WARC-Concurrent-To\":\"<urn:uuid:d18de9eb-8dd0-48df-add5-394479efef0e>\",\"WARC-IP-Address\":\"192.229.210.176\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/program-to-find-lexicographically-smallest-subsequence-of-size-k-in-python\",\"WARC-Payload-Digest\":\"sha1:I3VGYTP5AJDN5RF5BQSP2IKSY272HB5B\",\"WARC-Block-Digest\":\"sha1:CLXTDIN467WN6OONU43LG5KEAHTEOBRA\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296948868.90_warc_CC-MAIN-20230328170730-20230328200730-00698.warc.gz\"}"}