İçeriğe atla
ΣDSA Patterns
Menü
Dil

Bit Manipülasyonu

Rehber 4 / 6 · Yol 4 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Missing Number

Problem (restated)

Array of n distinct numbers in [0, n]. Find the missing one.

Intuition

XOR of 0..n with all nums cancels pairs; leftover is missing.

Approaches

XOR 0..n with nums

Tested only
Time O(n)Space O(1)

Idea. x=0..n fold with nums.

Walkthrough. [3,0,1] → 2.

Trade-offs. Sum formula also O(n); XOR avoids overflow concerns in other langs.

Solution
export function missingNumber(nums: number[]): number {
  let x = nums.length;
  for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
  return x;
}
export function missingNumber(nums: number[]): number {
  let x = nums.length;
  for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
  return x;
}

Template connection

Bit XOR identity (same family as single number).

Reflection