Problem Description
Given an integer array nums, determine if it is a permutation of a special array base[n], where base[n] is defined as [1, 2, ..., n - 1, n, n] (an array of length n + 1 that contains every number from 1 to n - 1 exactly once and the number n exactly twice). In other words, verify whether nums can be rearranged to match base[n].
Key Insights
- The maximum element in nums determines the candidate n.
- The length of nums must be exactly n + 1.
- All numbers from 1 to n - 1 should appear exactly once.
- The number n must appear exactly twice.
- Using a frequency count (hash table) is an efficient approach to verify these conditions.
Space and Time Complexity
Time Complexity: O(n) – We iterate through the array to count frequencies. Space Complexity: O(n) – Additional data structure (hash table) to store counts.
Solution
We first determine the candidate n by finding the maximum value from nums. Next, we check whether the length of nums is n + 1. If not, we immediately return false since it cannot match base[n]. Then we use a hash table (or dictionary) to count the frequency of each element. For each number i from 1 to n - 1, we check if its frequency is exactly 1. For n, we check if its frequency is exactly 2. If all conditions hold, the array is a valid permutation of base[n]; otherwise, it is not.