Find missing number

Arrays Logic Building Easy
  • Fun Fact: The problem concept of identifying missing elements in a sequence is commonly used in the software industry for a variety of purposes
  • For instance, it’s integral in database management where checking for missing IDs or sequence gaps is crucial
  • The concept is also highly relevant in network programming, specifically in TCP (Transmission Control Protocol) where packet sequence numbers are maintained
  • Identifying missing sequence numbers helps in detecting packet loss during data transmission

Given an integer array of size n containing distinct values in the range from 0 to n (inclusive), return the only number missing from the array within this range.

Examples:

Input: nums = [0, 2, 3, 1, 4]

Output: 5

Explanation: nums contains 0, 1, 2, 3, 4 thus leaving 5 as the only missing number in the range [0, 5]

Input: nums = [0, 1, 2, 4, 5, 6]

Output: 3

Explanation: nums contains 0, 1, 2, 4, 5, 6 thus leaving 3 as the only missing number in the range [0, 6]

Input: nums = [1, 3, 6, 4, 2, 5]

Constraints

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

Hints

  • "Use the formula for the sum of the first n natural numbers: S= (n×(n+1))/2. Subtract the sum of the array elements from S to find the missing number."
  • Leverage the XOR property: x⊕x=0 and x⊕0=x. XOR all indices and array values; the missing number will be the result.

Company Tags

Rakuten HCL Technologies ARM Rockstar Games Roblox PayPal Robinhood Snowflake Philips Healthcare Mastercard Byju's HashiCorp Deloitte NVIDIA Texas Instruments GE Healthcare Freshworks IBM Lyft Wayfair Bloomberg Teladoc Health Chewy Shopify Salesforce TCS Cognizant Accenture Infosys Capgemini Wipro