DSA AnimatorREVISION VIDEOS
← Back to problems
New

Contains Duplicate — LeetCode 217 video explanation

Given an array, return true if any value appears at least twice. Return false if every value is distinct.

Loading videos…

DSA Animator › DSA Revision › Arrays › Contains Duplicate

Key moments in the Contains Duplicate video

0:04Problem0:11Example0:15Brute force0:22Key idea0:29Dry run0:36Code0:48Takeaway

What you will learn

Remember: seen before means a hash set lookup. Stop as soon as the first duplicate appears. The video solves Contains Duplicate (LeetCode 217, Easy) with the Hash Set pattern from the Arrays topic, and you can replay every step in the interactive Contains Duplicate animation.

Contains Duplicate video transcript

Problem

Given an array, return true if any value appears at least twice. Return false if every value is distinct.

Example

For 1, 2, 3, 1, the answer is true, because 1 appears twice.

Brute force

Comparing every pair is O of n squared. Sorting and checking neighbours works too, but costs O of n log n.

Key idea

Keep a hash set of the values seen so far. If the current value is already in the set, you found a duplicate.

Dry run

1 is new, so add it. 2 is new, so add it. 3 is new, so add it. 1 is already in the set, so return true.

Code

In code, create an empty set. For each number, if adding it fails because it is already there, return true. If the loop finishes, return false, so it's O of n time and O of n space.

Takeaway

Remember: seen before means a hash set lookup. Stop as soon as the first duplicate appears.

More Arrays revision videos

← All 185 DSA revision videos