Computer >> Computer tutorials >  >> Programming >> Python

Program to find the kth missing number from a list of elements in Python


Suppose we have a list of sorted unique numbers called nums and an integer k, we have to find the kth missing number from the first element of the given list.

So, if the input is like nums = [5,6,8,10,11], k = 1, then the output will be 9, as 9 is the second (index 1) missing number.

To solve this, we will follow these steps −

  • for i in range 1 to size of nums, do

    • diff := nums[i] - nums[i - 1] - 1

    • if k >= diff, then

      • k := k - diff

    • otherwise,

      • return nums[i - 1] + k + 1

  • return nums[-1] + k + 1

Let us see the following implementation to get better understanding −

Example

class Solution:
   def solve(self, nums, k):
      for i in range(1, len(nums)):
         diff = nums[i] - nums[i - 1] - 1
         if k >= diff:
            k -= diff
         else:
            return nums[i - 1] + k + 1
      return nums[-1] + k + 1

ob = Solution()
nums = [5,6,8,10,11]
k = 1
print(ob.solve(nums, k))

Input

[5,6,8,10,11], 1

Output

9