EasyNo. 2229LeetCode Premium

Check if an Array Is Consecutive — LeetCode 2229 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, Sorting
Reading time
2 min

The problem

Given an integer array nums, return true if nums is consecutive, otherwise return false. An array is consecutive if it contains every number in the range [x, x + n - 1] (inclusive), where x is the minimum number in the array and n is the length of the array.

Example

Input
nums = [1,3,4,2]
Output
true
Explanation
The minimum value is 1 and the length of nums is 4.

Python solution

PythonSolution
class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        mi, mx = min(nums), max(nums)
        return len(set(nums)) == mx - mi + 1 == len(nums)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2229. Check if an Array Is Consecutive 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
2225Find Players With Zero or One LossesMedium
0049Group AnagramsMedium
0169Majority ElementEasy
0217Contains DuplicateEasy
0229Majority Element IIMedium
0268Missing NumberEasy

Frequently asked questions

How hard is LeetCode 2229. Check if an Array Is Consecutive?

LeetCode 2229. Check if an Array Is Consecutive is rated Easy on LeetCode.

What is the time complexity of LeetCode 2229. Check if an Array Is Consecutive?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2229. Check if an Array Is Consecutive?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2229. Check if an Array Is Consecutive cover?

LeetCode 2229. Check if an Array Is Consecutive is tagged Array, Hash Table and Sorting on LeetCode.

Is LeetCode 2229. Check if an Array Is Consecutive a premium problem?

Yes. LeetCode 2229. Check if an Array Is Consecutive is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.