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
46 changes: 46 additions & 0 deletions DiagonalTraverse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Time Complexity :O(m*n)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode :yes
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[] result = new int[m*n];
int row = 0;
int col = 0;
boolean direction = true;

for(int i = 0; i < m * n; i++) {
result[i] = mat[row][col];
if(direction) {//move up
if(col == n - 1) {//reached last column
row++;
direction = false;
}
else if(row == 0) {//reached top row
col++;
direction = false;
}
else {
row--;
col++;
}
} else {//move down
if(row == m - 1) {//reached bottom row
col++;
direction = true;
}
else if(col == 0) {//reached first column
row++;
direction = true;
}
else {
row++;
col--;
}
}
}
return result;
}
}

21 changes: 21 additions & 0 deletions ProductOfArrayExceptSelf.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Time Complexity :O(n)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode :yes

class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int product = 1;
result[0] = 1;//no left side product for first element
for(int i=1; i<nums.length; i++){//product of left side
product = product * nums[i-1];
result[i] = product;
}
product = 1;//again to calculate product of right elements
for(int i=nums.length-2; i>=0; i--){//product of right side
product = product*nums[i+1];
result[i] = result[i] * product;
}
return result;
}
}
44 changes: 44 additions & 0 deletions SpiralMatrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Time Complexity :O(m*n)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode :yes
import java.util.ArrayList;
import java.util.List;

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int top = 0;
int bottom = m-1;
int left = 0;
int right = n-1;
List<Integer> result = new ArrayList<>();

while(top <= bottom && left <= right){
for(int i=left; i<=right; i++){//top row
result.add(matrix[top][i]);
}
top++;//update top
for(int i=top; i<=bottom; i++){//right column
result.add(matrix[i][right]);
}
right--;//update right
if(top <= bottom)
{
for(int i=right; i>=left; i--){//bottom row
result.add(matrix[bottom][i]);
}
bottom--;//update bottom
}
if(left <= right)
{
for(int i=bottom; i>=top; i--){//left column
result.add(matrix[i][left]);
}
left++;//update left
}
}
return result;
}
}