30. Contains Duplicate
easyAsked at OlaReturn true if any value appears at least twice in an array.
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 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
trueExample 2
Input
nums = [1,2,3,4]Output
falseApproaches
1. Sort and scan
Sort and check consecutive equal entries.
- Time
- O(n log n)
- Space
- O(1)
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
Insert into a set and stop the first time the size doesn't grow.
- Time
- O(n)
- Space
- O(n)
function containsDuplicate(nums) {
const seen = new Set();
for (const x of nums) {
if (seen.has(x)) return true;
seen.add(x);
}
return false;
}Tradeoff:
Ola-specific tips
Ola uses this to discuss set-versus-sort tradeoffs; relate it to checking duplicate ride IDs in a streaming dispatch deduper.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Contains Duplicate and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →