LeetCode 2784: Check if Array is Good Solution

Master LeetCode problem 2784 (Check if Array is Good), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2784. Check if Array is Good

Problem Explanation

Explanation

To determine if an array is a good array, we need to check if it is a permutation of an array base where base contains integers from 1 to n-1 exactly once, and n appears twice. We can do this by iterating through the array, counting the frequency of each number, and ensuring that the maximum number is n. Then we check if the count of n is 2 and all other numbers have a count of 1. If these conditions are met, the array is considered good.

  • Time complexity: O(n) where n is the length of the input array nums.
  • Space complexity: O(n) to store the frequency of each number.

Solution Code

class Solution {
    public boolean isGoodArray(int[] nums) {
        int n = nums.length;
        int[] count = new int[201]; // As per constraints 1 <= num[i] <= 200

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

        int maxNum = 0;
        for (int i = 1; i <= 200; i++) {
            if (count[i] > 0) {
                if (count[i] > 1 && count[i] != 2) {
                    return false;
                }
                maxNum = Math.max(maxNum, i);
            }
        }

        return count[maxNum] == 2 && maxNum == n;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2784 (Check if Array is Good)?

This page provides optimized solutions for LeetCode problem 2784 (Check if Array is Good) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2784 (Check if Array is Good)?

The time complexity for LeetCode 2784 (Check if Array is Good) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2784 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2784 in Java, C++, or Python.

Back to LeetCode Solutions