Skip to main content

16. Contains Duplicate

easyAsked at Unity

Detect repeated values in an array — the same deduplication check Unity's asset import pipeline runs when the editor scans a folder for duplicate mesh GUIDs before loading a scene.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1

Input
nums = [1,2,3,1]
Output
true

Explanation: 1 appears at indices 0 and 3.

Example 2

Input
nums = [1,2,3,4]
Output
false

Approaches

1. Sorting

Sort the array; duplicates become adjacent. One scan suffices.

Time
O(n log n)
Space
O(1)
function containsDuplicate(nums) {
  nums.sort((a, b) => a - b);
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] === nums[i - 1]) return true;
  }
  return false;
}

Tradeoff:

2. Hash set single pass

Insert each element into a Set. If it already exists, a duplicate is found. O(n) time, O(n) space.

Time
O(n)
Space
O(n)
function containsDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

Tradeoff:

Unity-specific tips

Unity interviewers tie this directly to asset deduplication — articulate the Set as a GUID registry that the import pipeline checks on every file discovery event, and mention the memory cost is acceptable given scene sizes are bounded.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Contains Duplicate and other Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →