Check if Array is Good - Problem
Array Pattern Recognition Challenge
You're given an integer array
An array is considered good if it's a permutation of a
•
• Contains numbers 1 through n-1 exactly once
• Contains the number n exactly twice
• Has a total length of n+1
Examples of base arrays:
•
•
•
Return
You're given an integer array
nums and need to determine if it follows a specific "good" pattern.An array is considered good if it's a permutation of a
base[n] array, where:•
base[n] = [1, 2, 3, ..., n-1, n, n]• Contains numbers 1 through n-1 exactly once
• Contains the number n exactly twice
• Has a total length of n+1
Examples of base arrays:
•
base[1] = [1, 1] (length 2)•
base[3] = [1, 2, 3, 3] (length 4)•
base[4] = [1, 2, 3, 4, 4] (length 5)Return
true if the given array matches this pattern (in any order), otherwise return false. Input & Output
example_1.py — Basic Valid Case
$
Input:
nums = [2, 1, 3]
›
Output:
false
💡 Note:
Length is 3, so n would be 2. But base[2] = [1, 2, 2] requires length 3 with numbers [1, 2, 2]. Our array has [1, 2, 3], which doesn't match.
example_2.py — Perfect Match
$
Input:
nums = [1, 3, 3, 2]
›
Output:
true
💡 Note:
Length is 4, so n = 3. base[3] = [1, 2, 3, 3]. Our array contains exactly one 1, one 2, and two 3's, which matches the required pattern.
example_3.py — Edge Case
$
Input:
nums = [1, 1]
›
Output:
true
💡 Note:
Length is 2, so n = 1. base[1] = [1, 1]. Our array has exactly two 1's, which matches perfectly.
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 200
- The array represents a permutation test case
Visualization
Tap to expand
Understanding the Visualization
1
Count Attendance
Go through the roster once, counting how many times each student number appears
2
Find Maximum
The highest student number tells us what 'n' should be for this class
3
Validate Pattern
Check: Do we have exactly n different student numbers? Do numbers 1 through n-1 appear once, and does n appear twice?
Key Takeaway
🎯 Key Insight: Use a hash table to count frequencies in one pass. The maximum value determines n, and we validate that numbers 1 to n-1 appear once while n appears twice.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code