diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..47947509 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,24 @@ +class Problem1 { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + + int[] result = new int[n]; + + int rp = 1; + result[0] = 1; + + for(int i=1; i=0; i--){ // right pass + rp = rp*nums[i+1]; + result[i] = result[i] * rp; + } + + return result; + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..49034063 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,43 @@ +class Problem2 { + public int[] findDiagonalOrder(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + + int[] result = new int[m*n]; + int r = 0, c = 0; + + boolean dir = true; + + for(int i = 0; i < m * n; i++) { + result[i] = mat[r][c]; + + if(dir) { + if(c == n - 1) { + r++; + dir = false; + } + else if(r == 0) { + c++; + dir = false; + } + else { + r--; c++; + } + } else { + if(r == m - 1) { + c++; + dir = true; + } + else if(c == 0) { + r++; + dir = true; + } + else { + r++; c--; + } + } + } + + return result; + } +} diff --git a/Problem3.java b/Problem3.java new file mode 100644 index 00000000..27f2dd85 --- /dev/null +++ b/Problem3.java @@ -0,0 +1,41 @@ +class Problem3 { + public List spiralOrder(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + + int top = 0, bottom = m-1, left = 0, right = n-1; + + List result = new ArrayList<>(); + + while(top <= bottom && left <= right){ + + for(int i=left; i<=right; i++){ + result.add(matrix[top][i]); + } + top++; + + for(int i=top; i<=bottom; i++){ + result.add(matrix[i][right]); + } + right--; + + if(top <= bottom) + { + for(int i=right; i>=left; i--){ + result.add(matrix[bottom][i]); + } + bottom--; + } + + if(left <= right) + { + for(int i=bottom; i>=top; i--){ + result.add(matrix[i][left]); + } + left++; + } + } + + return result; + } +}