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
64 changes: 64 additions & 0 deletions Leetcode_289.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//In this problem, we need to update the given board. If we do so, we might loose old value. To retain it, we will update the values other than 0 or 1[as 0 and 1 are given in input]
//TC: 8*O(m*n); SC:O(1)


class Solution {
public void gameOfLife(int[][] board) {

int n=board.length;
int m=board[0].length;

for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int active=getAliveCount(board,i,j);

if(board[i][j] == 1 && (active>3 || active<2)){
board[i][j]=2;
}

if(board[i][j] == 0 && (active==3)){
board[i][j]=3;
}


}
}

for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]==2){
board[i][j]=0;
}

if(board[i][j]==3){
board[i][j]=1;
}
}
}

}

private int getAliveCount(int[][] board, int i, int j){
int[][] dir=new int[][]{
{-1,-1},{0,-1},{-1,0},{1,1},{0,1},{1,0},{-1,1},{1,-1}
};

int ans=0;

for(int[] d:dir){
int r=i+d[0];
int c=j+d[1];

if((r>=0 && r<board.length) && (c>=0 && c<board[0].length)){
if(board[r][c]==1 || board[r][c]==2){
ans+=1;
}

}


}

return ans;
}
}
58 changes: 58 additions & 0 deletions Leetcode_448.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//way1
//Store them in Set. Iterate and identify which element is missed.
//TC: O(2n); SC: O(n)
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
Set<Integer> set=new HashSet<>();

//first iteration
for(int i:nums){
set.add(i);
}

int n=nums.length;

List<Integer> ans=new ArrayList<>();
//second iteration
for(int i=1;i<=n;i++){
if(!(set.contains(i))){
ans.add(i);
}
}

return ans;

}
}

//way2
//Mutate the original array by going to the exact position of element present at index
//nums[0]=5 -- go to index 4[because 5th element's position is at 4] and update it to negative value at 4th index. It means element 5 is present
//After updating the entire array with abive concept, travel array again to identify missing elements
//TC: O(2n); SC: constant
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n=nums.length;
for(int i=0;i<n;i++){
int idx=Math.abs(nums[i])-1;
if(nums[idx]>0){
nums[idx]*=-1;
}

}

List<Integer> ans=new ArrayList<>();

for(int i=0;i<n;i++){

if(nums[i]>0){
ans.add(i+1);
}else{
nums[i]*=-1;
}
}

return ans;

}
}