PREFIX & SUFFIX Product of array 3n time complexity
import java.util.*;
class Solution {
public static void main(String[] args) {
// Create an instance of the Solution class
Solution s=new Solution();
// Define an input array
int[] nums = {1, 2, 3, 4 ,5};
// Call the productExceptSelf method and store the result
int[] result = s.productExceptSelf(nums);
// Print the output array
System.out.println("Product Except Self: ");
for (int num : result) {
System.out.print(num + " ");
}
}
public int[] productExceptSelf(int[] nums) {
int len=nums.length;
int result[]=new int[len];
int suffix[]=new int[len];
int prefix[]=new int[len];
prefix[0]=nums[0];
suffix[len-1]=nums[len-1];
for(int i=1;i<len;i++){
prefix[i]=prefix[i-1]*nums[i];
}
for(int i=len-2;i>=0;i--){
suffix[i]=suffix[i+1]*nums[i];
}
for(int i=0;i<len;i++){
System.out.println(suffix[i]);
}
result[0]=suffix[1];
result[len-1]=prefix[len-2];
for(int i=1;i<=len-2;i++){
result[i]=suffix[i+1]*prefix[i-1];
}
return result;
}
}
Comments
Post a Comment