diff --git a/diagonal-traverse.java b/diagonal-traverse.java new file mode 100644 index 00000000..77aff4e6 --- /dev/null +++ b/diagonal-traverse.java @@ -0,0 +1,44 @@ +// Time Complexity :O(m*n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english :We use a boolean variable dir to decide whether to move up-right or down-left along the diagonals. When the traversal hits a boundary (top row, bottom row, left column, or right column), it changes direction and adjusts the row or column accordingly until all elements are visited. + +class Solution { + public int[] findDiagonalOrder(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[] output = new int[m*n]; + int row =0; + int col =0; + // If this is true we go up and if this is false we go down + boolean dir = true; + for(int i=0; i=0; i--) { + output[i] *= runMul; + runMul *= nums[i]; + } + return output; + } +} \ No newline at end of file diff --git a/spiral-matrix.java b/spiral-matrix.java new file mode 100644 index 00000000..6efa0921 --- /dev/null +++ b/spiral-matrix.java @@ -0,0 +1,57 @@ +// Time Complexity :O(m*n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english : We keep track of the current direction (RIGHT, DOWN, LEFT, UP) using an enum. We use bounds (rightBound, downBound, leftBound, upperBound) to know when to turn and shrink the spiral. In each iteration, we add the current element to the output list and moves the row/column according to the direction. When a bound is reached, it changes direction and updates the corresponding bound until all elements are added. + +class Solution { + public List spiralOrder(int[][] matrix) { + List output = new ArrayList<>(); + int m = matrix.length; + int n = matrix[0].length; + enum Direction {UP, DOWN, LEFT, RIGHT} + int rightBound = n-1; + int downBound = m-1; + int leftBound = 0; + int upperBound = 1; + int row = 0; + int col = 0; + Direction dir = Direction.RIGHT; + for(int i=0; i