diff --git a/Leetcode238.java b/Leetcode238.java new file mode 100644 index 00000000..b6b4289f --- /dev/null +++ b/Leetcode238.java @@ -0,0 +1,21 @@ +// SC - O(1) since no extra space is being used +// TC - O(n) Iteration of the array twice. +class Solution { + public int[] productExceptSelf(int[] nums) { + int[] res = new int[nums.length]; + int suffixMul = nums[nums.length - 1]; + int prefixMul = 1; + res[0] = prefixMul; + for (int i = 1; i < nums.length; i++) { + res[i] = nums[i - 1] * prefixMul; // res[i] will contain Mul till i-1 + prefixMul = res[i]; // prefix mul 0 to i + } + + for (int i = nums.length - 2; i >= 0; i--) { + res[i] = res[i] * suffixMul;// res[i] will contain Mul till i-1 and multiplied by suffix -> product of all + // items except ith element + suffixMul = nums[i] * suffixMul; // suffix mul from i to n + } + return res; + } +} diff --git a/Leetcode498.java b/Leetcode498.java new file mode 100644 index 00000000..eeb4d0cc --- /dev/null +++ b/Leetcode498.java @@ -0,0 +1,45 @@ +// TC - O(m*n) +// SC - O(1) +class Solution { + public int[] findDiagonalOrder(int[][] mat) { + boolean top = true; + int m = mat.length; + int n = mat[0].length; + int[] res = new int[m * n]; + int i = 0; + int r = 0; + int c = 0; + + while (i < m * n) { + + res[i] = mat[r][c]; + + if (top) { + if ((c + 1) >= n) { + r = r + 1; + top = false; + } else if ((r - 1) < 0) { + c = c + 1; + top = false; + } else { + r = r - 1; + c = c + 1; + } + } else { + if ((r + 1) >= m) { + c = c + 1; + top = true; + } else if ((c - 1) < 0) { + r = r + 1; + top = true; + } else { + c = c - 1; + r = r + 1; + } + + } + i += 1; + } + return res; + } +} diff --git a/Leetcode54.java b/Leetcode54.java new file mode 100644 index 00000000..55982759 --- /dev/null +++ b/Leetcode54.java @@ -0,0 +1,58 @@ +// TC - O(mn) +// SC - O(1) +class Solution { + public List spiralOrder(int[][] matrix) { + List res = new ArrayList<>(); + + int top = 0; + int bottom = matrix.length - 1; + int left = 0; + int right = matrix[0].length - 1; + + int i = 0; // Used to iterate resultant list + int r = 0; // Used to iterate intput matrix + int c = 0; // Used to iterate intput matrix + + while (i < matrix.length * matrix[0].length) { // Use the max number of items possible to add into the array + // instead of using boundaries. + while (c <= right) { + res.add(i, matrix[top][c]); + i += 1; + c += 1; + } + top += 1; + r = top; + while (r <= bottom) { + res.add(i, matrix[r][right]); + i += 1; + r += 1; + } + right -= 1; + + c = right; + if (top <= bottom) { + while (c >= left) { + res.add(i, matrix[bottom][c]); + i += 1; + c -= 1; + } + bottom -= 1; + r = bottom; + } + + if (left <= right && top <= bottom) { + while (r >= top) { + res.add(i, matrix[r][left]); + i += 1; + r -= 1; + } + left += 1; + c = left; + + } + + } + return res; + + } +}