5 lines in Java-You can solve this problem without any extra space(besides the loop variable such as the index i).

  • -1
    public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] result = new int[nums.length];
        result[0] = 1;
        for(int i=1;i<nums.length;i++) result[i] = result[i-1] * nums[i-1];
        for(int i=nums.length-2;i>=0;nums[nums.length-1] *= nums[i--]) result[i] *= nums[nums.length-1];//save the temporary value into the last index of the array
        return result;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.