#2784
Check if Array is Good
EasyArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating and sorting arrays, we can use a frequency count to validate the conditions for a good array directly, which is more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Find the maximum element in the array, n.
- 2Step 2: Count the occurrences of each number in the array using a hash map.
- 3Step 3: Check if the count of n is exactly 2 and if all numbers from 1 to n-1 appear exactly once.
- 4Step 4: If both conditions are satisfied, return true; otherwise, return false.
solution.py8 lines
1# Full working Python code
2
3def isGoodArray(nums):
4 n = max(nums)
5 count = {}
6 for num in nums:
7 count[num] = count.get(num, 0) + 1
8 return count.get(n, 0) == 2 and all(count.get(i, 0) == 1 for i in range(1, n))ℹ
Complexity note: The time complexity is O(n) because we only traverse the array a couple of times. The space complexity is O(n) due to the hash map storing counts of the elements.
- 1The maximum element determines the expected structure of the array.
- 2A good array must have exactly two occurrences of the maximum element and one of all others.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.