EasyNo. 0217

Contains Duplicate — LeetCode 217 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, Sorting
On study lists
Blind 75, NeetCode 150 and Grind 75
Reading time
2 min

The 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.

Python solution

PythonSolution
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return any(a == b for a, b in pairwise(sorted(nums)))

Complexity

Time
O(n × log n)where n is the length of the array `nums`
Space · auxiliary
O(n)where n is the length of the array `nums`

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 217. Contains Duplicate is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0219Contains Duplicate IIEasy
0220Contains Duplicate IIIHard
0049Group AnagramsMedium
0169Majority ElementEasy
0229Majority Element IIMedium
0268Missing NumberEasy

Frequently asked questions

How hard is LeetCode 217. Contains Duplicate?

LeetCode 217. Contains Duplicate is rated Easy on LeetCode.

What is the time complexity of LeetCode 217. Contains Duplicate?

The Python solution on this page runs in O(n × log n), where n is the length of the array `nums`.

What is the space complexity of LeetCode 217. Contains Duplicate?

The Python solution on this page uses O(n), where n is the length of the array `nums` auxiliary space.

What topics does LeetCode 217. Contains Duplicate cover?

LeetCode 217. Contains Duplicate is tagged Array, Hash Table and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.