Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Distinct Distinct Elements Read a series of numbers into an integer array, until

ID: 3748615 • Letter: D

Question

Distinct Distinct Elements Read a series of numbers into an integer array, until -1 is entered. The input will have at least one number (not counting -1) and may consist of up to 100 numbers. Print to the screen all distinct numbers in the array sequentially. In other words, every number that appears in the array will be printed to the screen exactly once, in order by its first appearance, even if it appears multiple times in the array. An example run is shown below: Enter integer values into the array, or 1 to stop 8 Distinct values in the array 5, 3, 4) Enter integer values into the aray, or -1 to stop Distinct values in the array

Explanation / Answer

Solution in JAVA- We are using hashing here to solve the problem in O(n) time complexity.Traverse

the elements of array from left to right and keep track of visited elements in hash table.

import java.util.*;

class Main
{
// This function prints all distinct elements


static void printDistinct(int arr[])

{

// Creates an empty hashset

HashSet<Integer> set = new HashSet<>();

// Traverse the input array

for (int i=0; i<arr.length; i++)

{

// If not present, then put it in hashtable and print it

if (!set.contains(arr[i]))

{
set.add(arr[i]);

System.out.print(arr[i] + " "+" "+" ");

}

}

}

// Driver method to test above method

public static void main (String[] args)

{

int i;

  int arr[] = new int[100];

Scanner s = new Scanner(System.in);

    System.out.println("enter elements of array or -1 to stop");

for(i=0;i<100;i++)

{

arr[i] = s.nextInt();

if(arr[i]== (-1))

break;

}

printDistinct(arr); //calling function

}

}