Posts

Showing posts from March, 2015

Java program to check if two elements of an array adds to the given sum

Hi everyone, in this blog post, I will be discussing about a famous java program, which is to check if two elements of an array adds to the given sum. Problem Given an array with elements and a sum. Check whether any 2 elements of the array adds to the given sum. Return true if the sum is present, else return false. Example Given an array {1,2,4}. The array should return true for the sum 5 and false for 4. Solution The basic solution which comes to everyone's mind would be to check each element with each other elements for the given sum. But the total time complexity in doing that will be O(n^2). We will approach the problem in a much easier way. The logic for that is as follows: Sort the given array in ascending order. Create two variables, one which tracks from the first position of array ( pos_first ) and other which tracks from the last position of the array ( pos_last ). While pos_first is less than pos_last , do the below steps. Add the elements corr

Java program to change the elements of the array with the product of remaining elements

Hi Everyone, In this blog post I will be discussing about an interesting program, which is to change the " elements of the array with the product of remaining elements ". This program is really interesting as well as tricky. If an array contains 0, the product of all the elements in the array will be 0. For eg: If an array is [0,1,2], after performing the algorithm, it will be [2,0,0]. Logic The logic of the program is as follows: Initialize an integer variable product = 1. (This variable is used to store the product of all elements of array) Initialize an integer variable countOfZeros =0 Find the product of all the non-zero elements in the array as well as count the number of zero's in the array. If countOfZeros is greater than or equal to 2, then change all the elements of array to 0. If countOfZeros is 1, then change all non zero elements to 0 and 0 to product . If countOfZeros is 0, then change all elements to product /(element). IDE used - Intel