LeetCode 2229: Check if an Array Is Consecutive Solution

Master LeetCode problem 2229 (Check if an Array Is Consecutive), 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.

2229. Check if an Array Is Consecutive

Problem Explanation

Explanation:

To check if an array is consecutive, we can sort the array first. Then, we can iterate through the sorted array to verify if each element is one more than the previous element. If the array is consecutive, then the last element minus the first element should equal the length of the array minus one.

Algorithm:

  1. Sort the given array.
  2. Check if the last element minus the first element is equal to the length of the array minus one.
  3. If the above condition is true, return true; otherwise, return false.

Time Complexity:

The time complexity of this approach is O(n log n) due to the sorting operation.

Space Complexity:

The space complexity of this approach is O(1) as we are not using any extra space.

:

Solution Code

import java.util.Arrays;

class Solution {
    public boolean isConsecutive(int[] nums) {
        Arrays.sort(nums);
        return (nums[nums.length - 1] - nums[0] == nums.length - 1);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2229 (Check if an Array Is Consecutive)?

This page provides optimized solutions for LeetCode problem 2229 (Check if an Array Is Consecutive) 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 2229 (Check if an Array Is Consecutive)?

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

Can I run code for LeetCode 2229 on DevExCode?

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

Back to LeetCode Solutions