The problem. Given an integer array nums, return true if any value appears at least twice, and false if every value is distinct.
nums = [1, 2, 3, 1] -> true
nums = [1, 2, 3, 4] -> false
nums = [1, 1, 1, 3, 3, 4, 3, 2, 4] -> trueMany questions are hard on a jumbled array and easy on a sorted one. Sorting puts related values next to each other: equal values become neighbours, the closest pair of numbers sits side by side, and intervals line up by start time so overlaps are adjacent. After an O(n log n) sort, a single O(n) scan comparing neighbours (or tracking a running value) finishes the job.
The cost to remember: sorting is O(n log n) and either modifies the input or needs a copy. When a hash map can answer the question in O(n), it's faster — but sorting needs no extra memory if you may reorder the input, and it's the only easy route when the question is about order (closest, overlapping, the h-th largest). The questions in this chapter all follow this shape.
function containsDuplicate(nums) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] === nums[j]) return true; } } return false;}Time O(n²), space O(1). About n²/2 comparisons — too slow for 10⁵ values.
After sorting, a duplicate must sit right next to its twin.
function containsDuplicate(nums) { const sorted = [...nums].sort((a, b) => a - b); // equal values end up side by side for (let i = 1; i < sorted.length; i++) { if (sorted[i] === sorted[i - 1]) return true; // a value equal to its neighbour } return false;}Time O(n log n), space O(n) for the copy — or O(1) extra if you may sort nums itself.
function containsDuplicate(nums) { const seen = new Set(); for (const x of nums) { if (seen.has(x)) return true; // seen before: a duplicate seen.add(x); } return false;}Time O(n), space O(n). The fastest, at the price of a set as big as the input.
Mention both 2 and 3: the set is faster, sorting saves memory. Interviewers like hearing the trade-off.
[1, 2, 3, 1]; sorting brings them together.nums.sort() changes their data; copy first if that matters.