Program to find lexicographically smallest subsequence of size k in Python

PythonServer Side ProgrammingProgramming

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]
raja
Published on 12-Dec-2020 10:04:26
Advertisements