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
32 changes: 32 additions & 0 deletions findnumsdisappear.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity : O(n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach: used hashset to store the elements of the array and then checked for the missing elements from 1 to n and added them to the result list.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {

List<Integer> result = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
int n = nums.length;

for(int i=0; i<n; i++){
set.add(nums[i]);
}

for(int i=1; i<=n; i++){
if(!set.contains(i)){
result.add(i);
}
}

return result;
}
}


56 changes: 56 additions & 0 deletions gameoflife.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Time Complexity : O(m*n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : figuring out the logic for the problem
// Your code here along with comments explaining your approach: live and dead cells are represented by 1 and 0 respectively. find the next state of the board based on the rules of the game of life. did this by iterating through each cell and counting the number of live neighbors. Based on the count, we can determine if the cell will be alive or dead in the next state. We can use two additional states to represent cells that will change from live to dead (2) and from dead to live (3). After processing all cells, we can update the board to reflect the next state.

class Solution {
int[][] dirs;
int m,n;

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

this.dirs = new int[][]{{-1,-1}, {-1,0}, {-1, 1}, {0, -1}, {0, 1}, {1,-1}, {1,0}, {1,1}};

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

for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int count = getCount(board, i, j);
if(board[i][j] == 0 && count == 3){
board[i][j] = 3;
}else if(board[i][j] == 1 && (count < 2 || count >3)){
board[i][j] = 2;
}
}
}

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

private int getCount(int[][] board, int i, int j){
int count = 0;

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

if(r>=0 && c>=0 && r<m && c<n){
if(board[r][c] == 1 || board[r][c] == 2) count++;
}
}

return count;
}
}