Contains Duplicate

Returns true if the input array has any duplicates, false otherwise.

Easy

Examples

Example 1: [1,2,3,1] → true
Example 2: [1,2,3,4] → false

Implementation

Ruby

  # 🔁 2. Contains Duplicate
  # Returns true if the input array has any duplicates, false otherwise.
  # Uses a Set to keep track of seen elements.
  # Time Complexity: O(n)
  # Why: Single pass through the array while checking and adding to a Set.
  def contains_duplicate(nums)
    seen = Set.new
    nums.each do |num|
      return true if seen.include?(num)
      seen.add(num)
    end
    false

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(n)

Patterns & Techniques

Problem Details

Category: Array Hashing Examples
Difficulty: Easy
Module: ArrayHashingExamples
Method: contains_duplicate
← Back to Array Hashing Examples