PROBLEM 01 OF 75 · CODE STUDIO

Contains Duplicate

Given an array of integers, return true if any value appears at two different positions. Return false when every value is distinct.

Know the exact contract

  • The local studio accepts finite safe integers, including negative values and zero. The array can be empty.
  • A repeated value is enough; you do not need to return its positions or count every repeat. The input should not be changed.
EXAMPLE 1numbers = [1, 2, 3, 1]→ true

The value 1 appears at indices 0 and 3.

EXAMPLE 2numbers = [4, -1, 0]→ false

Every value is different, even though their signs vary.

EXAMPLE 3numbers = []→ false

No entries means no pair of equal positions can exist.

From repeated checks to one scan

SIMPLE APPROACH

Compare every value with every later value. This makes the distinct-position rule obvious, but examines O(n²) pairs in the worst case and uses O(1) extra space.

IMPROVED APPROACH

Scan once while keeping a set of values from earlier positions. If the current value is already in the set, return true immediately. Otherwise add it and continue. Return false only after the whole array has been checked.

Why it works

Before checking position i, the set contains exactly the values from positions before i. A hit therefore proves a second occurrence at a different position; a miss means the checked prefix remains duplicate-free.

Cost

The set approach takes O(n) expected time and O(n) extra space in the worst case. Sorting a copy takes O(n log n) time and O(n) copy space; sorting the input would violate this studio’s no-mutation contract.

A tempting mistake

A one-element array such as [8] has no duplicate. Do not add the current value and then check membership: that would make every first occurrence appear to match itself.

FOLLOW THE ACTUAL STATE

Has this value appeared before?

The set contains only earlier values. A match proves two different positions share one value.

STEP 1 / 4

Index 0 has value 1. Earlier values: none yet.

1 is new. Add it to the set before inspecting the next position.
Result: true
GUIDED CHECK · BEFORE YOU CODE

Can you prove a repeat?

This check gives feedback. Only a separate code pass records an independent solve.

1. What is in the set before checking index i?
2. When can the scan stop?
3. Why is [8] not a duplicate?
4. What does an empty array return?
5. What is the expected cost of the set scan?
INDEPENDENT SOLVE

Now write the code.

Write solve(data). data.numbers is an integer array. Return a boolean and leave the array unchanged. Built-in checks include empty input, immediate repeats, negative values, and fresh distinct and repeated cases.

Opening the code studio…

PROVE IT AGAIN TOMORROW

A fresh solve is the test.

Loading your saved attempts…

This lesson uses original explanations and examples. For additional practice, see the related LeetCode challenge.