diff --git a/DisappearedNumbers.java b/DisappearedNumbers.java new file mode 100644 index 00000000..5e0549d9 --- /dev/null +++ b/DisappearedNumbers.java @@ -0,0 +1,31 @@ +import java.util.*; + +//Approach: The idea is to calculate the index of the current element and making the element in that index to negative. +//At the end, iterate through the array to find if there are any positive elements in the original array and add them +// to the result. + +//Time Complexity : O(2n) +//Space Complexity: O(1) + +class DisappearedNumbers { + public List findDisappearedNumbers(int[] nums) { + + List ans = new ArrayList<>(); + + for (int i = 0; i < nums.length; i++) + { + int idx = Math.abs(nums[i]) - 1; + if (nums[idx] > 0){ + nums[idx]*= -1; + } + } + + for(int i=0; i 0){ + ans.add(i+1); + } + } + + return ans; + } +} diff --git a/GameOfLife.java b/GameOfLife.java new file mode 100644 index 00000000..3cc5c93e --- /dev/null +++ b/GameOfLife.java @@ -0,0 +1,61 @@ + +//Approach: The idea behind this solution is to iterate through the matrix using direction array and apply the rules to +//mark a particular element is dead or alive. To avoid collisions, in the first iteration mark the dead and alive with +// other any numbers other than 0 and 1. At the end, iterate through the matrix to replace with original 0 and 1. + +//Time Complexity: O(mxn) +//Space Complexity: O(1) +class GameOfLife +{ + 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}}; + + //live to die => -1 + //die to live => 2 + for(int i=0; i 3) { + board[i][j] = -1; + } + } else { + //Case-4 + if(livingCount(board, i, j) == 3) { + board[i][j] = 2; + } + } + } + } + + for(int i=0; i= 0 && c >= 0 && r < m && c < n && (board[r][c] == 1 || board[r][c] == -1)) // Check boundaries + { + count++; + } + } + + return count; + } +} \ No newline at end of file diff --git a/MaxAndMinArray.java b/MaxAndMinArray.java new file mode 100644 index 00000000..e71522ec --- /dev/null +++ b/MaxAndMinArray.java @@ -0,0 +1,30 @@ +//Given an array of numbers of length N, find both the minimum and maximum. Follow up : Can you do it using less than 2 * (N - 2) comparison +//Time Complexity : O(n) and 2n comparisions +//Space Complexity: O(1) +//Approach: Find min and max between pairs of elements while comparing them with global min and max values to get the final min and max values +public class MaxAndMinArray { + + public int[] FindMaxAndMin(int[] arr) + { + //Validate the inputs + if (arr == null || arr.length == 0) return new int[]{-1, -1}; + + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + + for (int i = 0; i < arr.length-1; i++) + { + if (arr[i] > arr[i+1]) + { + max = Math.max(max, arr[i]); + min = Math.min(min, arr[i+1]); + } + else + { + max = Math.max(max, arr[i+1]); + min = Math.min(min, arr[i]); + } + } + return new int[] {min, max}; + } +}