diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..9739d987 Binary files /dev/null and b/.DS_Store differ diff --git a/FindAllNumbersDisappearedInAnArray.cs b/FindAllNumbersDisappearedInAnArray.cs new file mode 100644 index 00000000..6a5f3fd4 --- /dev/null +++ b/FindAllNumbersDisappearedInAnArray.cs @@ -0,0 +1,28 @@ +public class FindAllDisappearedNumbers { + +// We use each number in the array to mark its corresponding index negative. +// If any index remains positive, it means that number was missing from the array. +// So we collect all those index+1 values as the result. + +// Time Complexity: +// O(n) + +// Space Complexity: +// O(1) + public IList FindDisappearedNumbers(int[] nums) { + List list = new List(); + int n = nums.Length; + for(int i=0;i 0) + nums[index] *= -1; + } + for(int i=0;i 0) + list.Add(i+1); + } + return list; + } +} diff --git a/GameOfLife.cs b/GameOfLife.cs new file mode 100644 index 00000000..1c933486 --- /dev/null +++ b/GameOfLife.cs @@ -0,0 +1,72 @@ +public class GameOfLife { + + // Time Complexity: + // O(m*n) + + // Space Complexity: + // O(1) + + // Traverse the board and count live neighbors for each cell using 8 directions, treating 1 and 2 as originally alive. + + // Mark state transitions in-place using encoded values (1→2 for live→dead, 0→3 for dead→live) based on Game of Life rules. + + // Do a second pass to finalize the board by converting 2→0 and 3→1. + public void GameOfLife(int[][] board) + { + int m = board.Length; + int n = board[0].Length; + // 1 -> 0 =2; + // 0 -> 1 =3 + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + int count = countAlive(board, i, j); + if (board[i][j] == 1 && (count < 2 || count > 3)) + { + board[i][j] = 2; + } + if (board[i][j] == 0 && count == 3) + { + board[i][j] = 3; + } + } + } + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + + if (board[i][j] == 2) + { + board[i][j] = 0; + } + if (board[i][j] == 3) + { + board[i][j] = 1; + } + } + } + } + private int countAlive(int[][] board,int i,int j) + { + int count = 0; + int[][] dirs = {new int[]{0,1},new int[]{0,-1},new int[]{-1,0}, + new int[]{1,0},new int[]{-1,-1}, new int[]{-1,1},new int[]{1,-1}, + new int[]{1,1} +}; + foreach (int[] dir in dirs) + { + int nr = i + dir[0]; //i is current index + direction + int nc = j + dir[1]; + + if(nr >=0 && nc >=0 && nr < board.Length && nc < board[0].Length && + (board[nr][nc] == 1 || board[nr][nc] == 2 )) + { + count++; + } + } + + return count; + } +}