Check if Array is Good - Problem

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

base[n] = [1, 2, ..., n - 1, n, n] (in other words, it is an array of length n + 1 which contains 1 to n - 1 exactly once, plus two occurrences of n). For example, base[1] = [1, 1] and base[3] = [1, 2, 3, 3].

Return true if the given array is good, otherwise return false.

Note: A permutation of integers represents an arrangement of these numbers.

Input & Output

Example 1 — Valid Good Array
$ Input: nums = [2,1,3,3]
Output: true
💡 Note: This array has length 4, so we expect base[3] = [1,2,3,3]. The input is a permutation of base[3], containing: 1 once, 2 once, and 3 twice.
Example 2 — Invalid Array
$ Input: nums = [1,3,3,2]
Output: true
💡 Note: This array has length 4, so we expect base[3] = [1,2,3,3]. The input is a permutation of [1,2,3,3], just in different order.
Example 3 — Wrong Pattern
$ Input: nums = [1,1]
Output: true
💡 Note: This array has length 2, so we expect base[1] = [1,1]. The input matches exactly.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Check if Array is Good INPUT nums = [2, 1, 3, 3] 2 i=0 1 i=1 3 i=2 3 i=3 base[n] Pattern: [1, 2, ..., n-1, n, n] Length = n + 1 base[1] = [1, 1] base[2] = [1, 2, 2] base[3] = [1, 2, 3, 3] For nums.length = 4: n = 3, check base[3] ALGORITHM STEPS 1 Calculate n n = len(nums) - 1 = 3 2 Sort Array [2,1,3,3] --> [1,2,3,3] 3 Verify Elements Check 1 to n-1 appear once Check n appears twice Index Value Expected 0 1 1 OK 1 2 2 OK 2 3 3 OK 3 3 3 OK 4 All Checks Pass Return true FINAL RESULT Sorted: [1, 2, 3, 3] 1 2 3 3 Matches base[3]: [1, 2, 3, 3] true Array is GOOD Validation Summary: 1-2 appear once: OK 3 appears twice: OK Key Insight: For an array of length n+1 to be "good", it must contain exactly the numbers 1 to n-1 (each once) plus the number n appearing exactly twice. Sort and compare with expected base[n] pattern. TutorialsPoint - Check if Array is Good | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~15 min Avg. Time
340 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