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
27 changes: 27 additions & 0 deletions ArrayProduct.java
Original file line number Diff line number Diff line change
@@ -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;

}
}
56 changes: 56 additions & 0 deletions DiagnolTraverse.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
48 changes: 48 additions & 0 deletions SpiralMatrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import java.util.ArrayList;
import java.util.List;

//TC: O(m * n)
//SC: O(1)
class SpiralMatrix {
public List<Integer> 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<Integer> 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;
}
}