Skip to content

2784. Check if Array is Good 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool isGood(vector<int>& nums) {
    constexpr int kMax = 200;
    const int n = nums.size() - 1;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    return all_of(count.begin() + 1, count.begin() + n,
                  [](int c) { return c == 1; }) &&
           count[n] == 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Solution {
  public boolean isGood(int[] nums) {
    final int kMax = 200;
    final int n = nums.length - 1;
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    return (n == 0 || Arrays.stream(count, 1, n).allMatch(c -> c == 1)) && count[n] == 2;
  }
}
1
2
3
4
5
class Solution:
  def isGood(self, nums: List[int]) -> bool:
    n = len(nums) - 1
    count = collections.Counter(nums)
    return all(count[i] == 1 for i in range(1, n)) and count[n] == 2