Check if Array is Good
The problem can be solved by checking two conditions:
 The array
nums
must haven+1
elements, wheren
is the maximum element in the array. n
must occur exactly twice, and the remaining elements must occur exactly once.
Here is a Python solution that follows this approach:


In this solution, we first calculate the maximum element n
in the array nums
. Then we check Condition 1: the length of nums
must be n+1
. If not, we return False.
Next, we count the number of occurrences of each number in nums
. We use a list counts
of size n+1
for this, where counts[i]
is the number of occurrences of i
in nums
.
Finally, we iterate through the numbers from 1 to n
and check Condition 2: numbers 1 to n1
must occur exactly once, and n
must occur exactly twice. If any of these conditions is not met, we return False. If both conditions are met for all numbers, we return True.
This solution has a time complexity of O(n) where n is the length of nums
, and a space complexity of O(n) for the counts
array.
Ruby solution:




In Ruby, we use the max
method to find the maximum element in nums
and we define counts
as an Array with default values of zero. The .each
method is used for iterating through the elements in nums
and the range (1..n)
. We use the &&
operator for logical AND, and the if
keyword for conditionals. The rest of the code is structurally the same as the Python version.
This solution still has a time complexity of O(n) and a space complexity of O(n), where n is the length of nums
.


Bit easier to read:
Key Takeaways
 The term permutation should not mislead you
 Check the given conditions individually without trying to see if the given input is a permutation
 Don’t try to overengineer the solution