Check if Array is Good - Problem
Array Pattern Recognition Challenge

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
🎯 Good Array Pattern RecognitionInput: [2, 1, 3, 3] → Is this a "good" array?Step 1: Count Frequencies2133Hash Table:1 → count: 12 → count: 13 → count: 2max = 3Step 2: Determine nmax value = 3, so n = 3Expected length = n + 1 = 4 ✓Expected base[3]:1233Pattern: [1,2,3,...,n-1,n,n]Step 3: Validate✓ Length: 4 == n+1✓ Unique numbers: 3 == n✓ Number 1: count 1 ✓✓ Number 2: count 1 ✓✓ Number 3: count 2 ✓RESULT: TRUE🚀 One-Pass Hash Solution (Optimal)Time Complexity: O(n) | Space Complexity: O(n)Single pass through array + O(n) validation = Linear time!💡 Key Insight: Hash Table Frequency CountingThe maximum value determines n, then we verify the frequency pattern matches base[n] requirements
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen