Java Program to Multiply Corresponding Elements of Two Lists
Last Updated :
07 Jan, 2021
Multiplying two corresponding elements implies multiplying the first element of the one list with the first element of another list and so on with the second element till the size of the list. Given 2 lists of elements, we have to multiply the corresponding elements of two lists.
This can be done in 2 ways:
- Using extra space
- Without Using extra space
Method 1: (Using Extra Space) – You can multiply the corresponding elements and store them in a string using the in-built function Integer.toString and print the string at last.
Java
import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
int a1[] = { 2 , 5 , - 2 , 10 };
int a2[] = { 3 , - 5 , 7 , 1 };
String result = "" ;
for ( int i = 0 ; i < a1.length; i++) {
result += Integer.toString(a1[i] * a2[i]) + " " ;
}
System.out.println(result);
}
}
|
Space Complexity: O(n)
Now instead of using string we can also store the output in the new array if we want to use the result later in the program.
Java
import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
int a1[] = { 2 , 5 , - 2 , 10 };
int a2[] = { 3 , - 5 , 7 , 1 };
int result[] = new int [a1.length];
for ( int i = 0 ; i < a1.length; i++)
{
result[i] = a1[i] * a2[i];
}
for ( int i = 0 ; i < a1.length; i++)
{
System.out.print(result[i] + " " );
}
}
}
|
Space Complexity: O(n)
Method 2: (Without using extra space)
This is the same as the above-mentioned approach. The only difference is instead of using the extra array we will use any of the 2 arrays used in input to store values of the output or after multiplication.
Java
import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
int a1[] = { 2 , 5 , - 2 , 10 };
int a2[] = { 3 , - 5 , 7 , 1 };
for ( int i = 0 ; i < a1.length; i++) {
a1[i] = a1[i] * a2[i];
}
for ( int i = 0 ; i < a1.length; i++) {
System.out.print(a1[i] + " " );
}
}
}
|
Space Complexity: O(1) (as we do not use any other auxiliary space)
Note: Time Complexity of all the above codes is O(n).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...