EasyNo. 2784

Check if Array is Good — LeetCode 2784 Python Solution

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

The problem

You are given an integer array nums. We consider an array good if it is a permutation of an array base[n].

Example

Input
nums = [2, 1, 3]
Output
false
Explanation
Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.

Python solution

PythonSolution
class Solution:
    def isGood(self, nums: List[int]) -> bool:
        cnt = Counter(nums)
        n = len(nums) - 1
        return cnt[n] == 2 and all(cnt[i] for i in range(1, n))

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 2784. Check if Array is Good 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
2780Minimum Index of a Valid SplitMedium
0049Group AnagramsMedium
0169Majority ElementEasy
0217Contains DuplicateEasy
0229Majority Element IIMedium
0268Missing NumberEasy

Frequently asked questions

How hard is LeetCode 2784. Check if Array is Good?

LeetCode 2784. Check if Array is Good is rated Easy on LeetCode.

What is the time complexity of LeetCode 2784. Check if Array is Good?

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

What is the space complexity of LeetCode 2784. Check if Array is Good?

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

What topics does LeetCode 2784. Check if Array is Good cover?

LeetCode 2784. Check if Array is Good 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.