Contains Duplicate — LeetCode 217 Python Solution

EasyArrayHash TableSorting
Problem
#217
Pattern
Sorting
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

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

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array `nums`
SpaceO(n), where n is the length of the array `nums` auxiliary

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

On study lists

This problem is on Blind 75, NeetCode 150 and Grind 75.

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 \times \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.

Get Stealth Interview