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:
- Initialize an empty hash set
contiguousIntegersto keep track of the integers we have seen so far. - Iterate through the array, and for each integer:
- Check if the integer is already present in the
contiguousIntegersset using acontainsmethod (e.g., Java'scontainsor Python'sin). If it is, then update the last seen contiguous integer. - If not, add the integer to the
contiguousIntegersset and update the last seen contiguous integer.
- Check if the integer is already present in the
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
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
}
}