Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find missing number from array in python #170

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions python/find_missing_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'''
Question : We are given an array with consecutive natural numbers , with one number missing
We have to return that number .
Example : Input = a =[1,2,3,4,5,6,8,9,10]
output = 7
Approach : There exists a very simple approach to this problem . But , overthinking can mess it up,
Sum= (n(n+1))/2 is the formula for sum of n natural numbers , if we subtract then sum of
elements of the given array with this then the result will be the remaining number .
where , n = len(a)
'''
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
Loading