Question

In: Computer Science

In the java programming language. How would you find if THREE (3) numbers in an array...

In the java programming language. How would you find if THREE (3) numbers in an array add up to a certain sum so for example if my array element consists of: INPUT: 200, 10, 50, 20 and my output asks if these elements add to: 270? YES (200+50+70) 260? YES (200+10+50) 30? NO What method would you suggest to look through the elements in an array (which im going to add through a text file) and determine if these sums exist in O(n^2)?

Solutions

Expert Solution

This is a Hashing based solution.

  • CODE:

(you can edit the code and take input from the file as required)

// Java program to find a triplet using Hashing 
import java.util.*; 

class tripletsum { 

        // returns true if there is triplet 
        // with sum equal to 'sum' present 
        // in A[]. Also, prints the triplet 
        static boolean find3Numbers(int A[],int arr_size, int sum) 
        { 
                // Fix the first element as A[i] 
                for (int i = 0; i < arr_size - 2; i++) { 

                        // Find pair in subarray A[i+1..n-1] 
                        // with sum equal to sum - A[i] 
                        HashSet<Integer> s = new HashSet<Integer>(); 
                        int curr_sum = sum - A[i]; 
                        for (int j = i + 1; j < arr_size; j++) { 
                                if (s.contains(curr_sum - A[j])) { 
                                        System.out.printf("Triplet is %d, %d, %d", A[i],A[j], curr_sum - A[j]); 
                                        return true; 
                                } 
                                s.add(A[j]); 
                        } 
                } 

                // If we reach here, then no triplet was found 
                return false; 
        } 

        /* Driver code */
        public static void main(String[] args) 
        { 
                int A[] = { 1, 4, 45, 6, 10, 8 }; 
                int sum = 22; 
                int arr_size = A.length; 

                find3Numbers(A, arr_size, sum); 
        } 
} 
 
  • Approach: This approach uses extra space but is simpler. Run two loops outer loop from start to end and the inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet.
  • Algorithm:
    1. Traverse the array from start to end. (loop counter i)
    2. Create a HashMap or set to store unique pairs.
    3. Run another loop from i+1 to end of the array. (loop counter j)
    4. If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break
    5. Insert the jth element in the set.
  • Complexity Analysis:
    1. Time complexity: O(N^2).
      There are only two nested loops traversing the array, so time complexity is O(n^2).
    2. Space Complexity: O(1).
      As no extra space is required.

Related Solutions

Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
Java Programming I need an application that collects the user input numbers into an array and...
Java Programming I need an application that collects the user input numbers into an array and after that calls a method that sums all the elements of this array. and display the array elements and the total to the user. The user decides when to stop inputting the numbers. Thanks for your help!
In java language how would I write the following? Create an array called “boyNames” and store...
In java language how would I write the following? Create an array called “boyNames” and store all names from the BoyNames.txt file Similarly, create an array called “girlsNames” and store all names from the GirlNames.txt file Create a text menu that allowing users to:          1. Enter a name and the application must display a message indicating if the name is   among the most popular (found on either array) If the name is found, tell the user if it is a boy’s...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a CPU scheduler. The number of CPU’s and the list of processes and their info will be read from a text file. The output, of your simulator will display the execution of the processes on the different available CPU’s. The simulator should also display: -   The given info of each process -   CPU utilization - The average wait time - Turnaround time for each process...
Java programming language Array - Single identifier which can store multiple values Example initialized with values:...
Java programming language Array - Single identifier which can store multiple values Example initialized with values: int[] mySimpleArray = {4, 17, 99}; Example with fixed length but no values: int[] myFixedArray = new int[11]; The brackets identify the index. Each value has its own index number. NOTE: First element is the zeroth element: mySimpleArray[0] is 4, [1] is 17 Make a new Netbeans project called ArraysAndLoops Create the simple array with 4, 17, 99. Use System.out.println with the variable with...
In C programming language how do you find if all the character on a single line...
In C programming language how do you find if all the character on a single line in a 2 dimensional array are the same? The program should read line by line to check if all the characters on a line are the same. For this program we want to see if the * character ever shows up on a line where it is the only character on the line. as seen below. so lets say we have a array with...
Using C# programming language, Write a program that sort three numbers entered by the user using...
Using C# programming language, Write a program that sort three numbers entered by the user using only if and nested if statements. If for instance the user entered 5, 2, and 7; the program should display 2,5,7.
JAVA LANGUAGE 1. What is the value of creditScores.length, if you have declared an array as...
JAVA LANGUAGE 1. What is the value of creditScores.length, if you have declared an array as follows: int[] creditScores = {670, 720, 815};? a. 0 b. 1 c. 2 d. 3 2. Which of the following correctly assigns the value 100 to each of the array element? Assume the array is declared as int [] num = new int[4] a. for(x=0;x<3;++x) num[x]=100; c. for(x=1;x<4;++x) num[x]=100 ; 3. Consider the following code fragment int[][] rectangle = new int[4][2]; What is the...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not...
art A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array...
art A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT