Given an integer array nums, return true if any value appears at least twice; otherwise false.
Scan left to right with a hash set of values already seen. For each x, if x is in the set return true; else insert it. Narrate a dry run on [1,2,3,1] and explain why a sort-based check is also valid but usually slower to code under pressure.
def containsDuplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
Time O(n), space O(n). Sorting is O(n log n) time and O(1)/O(n) space depending on the sort.
Practice tip: keep the same narration under time pressure with AI coding interview assistant.
Disclosure: I work on Linkjob AI.