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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

Live Demo

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
Updated on 09-Oct-2020 14:34:28