LeetCode 2229: Check if an Array Is Consecutive

Problem Description

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.

:

Solutions

import java.util.Arrays;

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

Loading editor...