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

Hashing

Rehber 4 / 6 · Yol 4 / 6

Interactive

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 8
2
7
11
15
map{ }

target = 9

Two Sum in one pass: ask for the complement before inserting.

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

Contains Duplicate

Problem (restated)

Return true if any value appears at least twice in the array.

Intuition

A set remembers seen values; a second sighting is a duplicate.

Approaches

Hash set

Verified
Time O(n)Space O(n)

Idea. Insert each number into a set; if already present, return true.

Walkthrough. [1,2,3,1] → see 1 again → true.

Trade-offs. Sorting is O(n log n) with O(1) extra space if allowed to mutate.

Solution
export function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const x of nums) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}
export function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const x of nums) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}

Reflection