2077 4

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]

Advanced Java ProgrammingChapter 1: Programming in JavaArraysNumerical: array all possibilities method

isAllPossibilities Method

Given data

  • Input: a non-empty integer array A of length n.
  • Condition: A must contain all integers from 0 to n-1 inclusive.
  • Output: return 1 if the condition holds, otherwise 0.

(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:

  1. every element lies in $[0, n-1]$, and
  2. 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

ArraynResultReason
{0,1,2,3}41Permutation of 0..3
{3,0,2,1}41Same set, reordered
{1,2,3,4}404 >= n out of range
{0,0,1,2}40Duplicate 0 detected
{-1,0,1,2}40-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.