Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Leetcode238.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
45 changes: 45 additions & 0 deletions Leetcode498.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
58 changes: 58 additions & 0 deletions Leetcode54.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// TC - O(mn)
// SC - O(1)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> 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;

}
}