numbers = [1, 2, 3, 1]→ trueThe value 1 appears at indices 0 and 3.
Given an array of integers, return true if any value appears at two different positions. Return false when every value is distinct.
numbers = [1, 2, 3, 1]→ trueThe value 1 appears at indices 0 and 3.
numbers = [4, -1, 0]→ falseEvery value is different, even though their signs vary.
numbers = []→ falseNo entries means no pair of equal positions can exist.
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.
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.
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.
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 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.
The set contains only earlier values. A match proves two different positions share one value.
Index 0 has value 1. Earlier values: none yet.
1 is new. Add it to the set before inspecting the next position.This check gives feedback. Only a separate code pass records an independent solve.
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…
Loading your saved attempts…
This lesson uses original explanations and examples. For additional practice, see the related LeetCode challenge.