Contains Duplicate — LeetCode 217 Python Solution
EasyArrayHash TableSorting
- Problem
- #217
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the length of the array `nums` |
| Space | O(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.