LeetCode Entry

268. Missing Number

20.02.2024 easy 2024 kotlin rust

Missing in [0..n] number.

268. Missing Number easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/513

Problem TLDR

Missing in [0..n] number.

Intuition

There are several ways to find it:

  • subtracting sums
  • doing xor
  • computing sum with a math n * (n + 1) / 2

Approach

Write what is easier for you, then learn the other solutions. Xor especially.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


  fun missingNumber(nums: IntArray): Int =
    (1..nums.size).sum() - nums.sum()


  pub fn missing_number(nums: Vec<i32>) -> i32 {
    nums.iter().enumerate().map(|(i, n)| i as i32 + 1 - n).sum()
  }