Java solution using two way traverse

  • 1

    public int[] productExceptSelf(int[] nums) {

        int length = nums.length;
        int[] result = new int[length];
        if(nums==null)return result;
        int[] front = new int[length];
        int[] back = new int[length];
        int frontM = 1;
        int backM = 1;
        for(int i=0;i<length;i++){
            front[i] = frontM;
            back[length-1-i] = backM;
        result[0] = back[1];
        result[length-1] = front[length-2];
        for(int j=1;j<length-1;j++){
            result[j] = front[j-1] * back[j+1]; 
        return result;

  • 0

    you are using extra space. The problem wants you to do it in constant space.

    Think on how you can solve the problem with only input array and space for output array. Make them as your front and back array.

Log in to reply

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