Product of array elements except for the current index in Java

Hi coders! today we are going to see an Arraylist program where we have to take an array as input and print the product of all elements except the element of current index. This question is very interesting as it is asked in many company placements rounds. So let’s start learning how to find the product of array elements except for the current index in Java.

Product of array elements except for the current index in Java

For a better understanding of the question, let’s take an array,
Size=6
Input array=5, 4, 6, 3, 2, 10

Output array= 1800, 1440, 1200, 2400, 3600, 720

Explanation:- Leave the element at the current index and provide the product of the rest of the element of the given array:-




1800=5*6*3*2*10
1440=4*6*3*2*10
1200=4*5*3*2*10

:
Here the Naive solution that will come into your mind is to solve it by nesting the For loop, one loop is to go to the particular index and second is to start multiplying all elements from the next index till the end, and print the product. But nesting the loops will make time complexity O(n²), which is not an ideal situation.
Another way of solving this is to find the product of all the numbers and then divide this product by the number at the current index and print the quotient. It is not the best solution but better than naive solution as its time complexity is O(n).

Java code to find the product of array elements except for the current index in Java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class product_array {

  public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);
    List<Integer> input=new ArrayList<Integer>();
    int size=sc.nextInt();
    for(int i=0;i<size;i++)   //input the array
    {
        input.add(sc.nextInt());
    }
        int product=1;
    for(int i=0;i<size;i++)   //take product of all number 
    {
      product*=input.get(i);
    }
    for(int j=0;j<size;j++)     //divide the specific number and print the rest
    {
       System.out.println(product/input.get(j));
    }

    
  }

}

OUTPUT:-

Enter the size of input array
6
Enter the array element
4
5
6
3
2
10
Output array:-
1800 1440 1200 2400 3600 720

Hope you understand the code.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *