-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathArrayProductExceptSelf.java
94 lines (77 loc) · 2.42 KB
/
ArrayProductExceptSelf.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Problem statement:
Given an integer array, we need to display a new array
such that array[index] is equal to the product of all the
elements of the array except array[index].
*/
class Solution {
public static int[] productExceptSelf(int[] nums) {
//find the product of all elements of the matrix
int product = 1;
for(int index=0;index<nums.length;index++){
product = product*nums[index];
}
//case when product 0
//if product=0, find the index that has 0 element
int zeroindex=0;
if(product==0){
for(int index=0;index<nums.length;index++){
if(nums[index]==0){
zeroindex=index;
}
}
//find the new product excluding 0 element
int newproduct=1;
for(int index=0;index<nums.length;index++){
if(index!=zeroindex){
newproduct = newproduct*nums[index];
}
}
for(int index=0;index<nums.length;index++){
if(index==zeroindex){
nums[index]=newproduct;
}else{
nums[index]=0;
}
}
return nums;
}
//case when product not zero
for(int i=0;i<nums.length;i++){
nums[i]=product/nums[i];
}
return nums;
}
//main method
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = sc.nextInt();
int nums[] = new int[n];
System.out.println("Enter the array elements: ");
for(int index=0;index<n;index++){
nums[index]=sc.nextInt();
}
int[] result = new int[n];
result = productExceptSelf(nums);
System.out.print("The array of product except self is: ");
for(int i=0;i<n;i++){
System.out.print(result[i]+" ");
}
}
}
/*
EXAMPLES:
INPUT:
Enter length of array: 2
Enter the array elements: 4 2
OUTPUT:
The array of product except self is: 2 4
INPUT:
Enter length of array: 3
Enter the array elements: 1 0 4
OUTPUT:
The array of product except self is: 0 4 0
Time complexity: O(n)
Space complexity: O(n)
*/