703113. Check if array contains contiguous integers

Easy

Check if Array Contains Contiguous Integers

Summary

Given an array of integers, write a program to check if the array contains contiguous integers. The array may contain duplicates, and the integers need not be in sorted order.

The key concepts involved are arrays, hash tables (for checking uniqueness), and sorting (to verify contiguity).

Detailed Explanation


To solve this problem, we can follow these steps:

  1. Initialize an empty hash set contiguousIntegers to keep track of the integers we have seen so far.
  2. Iterate through the array, and for each integer:
    • Check if the integer is already present in the contiguousIntegers set using a contains method (e.g., Java's contains or Python's in). If it is, then update the last seen contiguous integer.
    • If not, add the integer to the contiguousIntegers set and update the last seen contiguous integer.

Here's an example of how this might look:

[1, 2, 3, 5, 6, 7]

In the above array, we can see that integers 1 through 3 are contiguous. Then there is a gap followed by another set of contiguous integers from 5 to 7.

Time complexity: O(n), where n is the size of the input array. Space complexity: O(min(n, k)), where k is the number of distinct contiguous integers in the array (in this case, it would be 3).

Optimized Solutions


Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static boolean checkArray(int[] arr) {
        Set<Integer> seen = new HashSet<>();
        int lastContiguous = Integer.MIN_VALUE;
        for (int num : arr) {
            if (!seen.add(num)) {
                if (num == lastContiguous + 1) {
                    continue; // Contiguous integers
                } else {
                    return false; // Gap in contiguous integers
                }
            }
            lastContiguous = num;
        }
        return true; // All integers are contiguous
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5, 6, 7};
        System.out.println(checkArray(arr)); // prints: true
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.