Leetcode 2784. Check if Array is Good
You are given an array nums
of length n
consisting of distinct integers from the range [0, n-1]
.
A “good” array is defined as an array where:
[0, n-1]
appears exactly once in the array.Write a function isGoodArray(int[] nums)
that returns true
if the array is “good” and false
otherwise.
Example:
Input: nums = [3, 0, 1, 2]
Output: true
Input: nums = [1, 2, 3, 4]
Output: false
[0, n-1]
.n
.To solve this problem, the approach is straightforward since the array contains distinct integers, and we just need to check if every integer from 0
to n-1
is present in the array. Here’s how we can do this:
[0, 1, 2, ... , n-1]
.n
and it contains all integers from 0
to n-1
.I will use the second approach which doesn’t involve sorting and is efficient.
import java.util.HashSet;
public class Solution {
public boolean isGoodArray(int[] nums) {
int n = nums.length;
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
if (set.size() != n) {
return false;
}
for (int i = 0; i < n; i++) {
if (!set.contains(i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = {3, 0, 1, 2};
int[] nums2 = {1, 2, 3, 4};
System.out.println(solution.isGoodArray(nums1)); // Output: true
System.out.println(solution.isGoodArray(nums2)); // Output: false
}
}
O(n)
due to iterating through the array and using a HashSet for storage. Both insertion and lookup in a HashSet have an average time complexity of O(1)
.O(n)
because we use a HashSet that may store n
elements in the worst case.This solution efficiently checks if the array contains all numbers from 0
to n-1
exactly once.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?