May 4, 2022

Question 31 : Check if Array Elements are Consecutive

Given an array, we need to check if array contains consecutive elements.
For example :
Input: array[] = {5, 3, 4, 1, 2} Output: true As array contains consecutive elements from 1 to 5 Input: array[] = {47, 43, 45, 44, 46} Output: true As array contains consecutive elements from 43 to 47 Input: array[] = {6, 7, 5, 6} Output: false As array does not contain consecutive elements.

Best Solution — HashSet + Min/Max

import java.util.HashSet; import java.util.Set; public class ConsecutiveArray { public static boolean isConsecutive(int[] arr) { if (arr.length == 0) return false; int min = arr[0], max = arr[0]; for (int num : arr) { min = Math.min(min, num); max = Math.max(max, num); } if (max - min + 1 != arr.length) { return false; } Set<Integer> set = new HashSet<>(); for (int num : arr) { if (set.contains(num)) return false; set.add(num); } return true; } }

Python 

def is_consecutive(arr): if not arr: return False mn = min(arr) mx = max(arr) if mx - mn + 1 != len(arr): return False return len(set(arr)) == len(arr) print(is_consecutive([5,2,3,4,1])) # True

Solution Sorting Approach 
import java.util.Arrays; public class ConsSorting { public static boolean isConsecutive(int[] arr) { Arrays.sort(arr); for (int i = 1; i < arr.length; i++) { if (arr[i] - arr[i - 1] != 1) { return false; } } return true; } }
Python 
def is_consecutive_sort(arr): arr.sort() for i in range(1, len(arr)): if arr[i] - arr[i-1] != 1: return False return True

Solution Brute Force (Check All Pairs) 
public class ConsBrute { public static boolean isConsecutive(int[] arr) { for (int num : arr) { boolean found = false; for (int x : arr) { if (x == num + 1) { found = true; } } } return true; } }
Python 
def is_consecutive_brute(arr): for num in arr: if num + 1 not in arr: return False return True

Approach Time Complexity Space Complexity Best Use
HashSet + Min/Max O(n) O(n) ⭐ Best & optimal
Sorting & adjacent diff O(n log n) O(1/ n) Simple if sort OK
Brute force O(n²) O(1) ❌ Only for learning

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS