diff --git a/ArrayProduct.java b/ArrayProduct.java new file mode 100644 index 00000000..90d1e255 --- /dev/null +++ b/ArrayProduct.java @@ -0,0 +1,27 @@ + +//TC: O(n) where n is the length of the array +//SC: O(1) +//Implemented using a new array and caluculate the product of the left side and push them to array +// then to same array multiply with the product of the right side +class ArrayProduct { + public int[] productExceptSelf(int[] nums) { + if(nums == null || nums.length == 0) { + return new int[] {}; + } + int n = nums.length; + int rp = 1; + int[] ans = new int[n]; + ans[0] = rp; + for(int i = 1; i< n; i++) { + rp *= nums[i-1]; + ans[i] = rp; + } + rp = 1; + for(int i = n-2; i>= 0; i--) { + rp *= nums[i+1]; + ans[i] *= rp; + } + return ans; + + } +} diff --git a/DiagnolTraverse.java b/DiagnolTraverse.java new file mode 100644 index 00000000..f04b7f99 --- /dev/null +++ b/DiagnolTraverse.java @@ -0,0 +1,56 @@ + +//TC: O(m * n) +//SC: O(1) +//Implemented using the directions from bottom to top and top to bottom +class DiagnolTraverse { + public int[] findDiagonalOrder(int[][] mat) { + if(mat == null || mat.length == 0) { + return new int[] {}; + } + int m = mat.length; + int n = mat[0].length; + int[] ans = new int[m * n]; + int row = 0; + int col = 0; + int index = 0; + int dir = 1; + //1 -> bottom to top; + //-1 -> top to bottom; + while( index < m * n){ + ans[index] = mat[row][col]; + index++; + if(dir == 1) { + if(col == n-1) { + dir = -1; + row++; + + } else if(row == 0) { + dir = -1; + col++; + + } else { + row--; + col++; + } + + } else { + if(row == m-1) { + dir = 1; + col++; + + } else if(col == 0) { + dir = 1; + row++; + + } else { + row++; + col--; + } + + } + + } + + return ans; + } +} diff --git a/SpiralMatrix.java b/SpiralMatrix.java new file mode 100644 index 00000000..a0e7cfdb --- /dev/null +++ b/SpiralMatrix.java @@ -0,0 +1,48 @@ +import java.util.ArrayList; +import java.util.List; + +//TC: O(m * n) +//SC: O(1) +class SpiralMatrix { + public List spiralOrder(int[][] matrix) { + if(matrix == null || matrix.length == 0) { + return new ArrayList<>(); + } + int m = matrix.length; + int n = matrix[0].length; + int left = 0; + int right = n-1; + int top = 0; + int bottom = m-1; + List result = new ArrayList<>(); + while(top <= bottom && left <= right) { + //Move from left to right + for(int i = left; i <= right; i++) { + result.add(matrix[top][i]); + } + top++; + //Move from top to bottom + for(int i = top; i <= bottom; i++) { + result.add(matrix[i][right]); + } + right--; + //Move from right to left + if(top <= bottom) { + for(int i = right; i >= left; i--) { + result.add(matrix[bottom][i]); + } + bottom--; + } + //Move from bottom to top + if(left <= right) { + for(int i = bottom; i >= top; i--) { + result.add(matrix[i][left]); + } + left++; + } + + + } + return result; + } +} \ No newline at end of file