InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Contains Duplicate

easy Original ↗ 00:00

Problem

Given an integer array nums, return True if any value appears more than once in the array, and False if every element is distinct.

Examples

  • nums = [1,2,3,1]True — the value 1 appears at indices 0 and 3.
  • nums = [1,2,3,4]False — all four values are distinct.
  • nums = [1,1,1,3,3,4,3,2,4,2]True — several values repeat (1, 3, 4, 2).

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9

At 10^5 elements, an O(n^2) pairwise comparison is about 5 * 10^9 operations — you need O(n log n) or better.

Think about it first

Hint 1 The naive answer compares every pair of elements. How many pairs is that for 10^5 elements?
Hint 2 If the array were sorted, where would any duplicates have to sit relative to each other?
Hint 3 A hash set gives O(1) membership checks. Walk the array once, asking "have I seen this value before?" and recording each value as you go.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug