[LeetCode] Missing Number

Description:

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.


Brute-force Approach:

  • Sort the array from 0 to N.
  • Inside a simple for loop, iterate through every element in the array till the length of the array if the index and element doesn't match, return the index.
Brute-force Solution:
















Brute-force Result:

















Efficient Approach:
  • Since the numbers are from 0 to N then calculate the sum of all the numbers from 0 to N using the mathematical formula: (N * ( N + 1 )) / 2
  • Calculate the sum of all numbers in the array.
  • Subtract both sums with each other and return.

Efficient Solution:














Efficient Result:


Comments

Popular

How To Create MySQL Table with SequelizeJS

How To Read CSV Files in Java as Maven Project

How To Create A Hibernate Project in Maven