CSC419 · 2077 · 5 marks
A non-empty array A of length n is called an array of all possibilities if it contains all numbers between 0 and A.length-1 inclusive. Write a method named isAllPossibilities that accepts an integer array and returns 1 if the array is an array of all possibilities, otherwise it returns 0.
A non-empty array A of length n is called an array of all possibilities if it contains all numbers between 0 and A.length-1 inclusive. Write a method named isAllPossibilities that accepts an integer array and returns 1 if the array is an array of all possibilities, otherwise it returns 0. [5]
isAllPossibilities Method
Given data
- Input: a non-empty integer array
Aof lengthn. - Condition:
Amust contain all integers from0ton-1inclusive. - Output: return
1if the condition holds, otherwise0.
(No specific test arrays are mandated by the question; behaviour must be general.)
Concept
An array of length n qualifies if and only if it is a permutation of ${0, 1, 2, \dots, n-1}$. Since the array has exactly n slots and must hold n distinct values all in range $[0, n-1]$, it suffices to check:
- every element lies in $[0, n-1]$, and
- no value repeats.
If both hold across n elements, each of the n distinct values must appear exactly once (pigeonhole principle).
Java Code
public static int isAllPossibilities(int[] A) {
int n = A.length;
boolean[] visited = new boolean[n]; // track which numbers seen
for (int i = 0; i < n; i++) {
// out of range check
if (A[i] < 0 || A[i] >= n) {
return 0;
}
// duplicate check
if (visited[A[i]]) {
return 0;
}
visited[A[i]] = true;
}
return 1; // all values 0..n-1 present exactly once
}
Dry Run
| Array | n | Result | Reason |
|---|---|---|---|
{0,1,2,3} | 4 | 1 | Permutation of 0..3 |
{3,0,2,1} | 4 | 1 | Same set, reordered |
{1,2,3,4} | 4 | 0 | 4 >= n out of range |
{0,0,1,2} | 4 | 0 | Duplicate 0 detected |
{-1,0,1,2} | 4 | 0 | -1 < 0 out of range |
Complexity
- Time: $O(n)$ - single pass.
- Space: $O(n)$ - visited array.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.