Missing Number - Array - Easy - LeetCode
💻 coding

Missing Number - Array - Easy - LeetCode

1 min read 91 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding a missing number from an array of distinct integers ranging from 0 to n.
  • 2The solution involves calculating the expected sum of numbers and subtracting the actual sum from it.
  • 3The algorithm achieves linear time complexity O(n) and constant space complexity O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding a missing number from an array of distinct integers ranging from 0 to n."

Missing Number - Array - Easy - LeetCode

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1] Output: 2 Example 2:

Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

public class Solution {
 public int MissingNumber(int[] nums) {
 int len = nums.Length;
 int expectedSum = len*(len+1)/2;
 int sum = 0;
 for(int i=0;i<nums.Length;i++){
 sum+=nums[i];
 }
 
 return expectedSum - sum;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 25 September 2020 · 1 min read · 91 words

Part of AskGif Blog · coding

You might also like