├── .cph └── .test.java_31ab5b91972e73fb4d5f9790a0d81843.prob ├── BST_1 ├── InsertNode.java ├── basicOperations.java ├── deleteNode.java └── validateBst.java ├── BST_2 ├── RecoverBST.java ├── TargetSubPairBST.java ├── bstIterator.java ├── constructBSTfromPostOrder.java ├── constructBSTfrompreorder.java └── constructBstFromLevelOrder.java ├── Bitmanipulation_1 ├── NumberOfSetBits.java ├── SingleNumber.java ├── setBitAtKthPosition.java └── singleNumber_3.java ├── Bitmanipulation_2 ├── flippingBit.java ├── gameOfXor.java └── uniqueNumbersInTripletArray.java ├── ContestDiscussion ├── RadioNetwork.java ├── tamperingScoreboard.java └── telepathicThanos.java ├── Graph_4 ├── .cph │ └── .spreadInfection.java_6a3acc159029607c355e7942aeaba3a9.prob ├── hamiltonianPath.java ├── networkDelayTime.java ├── numberOfEnclaves.java └── spreadInfection.java ├── Graphs_1 ├── .cph │ ├── .graphConstruct.java_cd98b7b6215380a4b8d7eae3cf436915.prob │ └── .graphWithWeights.java_b6922dfddd493f2297bec7f739d64e6e.prob ├── Main$Edge.class ├── Main.class ├── bfs.java ├── dfs.java ├── graphConstruct.java └── graphWithWeights.java ├── Graphs_2 ├── connectedComponentsAdjMatrix.java ├── cycleDirected.java ├── cycleUndirected.java ├── dijkstra.java └── smallestPathProblem.java ├── Graphs_3_contest_discussion ├── catchTheBus.java ├── courseSchedule2.java ├── heaters.java ├── maxUsingAndOr.java └── possibleBipartition.java ├── Greedy_1 ├── DistributeCandy.java ├── FrationalKnapsack.java ├── JobSeq.java ├── LargestPerm.java └── MinCostRopes.java ├── Greedy_2 ├── GasStation.java ├── HuffmanCoding.java ├── HuffmanDecoding.java └── MiceToHoles.java ├── Prefix_1 ├── CarPooling.java ├── MaximumSum.java ├── XorQueries.java ├── rangeSum.java └── rangeSum2d.java ├── Prefix_2 ├── GridGame.java ├── MaxSumNolargerThanK.java ├── circularSumSubarray.java └── maxContSubarraySum.java ├── Revision ├── LCAofBST.java ├── LongestKRepeatingChars.java ├── NumberOfDistinctIslands.java ├── allThreeCharacters.java ├── sumRange.java └── trim.java ├── SlidingWindow2 ├── minwindowSubstring.java ├── slidingWindowMaximum.java └── substringConcatenation.java ├── _Module Guide_ DSA 4.pdf ├── contestDiscussionSlidingWindow ├── AlexKthLargest.java ├── groceryStore2.java ├── matrixChallenge.java ├── maxWidthJump.java └── pairWithKDiff.java ├── sliding_twoPointers ├── 4sum.java ├── maxConsecutiveOnes.java ├── subarrayProdLessthanK.java └── twoSum.java └── test.java /.cph/.test.java_31ab5b91972e73fb4d5f9790a0d81843.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: test","url":"e:\\Codes\\Acciojob\\Module-4-Feb23\\test.java","tests":[{"id":1677155004945,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"e:\\Codes\\Acciojob\\Module-4-Feb23\\test.java","group":"local","local":true} -------------------------------------------------------------------------------- /BST_1/InsertNode.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | class Node{ 6 | int val; 7 | Node left, right; 8 | Node(int val){ 9 | this.val = val; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | class BST{ 15 | Node root = null; 16 | BST(){ 17 | 18 | } 19 | BST(Node root){ 20 | root=root; 21 | } 22 | Node insert(Node root, int val){ 23 | if(root == null){ 24 | root = new Node(val); 25 | return root; 26 | } 27 | if(root.val == val) 28 | return root; 29 | if(val < root.val){ 30 | root.left = insert(root.left, val); 31 | }else{ 32 | root.right = insert(root.right, val); 33 | } 34 | return root; 35 | } 36 | void print(Node root){ 37 | System.out.print(root.val + " "); 38 | if(root.left != null){ 39 | print(root.left); 40 | } 41 | if(root.right != null){ 42 | print(root.right); 43 | } 44 | } 45 | } 46 | 47 | class Solution{ 48 | public Node insertNode(Node root, int val){ 49 | // WRITE YOUR CODE HERE 50 | 51 | if(root==null){ 52 | Node me = new Node(val); 53 | return me; 54 | } 55 | if(root.val == val) return root; 56 | if(val > root.val){ 57 | root.left = insertNode(root.left,val); 58 | }else if(val st = new Stack<>(); 32 | st.push(rtp); 33 | 34 | int idx = 0; 35 | while (st.size() > 0) { 36 | Pair top = st.peek(); 37 | if (top.state == 1) { 38 | idx++; 39 | if (arr[idx] != null) { 40 | top.node.left = new Node(arr[idx], null, null); 41 | Pair lp = new Pair(top.node.left, 1); 42 | st.push(lp); 43 | } else { 44 | top.node.left = null; 45 | } 46 | 47 | top.state++; 48 | } else if (top.state == 2) { 49 | idx++; 50 | if (arr[idx] != null) { 51 | top.node.right = new Node(arr[idx], null, null); 52 | Pair rp = new Pair(top.node.right, 1); 53 | st.push(rp); 54 | } else { 55 | top.node.right = null; 56 | } 57 | 58 | top.state++; 59 | } else { 60 | st.pop(); 61 | } 62 | } 63 | 64 | return root; 65 | } 66 | 67 | public static void display(Node node) { 68 | if (node == null) { 69 | return; 70 | } 71 | 72 | String str = ""; 73 | str += node.left == null ? "." : node.left.data + ""; 74 | str += " <- " + node.data + " -> "; 75 | str += node.right == null ? "." : node.right.data + ""; 76 | System.out.println(str); 77 | 78 | display(node.left); 79 | display(node.right); 80 | } 81 | 82 | public static int size(Node node) { 83 | // write your code here 84 | if(node == null) return 0; 85 | int leftSubtreeSize = size(node.left); 86 | int rightSubtreeSize = size(node.right); 87 | return 1 +leftSubtreeSize + rightSubtreeSize; 88 | } 89 | 90 | public static int sum(Node node) { 91 | // write your code here 92 | if(node == null) return 0; 93 | int leftSubtreeSum = sum(node.left); 94 | int rightSubtreeSum = sum(node.right); 95 | return node.data + leftSubtreeSum + rightSubtreeSum; 96 | } 97 | 98 | public static int max(Node root) { 99 | // write your code here 100 | Node temp = root; 101 | while(temp.right != null) temp= temp.right; 102 | return temp.data; 103 | 104 | } 105 | 106 | public static int min(Node node) { 107 | // write your code here 108 | if(node.left == null) return node.data; 109 | return min(node.left); 110 | // return node.left == null?node.data:min(node.left); 111 | } 112 | 113 | // (true or false)?(first):(second) 114 | 115 | public static boolean find(Node node, int data){ 116 | // write your code here 117 | if(node == null) return false; 118 | if(node.data == data) return true; 119 | if(node.data < data) return find(node.right,data); 120 | else return find(node.left,data); 121 | // return node==null?false:(node.data==data?true:(node.data queue = new LinkedList<>(); 25 | queue.add(root); 26 | int i = 1; 27 | while(queue.size()>0 && i < ip.length) { 28 | Node currNode = queue.peek(); 29 | queue.remove(); 30 | String currVal = ip[i]; 31 | if(!currVal.equals("-1")) { 32 | currNode.left = new Node(Integer.parseInt(currVal)); 33 | queue.add(currNode.left); 34 | } 35 | i++; 36 | if(i >= ip.length) 37 | break; 38 | currVal = ip[i]; 39 | if(!currVal.equals("-1")) { 40 | currNode.right = new Node(Integer.parseInt(currVal)); 41 | queue.add(currNode.right); 42 | } 43 | i++; 44 | } 45 | 46 | return root; 47 | } 48 | static void printInorder(Node root){ 49 | if(root == null) 50 | return; 51 | printInorder(root.left); 52 | System.out.print(root.data+" "); 53 | printInorder(root.right); 54 | } 55 | 56 | public static void main (String[] args) throws IOException{ 57 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 58 | int t=Integer.parseInt(br.readLine()); 59 | while(t > 0){ 60 | String s = br.readLine(); 61 | Node root = treeBuilder(s); 62 | Solution g = new Solution(); 63 | if(g.isBST(root)) 64 | System.out.println("true"); 65 | else 66 | System.out.println("false"); 67 | t--; 68 | } 69 | } 70 | 71 | } 72 | 73 | class Solution{ 74 | 75 | boolean validate(Node node,int lower,int upper){ 76 | if(node == null) return true; 77 | if(node.data <= lower || node.data >= upper) return false; 78 | boolean isLeftBst = validate(node.left,lower,node.data); 79 | boolean isRightBst = validate(node.right,node.data,upper); 80 | return isLeftBst && isRightBst; 81 | } 82 | 83 | boolean isBST(Node root){ 84 | // Your Code Here 85 | return validate(root,Integer.MIN_VALUE,Integer.MAX_VALUE); 86 | } 87 | } 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /BST_2/RecoverBST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static Scanner scn = new Scanner(System.in); 5 | 6 | public static class TreeNode { 7 | int val = 0; 8 | TreeNode left = null; 9 | TreeNode right = null; 10 | 11 | TreeNode(int val) { 12 | this.val = val; 13 | } 14 | } 15 | public static class Pair{ 16 | TreeNode node; 17 | int state; 18 | Pair(TreeNode node,int state){ 19 | this.node = node; 20 | this.state = state; 21 | } 22 | } 23 | 24 | public static TreeNode getNextInorder(Stack st){ 25 | while(st.size()>0){ 26 | Pair top = st.peek(); 27 | if(top.state == 1){ 28 | //pre 29 | top.state++; 30 | if(top.node.left != null) st.push(new Pair(top.node.left,1)); 31 | }else if(top.state == 2){ 32 | //in 33 | top.state++; 34 | if(top.node.right != null) st.push(new Pair(top.node.right,1)); 35 | return top.node; 36 | }else{ 37 | //post 38 | st.pop(); 39 | } 40 | } 41 | return null; 42 | } 43 | public static void recoverTree(TreeNode root) { 44 | //Write code here 45 | Stack st = new Stack<>(); 46 | st.push(new Pair(root,1)); 47 | TreeNode a = null; 48 | TreeNode b = null; 49 | 50 | TreeNode prev = null; 51 | TreeNode curr = getNextInorder(st); 52 | 53 | while(curr != null){ 54 | if(prev != null && prev.val > curr.val){// problematic area 55 | if(a == null){//first problematic area 56 | a = prev; 57 | b = curr; 58 | }else{//second problematic area 59 | b = curr; 60 | } 61 | } 62 | prev = curr; 63 | curr = getNextInorder(st); 64 | } 65 | 66 | int tval= a.val; 67 | a.val= b.val; 68 | b.val = tval; 69 | 70 | } 71 | 72 | // input_section================================================= 73 | 74 | public static void display(TreeNode node) { 75 | if (node == null) 76 | return; 77 | 78 | StringBuilder sb = new StringBuilder(); 79 | sb.append((node.left != null ? node.left.val : ".")); 80 | sb.append(" -> " + node.val + " <- "); 81 | sb.append((node.right != null ? node.right.val : ".")); 82 | 83 | System.out.println(sb.toString()); 84 | 85 | display(node.left); 86 | display(node.right); 87 | 88 | } 89 | 90 | public static TreeNode createTree(int[] arr, int[] IDX) { 91 | if (IDX[0] > arr.length || arr[IDX[0]] == -1) { 92 | IDX[0]++; 93 | return null; 94 | } 95 | 96 | TreeNode node = new TreeNode(arr[IDX[0]++]); 97 | node.left = createTree(arr, IDX); 98 | node.right = createTree(arr, IDX); 99 | 100 | return node; 101 | } 102 | 103 | public static void solve() { 104 | int n = scn.nextInt(); 105 | int[] arr = new int[n]; 106 | for (int i = 0; i < n; i++) 107 | arr[i] = scn.nextInt(); 108 | 109 | int[] IDX = new int[1]; 110 | TreeNode root = createTree(arr, IDX); 111 | recoverTree(root); 112 | display(root); 113 | } 114 | 115 | public static void main(String[] args) { 116 | solve(); 117 | } 118 | } -------------------------------------------------------------------------------- /BST_2/TargetSubPairBST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Node { 4 | int data; 5 | Node left, right; 6 | 7 | public Node(int item) { 8 | data = item; 9 | left = right = null; 10 | } 11 | } 12 | 13 | class BinarySearchTree { 14 | Node constructBST(int[] arr, int start, int end, Node root) { 15 | if (start > end) 16 | return null; 17 | int mid = (start + end) / 2; 18 | 19 | if (root == null) 20 | root = new Node(arr[mid]); 21 | 22 | root.left = constructBST(arr, start, mid - 1, root.left); 23 | root.right = constructBST(arr, mid + 1, end, root.right); 24 | 25 | return root; 26 | 27 | } 28 | } 29 | 30 | public class Main { 31 | public static void main(String[] args) throws Throwable { 32 | Scanner sc = new Scanner(System.in); 33 | int n = sc.nextInt(); 34 | int arr[] = new int[n]; 35 | for (int i = 0; i < n; i++) { 36 | arr[i] = sc.nextInt(); 37 | } 38 | int target = sc.nextInt(); 39 | 40 | Arrays.sort(arr); 41 | Node root = null; 42 | BinarySearchTree bst = new BinarySearchTree(); 43 | root = bst.constructBST(arr, 0, n - 1, root); 44 | 45 | Accio A = new Accio(); 46 | A.targetSum(root, target); 47 | 48 | sc.close(); 49 | } 50 | } 51 | 52 | class Accio { 53 | 54 | public class Pair{ 55 | Node node; 56 | int state; 57 | Pair(Node node,int state){ 58 | this.node = node; 59 | this.state = state; 60 | } 61 | } 62 | 63 | public Node getNextFromNormal(Stack st){ 64 | while(st.size()>0){ 65 | Pair top = st.peek(); 66 | if(top.state == 1){ 67 | //pre 68 | top.state++; 69 | if(top.node.left != null) st.push(new Pair(top.node.left,1)); 70 | }else if(top.state == 2){ 71 | //in 72 | top.state++; 73 | if(top.node.right != null) st.push(new Pair(top.node.right,1)); 74 | return top.node; 75 | }else{ 76 | //post 77 | st.pop(); 78 | } 79 | } 80 | return null; 81 | } 82 | public Node getNextFromReverse(Stack st){ 83 | while(st.size()>0){ 84 | Pair top = st.peek(); 85 | if(top.state == 1){ 86 | //pre 87 | top.state++; 88 | if(top.node.right != null) st.push(new Pair(top.node.right,1)); 89 | }else if(top.state == 2){ 90 | //in 91 | top.state++; 92 | if(top.node.left != null) st.push(new Pair(top.node.left,1)); 93 | return top.node; 94 | }else{ 95 | //post 96 | st.pop(); 97 | } 98 | } 99 | return null; 100 | } 101 | 102 | public void targetSum(Node root, int tar){ 103 | // your code here 104 | Stack normal = new Stack<>();// stack for normal iteration 105 | Stack reverse = new Stack<>(); // stack for reverse iteration 106 | 107 | normal.push(new Pair(root,1)); 108 | reverse.push(new Pair(root,1)); 109 | 110 | Node left = getNextFromNormal(normal);//next inorder node in normal traversal 111 | Node right = getNextFromReverse(reverse);//next inorder node in reverse traversal 112 | boolean printed = false; 113 | 114 | while(left.data < right.data){ 115 | if(left.data + right.data == tar){ 116 | printed = true; 117 | System.out.println(left.data+" "+right.data); 118 | left = getNextFromNormal(normal); 119 | right = getNextFromReverse(reverse); 120 | }else if(left.data + right.data st; 18 | public class Helper{ 19 | TreeNode node; 20 | int state; 21 | Helper(TreeNode node,int state){ 22 | this.node = node; 23 | this.state = state; 24 | } 25 | } 26 | public BSTIterator(TreeNode root) { 27 | //Your code here 28 | st = new Stack<>(); 29 | st.push(new Helper(root,0)); 30 | } 31 | public int next() { 32 | //Your code here 33 | while(st.size() > 0){ 34 | Helper top = st.peek(); 35 | if(top.state == 0){ 36 | // preorder 37 | if(top.node.left != null) st.push(new Helper(top.node.left,0)); 38 | top.state++; 39 | }else if(top.state == 1){ 40 | //inorder 41 | st.pop(); 42 | if(top.node.right != null) st.push(new Helper(top.node.right,0)); 43 | top.state++; 44 | return top.node.val; 45 | } 46 | } 47 | return -1; 48 | } 49 | public boolean hasNext() { 50 | //Your code here 51 | return st.size()>0; 52 | } 53 | } 54 | 55 | public static void display(TreeNode node) { 56 | if (node == null) 57 | return; 58 | StringBuilder sb = new StringBuilder(); 59 | sb.append((node.left != null ? node.left.val : ".")); 60 | sb.append(" -> " + node.val + " <- "); 61 | sb.append((node.right != null ? node.right.val : ".")); 62 | System.out.println(sb.toString()); 63 | display(node.left); 64 | display(node.right); 65 | 66 | } 67 | 68 | public static TreeNode constructFromInOrder_(int[] in, int si, int ei) { 69 | if (si > ei) 70 | return null; 71 | int mid = (si + ei) / 2; 72 | TreeNode node = new TreeNode(in[mid]); 73 | node.left = constructFromInOrder_(in, si, mid - 1); 74 | node.right = constructFromInOrder_(in, mid + 1, ei); 75 | return node; 76 | } 77 | 78 | public static void solve() { 79 | int n = scn.nextInt(); 80 | int[] in = new int[n]; 81 | for (int i = 0; i < n; i++) 82 | in[i] = scn.nextInt(); 83 | TreeNode root = constructFromInOrder_(in, 0, in.length - 1); 84 | BSTIterator itr = new BSTIterator(root); 85 | while (itr.hasNext()) { 86 | System.out.println(itr.next()); 87 | } 88 | } 89 | 90 | public static void main(String[] args) { 91 | solve(); 92 | } 93 | } -------------------------------------------------------------------------------- /BST_2/constructBSTfromPostOrder.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | public static Scanner scn = new Scanner(System.in); 5 | 6 | public static class TreeNode { 7 | int val = 0; 8 | TreeNode left = null; 9 | TreeNode right = null; 10 | 11 | TreeNode(int val) { 12 | this.val = val; 13 | } 14 | } 15 | 16 | public static int idx ; 17 | 18 | public static TreeNode construct(int[] post,int min,int max){ 19 | if(idx <0 || post[idx] max) return null; 20 | TreeNode me = new TreeNode(post[idx]); 21 | idx--; 22 | me.right = construct(post,me.val,max); 23 | me.left = construct(post,min,me.val); 24 | return me; 25 | } 26 | 27 | public static TreeNode CreateTree(int n,int[] postOrder) { 28 | //write code here 29 | idx =postOrder.length-1; 30 | TreeNode root = construct(postOrder,Integer.MIN_VALUE,Integer.MAX_VALUE); 31 | return root; 32 | } 33 | 34 | // input_section================================================= 35 | 36 | public static void display(TreeNode node) { 37 | if (node == null) return; 38 | StringBuilder sb = new StringBuilder(); 39 | sb.append((node.left != null ? node.left.val : ".")); 40 | sb.append("->" + node.val + "<-"); 41 | sb.append((node.right != null ? node.right.val : ".")); 42 | System.out.println(sb.toString()); 43 | display(node.left); 44 | display(node.right); 45 | 46 | } 47 | 48 | public static void solve() { 49 | int n = scn.nextInt(); 50 | int[] post = new int[n]; 51 | for (int i = 0; i < n; i++) 52 | post[i] = scn.nextInt(); 53 | 54 | TreeNode root = CreateTree(n,post); 55 | display(root); 56 | } 57 | 58 | public static void main(String[] args) { 59 | solve(); 60 | } 61 | } -------------------------------------------------------------------------------- /BST_2/constructBSTfrompreorder.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | public static Scanner scn = new Scanner(System.in); 5 | 6 | public static class TreeNode { 7 | int val = 0; 8 | TreeNode left = null; 9 | TreeNode right = null; 10 | 11 | TreeNode(int val) { 12 | this.val = val; 13 | } 14 | } 15 | 16 | public static int idx; 17 | 18 | public static TreeNode construct(int[] pre,int min,int max){ 19 | if(idx >= pre.length) return null; 20 | if(pre[idx]<=min || pre[idx]>=max) return null; 21 | TreeNode me = new TreeNode(pre[idx]); 22 | idx++; 23 | me.left = construct(pre,min,me.val); 24 | me.right = construct(pre,me.val,max); 25 | return me; 26 | } 27 | 28 | public static TreeNode CreateTree(int n,int[] preOrder) { 29 | // Write Your Code here 30 | idx =0; 31 | TreeNode root = construct(preOrder,Integer.MIN_VALUE,Integer.MAX_VALUE); 32 | return root; 33 | } 34 | 35 | // input_section================================================= 36 | 37 | public static void display(TreeNode node) { 38 | if (node == null) return; 39 | StringBuilder sb = new StringBuilder(); 40 | sb.append((node.left != null ? node.left.val : ".")); 41 | sb.append("->" + node.val + "<-"); 42 | sb.append((node.right != null ? node.right.val : ".")); 43 | System.out.println(sb.toString()); 44 | display(node.left); 45 | display(node.right); 46 | 47 | } 48 | 49 | public static void solve() { 50 | int n = scn.nextInt(); 51 | int[] pre = new int[n]; 52 | for (int i = 0; i < n; i++) 53 | pre[i] = scn.nextInt(); 54 | 55 | TreeNode root = CreateTree(n,pre); 56 | display(root); 57 | } 58 | 59 | public static void main(String[] args) { 60 | solve(); 61 | } 62 | } -------------------------------------------------------------------------------- /BST_2/constructBstFromLevelOrder.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | import java.io.*; 4 | import java.util.*; 5 | import java.lang.*; 6 | 7 | class Node { 8 | int data; 9 | Node left; 10 | Node right; 11 | 12 | Node(int data) { 13 | this.data = data; 14 | left = null; 15 | right = null; 16 | } 17 | } 18 | 19 | public class Main { 20 | 21 | static void printLevelOrder(Node root) { 22 | Queue queue = new LinkedList(); 23 | queue.add(root); 24 | while (!queue.isEmpty()) { 25 | 26 | Node tempNode = queue.poll(); 27 | System.out.print(tempNode.data + " "); 28 | 29 | if (tempNode.left != null) { 30 | queue.add(tempNode.left); 31 | } 32 | 33 | if (tempNode.right != null) { 34 | queue.add(tempNode.right); 35 | } 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner sc = new Scanner(System.in); 41 | int n = sc.nextInt(); 42 | int[] arr = new int[n]; 43 | for (int i = 0; i < n; ++i) 44 | arr[i] = sc.nextInt(); 45 | Solution Obj = new Solution(); 46 | Node ans = Obj.bstFromLevel(arr, n); 47 | printLevelOrder(ans); 48 | sc.close(); 49 | } 50 | } 51 | 52 | class Solution { 53 | class Helper{ 54 | int min; 55 | int max; 56 | Node parent; 57 | Helper(Node parent,int min,int max){ 58 | this.parent=parent; 59 | this.min = min; 60 | this.max = max; 61 | } 62 | } 63 | 64 | Node bstFromLevel(int arr[], int n) { 65 | // write code here 66 | Node root = new Node(arr[0]); 67 | int idx = 1; 68 | Queue q = new LinkedList<>(); 69 | q.add(new Helper(root,Integer.MIN_VALUE,root.data)); 70 | q.add(new Helper(root,root.data,Integer.MAX_VALUE)); 71 | while(q.size() > 0){ 72 | Helper curr = q.remove(); 73 | if(idx == arr.length || arr[idx] < curr.min || arr[idx] > curr.max) continue; 74 | Node nn = new Node(arr[idx++]); 75 | if(nn.data < curr.parent.data){ 76 | curr.parent.left = nn; 77 | q.add(new Helper(nn,curr.min,nn.data)); 78 | q.add(new Helper(nn,nn.data,curr.max)); 79 | }else{ 80 | curr.parent.right = nn; 81 | q.add(new Helper(nn,curr.min,nn.data)); 82 | q.add(new Helper(nn,nn.data,curr.max)); 83 | } 84 | } 85 | return root; 86 | } 87 | 88 | 89 | } 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /Bitmanipulation_1/NumberOfSetBits.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int setBits(int n) { 5 | // write code here 6 | int cnt= 0; 7 | while(n!=0){ 8 | cnt++; 9 | n = (n & (n-1)); 10 | } 11 | return cnt; 12 | } 13 | } 14 | 15 | public class Main { 16 | 17 | public static void main(String[] args) throws Throwable { 18 | Scanner sc = new Scanner(System.in); 19 | int n = sc.nextInt(); 20 | Solution Obj = new Solution(); 21 | sc.close(); 22 | System.out.println(Obj.setBits(n)); 23 | } 24 | } -------------------------------------------------------------------------------- /Bitmanipulation_1/SingleNumber.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.*; 4 | 5 | class Solution { 6 | public void singleElement(int[]A,int n) { 7 | //Write code here and print output 8 | int res = 0; 9 | for(int num:A){ 10 | res ^= num; 11 | } 12 | System.out.println(res); 13 | } 14 | } 15 | 16 | public class Main { 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n; 20 | n = sc.nextInt(); 21 | int[] A = new int[n]; 22 | for (int i = 0; i < n; i++) 23 | A[i] = sc.nextInt(); 24 | Solution Obj = new Solution(); 25 | Obj.singleElement(A,n); 26 | sc.close(); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Bitmanipulation_1/setBitAtKthPosition.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int setKBit(int n, int k) { 5 | // write code here 6 | int mask = 1< 0){//if kth bit is set 18 | xorOfpeopleHavingKthBitSet ^= num; 19 | }else{ 20 | xorOfpeopleHavingKthBitUnset ^= num; 21 | } 22 | } 23 | int[] ans = {xorOfpeopleHavingKthBitSet,xorOfpeopleHavingKthBitUnset}; 24 | Arrays.sort(ans); 25 | return ans; 26 | } 27 | } 28 | 29 | public class Main { 30 | public static void main(String[] args) { 31 | Scanner scn = new Scanner(System.in); 32 | int n = scn.nextInt(); 33 | int[] arr = new int[n]; 34 | for (int i = 0; i < n; i++) { 35 | arr[i] = scn.nextInt(); 36 | } 37 | Solution Obj = new Solution(); 38 | scn.close(); 39 | int[] ans = Obj.singleNumber3(n, arr); 40 | System.out.print(ans[0] + " " + ans[1]); 41 | } 42 | } -------------------------------------------------------------------------------- /Bitmanipulation_2/flippingBit.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class Solution { 5 | public long flipBits(long n) { 6 | // your code here 7 | long maxi = (1L<<32) - 1; 8 | // System.out.println(maxi); 9 | return maxi ^ n; 10 | } 11 | } 12 | 13 | public class Main { 14 | public static void main(String args[]) { 15 | Scanner input = new Scanner(System.in); 16 | int q = input.nextInt(); 17 | Solution solution = new Solution(); 18 | for(int qq = 0; qq < q; qq++){ 19 | long n = input.nextLong(); 20 | System.out.println(solution.flipBits(n)); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Bitmanipulation_2/gameOfXor.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution 3 | { 4 | static int xorSubarrayXors(int arr[], int n) { 5 | //Write code here 6 | int ans = 0; 7 | for(int i = 0;i>=1; 17 | } 18 | } 19 | int ans = 0; 20 | int pow = 1;//2^0 21 | for(int i = 0;i<32;i++){ 22 | if(bits[i] % 3 == 1) ans+=pow;//contribution of ith bit 23 | pow*=2; //preparing contribution for the next bit 24 | } 25 | return ans; 26 | } 27 | } 28 | public class Main { 29 | public static void main (String[] args) 30 | { 31 | Scanner sc = new Scanner(System.in); 32 | int n = sc.nextInt(); 33 | int[] nums = new int[n]; 34 | for (int i = 0; i < n; i++) { 35 | nums[i] = sc.nextInt(); 36 | } 37 | System.out.println(Solution.singleNumber(nums)); 38 | } 39 | } -------------------------------------------------------------------------------- /ContestDiscussion/RadioNetwork.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | 5 | public long maxUseful(int n, int[][] roads) { 6 | // write code here 7 | int[] degrees = new int[n]; 8 | for(int[] edge: roads){ 9 | int u = edge[0]; 10 | int v = edge[1]; 11 | degrees[u]++; 12 | degrees[v]++; 13 | } 14 | Arrays.sort(degrees); 15 | long ans = 0; 16 | long currVal = 1; 17 | for(int i = 0;i c1){ 29 | for(int row = 0;row=0;col--){ 40 | if(a[row][col] == 1) cnum+=pow; 41 | pow*=2; 42 | } 43 | total+=cnum; 44 | } 45 | return total; 46 | } 47 | 48 | public static void main(String[] args) { 49 | Scanner sc = new Scanner(System.in); 50 | int m = sc.nextInt(), n = sc.nextInt(); 51 | int[][] matrix = new int[m][n]; 52 | for (int i = 0; i < m; i++) { 53 | for (int j = 0; j < n; j++) { 54 | matrix[i][j] = sc.nextInt(); 55 | } 56 | } 57 | sc.close(); 58 | System.out.println(matrixScore(matrix)); 59 | } 60 | } -------------------------------------------------------------------------------- /ContestDiscussion/telepathicThanos.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | @SuppressWarnings("unchecked") 5 | 6 | public class Pair{ 7 | int wt; 8 | int node; 9 | Pair(int wt,int node){ 10 | this.wt = wt; 11 | this.node = node; 12 | } 13 | } 14 | 15 | public void dijkstra(ArrayList> graph,int[] dist){ 16 | int n = dist.length; 17 | boolean[] visited = new boolean[n]; 18 | 19 | PriorityQueue pq = new PriorityQueue<>((a,b)->{ 20 | return a.wt - b.wt; 21 | }); 22 | 23 | pq.add(new Pair(0,0)); 24 | 25 | while(pq.size()>0){ 26 | Pair curr = pq.remove(); 27 | int wt = curr.wt; 28 | int node = curr.node; 29 | 30 | if(visited[node]) continue; 31 | visited[node] = true; 32 | 33 | dist[node] = wt; 34 | 35 | for(int nbr: graph.get(node)){ 36 | if(!visited[nbr]) pq.add(new Pair(wt+1,nbr)); 37 | } 38 | } 39 | 40 | 41 | } 42 | 43 | public int thanosTelepath(int[][] edges, int[] patience) { 44 | // Write your code here 45 | int n = patience.length;// total subordinates including thanos 46 | ArrayList> graph = new ArrayList<>(); 47 | for(int i = 0;i()); 48 | 49 | for(int[] e: edges){ 50 | int u = e[0]; 51 | int v = e[1]; 52 | graph.get(u).add(v); 53 | graph.get(v).add(u); 54 | } 55 | int[] dist = new int[n]; 56 | dijkstra(graph,dist); 57 | 58 | int idleTime = 0; 59 | 60 | for(int i = 1;i> Edges = new ArrayList>(); 11 | for (int i = 0; i < M; i++) { 12 | ArrayList e = new ArrayList(); 13 | e.add(sc.nextInt()); 14 | e.add(sc.nextInt()); 15 | Edges.add(e); 16 | } 17 | Solution ob = new Solution(); 18 | if (ob.check(N, M, Edges)) { 19 | System.out.println(1); 20 | } else { 21 | System.out.println(0); 22 | } 23 | sc.close(); 24 | } 25 | 26 | } 27 | 28 | class Solution { 29 | 30 | boolean hamiltonian(int curr,boolean[] visited,ArrayList psf,ArrayList> graph,int os){ 31 | int totalNodes = graph.size()-1; //n+1 arraylists in graph ( because of 1 indexing ) 32 | if(psf.size() == totalNodes-1){ 33 | // we have found a hamiltonian path 34 | psf.add(curr); 35 | System.out.print(psf); 36 | psf.remove(psf.size()-1); 37 | 38 | // lets check if this node makes a cycle 39 | // it makes a cycle if it has the os node as one of its neighbours 40 | boolean isCycle = false; 41 | for(int nbr: graph.get(curr)){// why curr? because curr is the last node of the path 42 | if(nbr == os) isCycle = true; 43 | } 44 | if(isCycle) System.out.println(" (Cycle)"); 45 | else System.out.println(); 46 | return true; 47 | } 48 | 49 | visited[curr] = true; 50 | psf.add(curr); 51 | 52 | boolean myRes = false; 53 | // try to visit all unvisited neighbours 54 | for(int nbr: graph.get(curr)){ 55 | if(!visited[nbr]){ 56 | boolean foundAPath = hamiltonian(nbr,visited,psf,graph,os); 57 | if(foundAPath) myRes = true; 58 | } 59 | } 60 | visited[curr] = false; 61 | psf.remove(psf.size()-1); 62 | return myRes; 63 | } 64 | 65 | boolean check(int N, int M, ArrayList> Edges) { 66 | // your code here 67 | ArrayList> graph = new ArrayList<>(); 68 | for(int i = 0;i<=N;i++){ 69 | graph.add(new ArrayList()); 70 | } 71 | for(ArrayList e: Edges){ 72 | int u = e.get(0); 73 | int v = e.get(1); 74 | graph.get(u).add(v); 75 | graph.get(v).add(u); 76 | } 77 | 78 | boolean[] visited = new boolean[N+1];// 1 based indexing 79 | ArrayList psf = new ArrayList<>(); 80 | boolean ans = false; 81 | for(int i = 1;i<=N;i++){ 82 | //trying all the nodes as source nodes 83 | boolean isHamiltonian = hamiltonian(i,visited,psf,graph,i); //treaing i as source, are we able to find hamiltonian paths 84 | //isHamiltonian = true when i detect hamiltonian path using i as source 85 | // if(isHamiltonian) ans = true; same result as below line 86 | ans = ans || isHamiltonian; 87 | } 88 | return ans; 89 | } 90 | } 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /Graph_4/networkDelayTime.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Throwable { 5 | Scanner sc = new Scanner(System.in); 6 | int v,e; 7 | v = sc.nextInt(); 8 | e = sc.nextInt(); 9 | //Create adjacency list of edges 10 | LinkedList> adj[] = new LinkedList[v+1]; 11 | for(int i=0;i<=v;i++) 12 | adj[i] = new LinkedList<>(); 13 | 14 | for(int i=0;i>[] adj){ 39 | int md = (int) 1e9 + 7; 40 | 41 | PriorityQueue pq = new PriorityQueue<>((a,b)->{ 42 | long diff = (a.cost-b.cost); 43 | if(diff>0) return 1; 44 | if(diff<0) return -1; 45 | return 0; 46 | }); 47 | pq.add(new Pair(1,0)); 48 | boolean[] visited = new boolean[V+1]; 49 | long ans = 0;// is the time it takes data to reach the latest computer 50 | 51 | while(pq.size()>0){ 52 | //pop 53 | Pair curr = pq.remove(); 54 | 55 | //mark 56 | if(visited[curr.node]) continue; 57 | visited[curr.node] = true; 58 | 59 | //work 60 | ans = curr.cost; 61 | 62 | //visit 63 | for(List edge: adj[curr.node]){ 64 | int nbr = edge.get(0); 65 | int wt = edge.get(1); 66 | if(!visited[nbr]) pq.add(new Pair(nbr,(wt+curr.cost))); 67 | } 68 | } 69 | 70 | for(int i= 1;i<=V;i++){ 71 | if(!visited[i]) return -1; 72 | } 73 | 74 | return ans; 75 | } 76 | } 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /Graph_4/numberOfEnclaves.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int m = sc.nextInt(), n = sc.nextInt(); 8 | int[][] grid = new int[m][n]; 9 | for (int i = 0; i < m; i++) { 10 | for (int j = 0; j < n; j++) { 11 | grid[i][j] = sc.nextInt(); 12 | } 13 | } 14 | sc.close(); 15 | System.out.println(numEnclaves(grid)); 16 | } 17 | 18 | public static void destroy(int i, int j,int[][] grid){ 19 | if(i < 0 || j<0|| i==grid.length || j==grid[0].length) return; 20 | if( grid[i][j] == 0) return; 21 | grid[i][j] = 0;//destroying an island 22 | destroy(i-1,j,grid);//up 23 | destroy(i,j-1,grid);//left 24 | destroy(i+1,j,grid);//down 25 | destroy(i,j+1,grid);//right 26 | } 27 | 28 | public static int numEnclaves(int[][] grid) { 29 | // your code here 30 | int n = grid.length; 31 | int m = grid[0].length; 32 | for(int i = 0;i[] graph = new ArrayList[vtces]; 20 | for (int i = 0; i < vtces; i++) { 21 | graph[i] = new ArrayList<>(); 22 | } 23 | 24 | int edges = Integer.parseInt(br.readLine()); 25 | for (int i = 0; i < edges; i++) { 26 | String[] parts = br.readLine().split(" "); 27 | int v1 = Integer.parseInt(parts[0]); 28 | int v2 = Integer.parseInt(parts[1]); 29 | graph[v1].add(new Edge(v1, v2)); 30 | graph[v2].add(new Edge(v2, v1)); 31 | } 32 | 33 | int src = Integer.parseInt(br.readLine()); 34 | int t = Integer.parseInt(br.readLine()); 35 | 36 | // write your code here 37 | 38 | Queue q = new LinkedList<>(); 39 | boolean[] vis= new boolean[vtces]; 40 | q.add(src); 41 | int cnt = 0; 42 | 43 | t--; 44 | int sz = q.size(); 45 | while(sz-- > 0){ 46 | int curr= q.remove(); 47 | if(vis[curr]) continue; 48 | vis[curr] = true; 49 | cnt++; 50 | for(Edge e: graph[curr]){ 51 | int nbr = e.nbr; 52 | if(!vis[nbr]) q.add(nbr); 53 | } 54 | } 55 | } 56 | System.out.println(cnt); 57 | } 58 | 59 | } 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /Graphs_1/.cph/.graphConstruct.java_cd98b7b6215380a4b8d7eae3cf436915.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: graphConstruct","url":"e:\\Codes\\Acciojob\\Module-4-Feb23\\Graphs_1\\graphConstruct.java","tests":[{"id":1676549297656,"input":"7 8\n0 1 \n1 2 \n2 3 \n0 3 \n3 4 \n4 5 \n5 6 \n4 6","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"e:\\Codes\\Acciojob\\Module-4-Feb23\\Graphs_1\\graphConstruct.java","group":"local","local":true} -------------------------------------------------------------------------------- /Graphs_1/.cph/.graphWithWeights.java_b6922dfddd493f2297bec7f739d64e6e.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: graphWithWeights","url":"e:\\Codes\\Acciojob\\Module-4-Feb23\\Graphs_1\\graphWithWeights.java","tests":[{"id":1676565150138,"input":"7 8\n0 1 2\n1 2 4\n2 3 5\n0 3 2\n3 4 2\n4 5 5\n5 6 7\n4 6 8","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"e:\\Codes\\Acciojob\\Module-4-Feb23\\Graphs_1\\graphWithWeights.java","group":"local","local":true} -------------------------------------------------------------------------------- /Graphs_1/Main$Edge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rohanfizz/Module-4-Feb23/fd5448add5dd522b0ff7ee7eb57c1ec50a908fb5/Graphs_1/Main$Edge.class -------------------------------------------------------------------------------- /Graphs_1/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rohanfizz/Module-4-Feb23/fd5448add5dd522b0ff7ee7eb57c1ec50a908fb5/Graphs_1/Main.class -------------------------------------------------------------------------------- /Graphs_1/bfs.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | 5 | public class Main { 6 | 7 | public static void bfs(int i,boolean[] visited,ArrayList> graph){ 8 | Queue q = new LinkedList<>(); 9 | q.add(i); 10 | while(q.size()>0){ 11 | int curr = q.remove(); 12 | if(visited[curr]) continue; 13 | visited[curr] = true; 14 | System.out.print(curr+" "); 15 | for(int nbr:graph.get(curr)){ 16 | if(!visited[nbr]) q.add(nbr); 17 | } 18 | } 19 | } 20 | 21 | public static void main(String args[]) { 22 | Scanner scn = new Scanner(System.in); 23 | int n = scn.nextInt(); 24 | int e = scn.nextInt(); 25 | 26 | ArrayList> graph = new ArrayList<>(); 27 | for (int i = 0; i <= n; i++) {//<=n for portal purposes 28 | graph.add(new ArrayList()); 29 | } 30 | //taking input for edges 31 | for (int i = 0; i < e; i++) { 32 | int u = scn.nextInt(); 33 | int v = scn.nextInt(); 34 | //undirected graph 35 | graph.get(u).add(v); 36 | } 37 | 38 | boolean[] visited = new boolean[n+1]; 39 | // for(int i = 0;i> graph,boolean[] visited){ 5 | //mark visited 6 | visited[currNode] = true; 7 | //do work 8 | System.out.print(currNode+" "); 9 | //this is not nessary in dfs 10 | // Collections.sort(graph.get(currNode)); 11 | for(int nbr: graph.get(currNode)){ 12 | // do dfs on those neighbours who are not visited 13 | if(!visited[nbr]) dfs(nbr,graph,visited); 14 | } 15 | } 16 | public static void DFSTraversal(List> edges, int n) { 17 | //Write your code here 18 | 19 | ArrayList> graph = new ArrayList<>(); 20 | for(int i = 0;i()); 21 | 22 | for(List edge: edges){ 23 | int u = edge.get(0); 24 | int v = edge.get(1); 25 | graph.get(u).add(v); 26 | graph.get(v).add(u); 27 | } 28 | boolean[] visited = new boolean[n]; 29 | dfs(0,graph,visited); 30 | 31 | } 32 | } 33 | 34 | public class Main { 35 | public static void main(String[] args) { 36 | Scanner sc = new Scanner(System.in); 37 | int n = sc.nextInt(); 38 | int e = sc.nextInt(); 39 | List> ed = new ArrayList<>(); 40 | for (int i = 0; i < e; i++) { 41 | List l = new ArrayList<>(); 42 | l.add(sc.nextInt()); 43 | l.add(sc.nextInt()); 44 | ed.add(l); 45 | } 46 | 47 | Solution ob = new Solution(); 48 | ob.DFSTraversal(ed, n); 49 | } 50 | } -------------------------------------------------------------------------------- /Graphs_1/graphConstruct.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class graphConstruct{ 4 | 5 | 6 | 7 | public static void main(String[] args){ 8 | Scanner scn = new Scanner(System.in); 9 | 10 | int n = scn.nextInt(); 11 | int e = scn.nextInt(); 12 | 13 | ArrayList> graph =new ArrayList<>(); 14 | for(int i = 0;i()); 16 | } 17 | //taking input for edges 18 | for(int i = 0;i> graph = new ArrayList<>(); 23 | for (int i = 0; i < n; i++) { 24 | graph.add(new ArrayList()); 25 | } 26 | //taking input for edges 27 | for (int i = 0; i < e; i++) { 28 | int u = scn.nextInt(); 29 | int v = scn.nextInt(); 30 | int wt = scn.nextInt(); 31 | //undirected graph 32 | graph.get(u).add(new Edge(v, wt)); 33 | graph.get(v).add(new Edge(u, wt)); 34 | } 35 | 36 | for (int i = 0; i < n; i++) { 37 | System.out.print(i + ": ("); 38 | for (Edge edge : graph.get(i)) { 39 | System.out.print("[ " + edge.nbr + "," + edge.wt + "], "); 40 | } 41 | System.out.println(")"); 42 | } 43 | scn.close(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Graphs_2/connectedComponentsAdjMatrix.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | class Main { 4 | public static void main(String args[]) throws IOException { 5 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 6 | int N = Integer.parseInt(read.readLine()); 7 | 8 | ArrayList> adj = new ArrayList<>(); 9 | 10 | for(int i=0; i temp = new ArrayList<>(); 14 | for(int j=0; j> graph, int N) { 26 | //Your code here 27 | boolean[] visited = new boolean[N]; 28 | int cnt = 0; 29 | for(int i = 0;i q = new LinkedList<>(); 34 | q.add(i); 35 | while(q.size()>0){ 36 | int front = q.remove(); 37 | if(visited[front]) continue; 38 | visited[front] = true; 39 | for(int ii = 0;ii[] graph){ 8 | visited[curr] = true; 9 | path[curr] = true; 10 | 11 | for(int nbr: graph[curr]){ 12 | if(visited[nbr] && path[nbr]) return true; 13 | else if(!visited[nbr]){ 14 | boolean isThereAnyCycleMyDearNbr = dfs(nbr,visited,path,graph); 15 | if(isThereAnyCycleMyDearNbr) return true; 16 | } 17 | } 18 | //if we have reached this line, this means that we are not able to detect any cycle 19 | //from here on, our visited will remain true which will symbolize our failure to detect a cycle 20 | // but path will become false as we will not be present in the path 21 | path[curr] = false; 22 | return false; 23 | } 24 | 25 | public boolean isCyclic(int V, ArrayList[] graph) { 26 | // Your code here 27 | boolean[] visited = new boolean[V]; 28 | boolean[] path = new boolean[V]; 29 | for(int i = 0;i[] adj = new ArrayList[V]; 46 | for (int i = 0; i < V; i++) { 47 | adj[i] = new ArrayList(); 48 | } 49 | for (int i = 0; i < E; i++) { 50 | int u, v; 51 | u = sc.nextInt(); 52 | v = sc.nextInt(); 53 | adj[u].add(v); 54 | } 55 | Solution obj = new Solution(); 56 | boolean ans = obj.isCyclic(V, adj); 57 | if (ans == true) { 58 | System.out.println("True"); 59 | } else { 60 | System.out.println("False"); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /Graphs_2/cycleUndirected.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Solution { 5 | public static boolean isCycle(int V, ArrayList> graph) { 6 | // Your code here 7 | boolean[] visited = new boolean[V]; 8 | for(int i = 0;i q = new LinkedList<>(); 11 | q.add(i); 12 | while(q.size()>0){ 13 | int curr = q.remove(); 14 | if(visited[curr]) return true;// already visited and again trying to visit therefore cycle detected 15 | //mark visited if not already visited 16 | visited[curr] = true; 17 | for(int nbr:graph.get(curr)){ 18 | //add only the unvisited neightbours 19 | if(!visited[nbr]) q.add(nbr); 20 | } 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | } 27 | 28 | public class Main{ 29 | public static void main(String args[]) 30 | { 31 | Scanner sc = new Scanner(System.in); 32 | int N, E; 33 | N = sc.nextInt(); 34 | E = sc.nextInt(); 35 | ArrayList> adj = new ArrayList<>(); 36 | for(int i =0; i()); 37 | for(int i =0; i>> graph, int S){ 19 | // Write your code here 20 | PriorityQueue pq = new PriorityQueue<>((a,b)->{ 21 | return a.wsf-b.wsf; 22 | }); 23 | pq.add( new Pair(S,""+S,0)); 24 | int[] visited = new int[V]; 25 | Arrays.fill(visited,-1); 26 | //from now on normal bfs code 27 | while(pq.size()>0){ 28 | Pair cp = pq.remove(); 29 | int node = cp.node; 30 | String psf = cp.psf; 31 | int wsf = cp.wsf; 32 | 33 | if(visited[node] != -1) continue; 34 | visited[node] = wsf; 35 | 36 | // System.out.println(node+" -> "+psf+" @ "+wsf); 37 | 38 | for(ArrayList edge: graph.get(node)){ 39 | int nbr = edge.get(0); 40 | int cost = edge.get(1); 41 | if(visited[nbr]==-1) pq.add(new Pair( nbr,psf+nbr,wsf+cost)); 42 | } 43 | } 44 | return visited; 45 | 46 | } 47 | 48 | public static void main(String args[]) throws IOException { 49 | 50 | BufferedReader read = 51 | new BufferedReader(new InputStreamReader(System.in)); 52 | String str[] = read.readLine().trim().split(" "); 53 | int V = Integer.parseInt(str[0]); 54 | int E = Integer.parseInt(str[1]); 55 | 56 | ArrayList>> adj = new ArrayList>>(); 57 | for(int i=0;i>()); 60 | } 61 | 62 | int i=0; 63 | while (i++ t1 = new ArrayList(); 69 | ArrayList t2 = new ArrayList(); 70 | t1.add(v); 71 | t1.add(w); 72 | t2.add(u); 73 | t2.add(w); 74 | adj.get(u).add(t1); 75 | adj.get(v).add(t2); 76 | } 77 | 78 | int S = Integer.parseInt(read.readLine()); 79 | 80 | int[] ptr = dijkstra(V, adj, S); 81 | 82 | for(i=0; i { 18 | int wsf; 19 | String psf; 20 | 21 | Pair(int wsf, String psf){ 22 | this.wsf = wsf; 23 | this.psf = psf; 24 | } 25 | 26 | public int compareTo(Pair o){ 27 | return this.wsf - o.wsf; 28 | } 29 | } 30 | 31 | public static void main(String[] args) throws Exception { 32 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 33 | 34 | int vtces = Integer.parseInt(br.readLine()); 35 | ArrayList[] graph = new ArrayList[vtces]; 36 | for (int i = 0; i < vtces; i++) { 37 | graph[i] = new ArrayList<>(); 38 | } 39 | 40 | int edges = Integer.parseInt(br.readLine()); 41 | for (int i = 0; i < edges; i++) { 42 | String[] parts = br.readLine().split(" "); 43 | int v1 = Integer.parseInt(parts[0]); 44 | int v2 = Integer.parseInt(parts[1]); 45 | int wt = Integer.parseInt(parts[2]); 46 | graph[v1].add(new Edge(v1, v2, wt)); 47 | graph[v2].add(new Edge(v2, v1, wt)); 48 | } 49 | 50 | int src = Integer.parseInt(br.readLine()); 51 | int dest = Integer.parseInt(br.readLine()); 52 | 53 | int criteria = Integer.parseInt(br.readLine()); 54 | int k = Integer.parseInt(br.readLine()); 55 | 56 | boolean[] visited = new boolean[vtces]; 57 | multisolver(graph, src, dest, visited, criteria, k,"", 0); 58 | 59 | System.out.println("Smallest Path = " + spath + "@" + spathwt); 60 | System.out.println("Just Larger Path than " + criteria + " = " + cpath + "@" + cpathwt); 61 | System.out.println(k + "th largest path = " + pq.peek().psf + "@" + pq.peek().wsf); 62 | } 63 | 64 | //Solution 65 | 66 | static String spath; 67 | static Integer spathwt = Integer.MAX_VALUE; 68 | static String cpath; 69 | static Integer cpathwt = Integer.MAX_VALUE; 70 | static PriorityQueue pq = new PriorityQueue<>(); 71 | 72 | public static void multisolver(ArrayList[] graph, int src, int dest, boolean[] visited, int criteria, int k, String psf, int wsf) { 73 | //Write code here 74 | //All Variables have been initialized above the function. 75 | if(src == dest){ 76 | String currPath = psf+src; 77 | 78 | //calculating minimum wt path 79 | if(wsf criteria && wsfk) pq.remove(); 92 | return; 93 | } 94 | visited[src] = true; 95 | for(Edge e: graph[src]){ 96 | if(visited[e.nbr]) continue; 97 | multisolver(graph, e.nbr ,dest,visited,criteria,k,psf+src,wsf+e.wt); 98 | } 99 | visited[src] = false; 100 | } 101 | } 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /Graphs_3_contest_discussion/catchTheBus.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int latestTimeCatchTheBus(int[] b, int[] p, int c) { 5 | //Write code here 6 | Arrays.sort(b); 7 | Arrays.sort(p); 8 | HashSet hs = new HashSet<>(); 9 | for(int x: p) hs.add(x); 10 | 11 | int n= b.length; 12 | int m = p.length; 13 | int bidx = 0; 14 | int pidx = 0; 15 | int solb = c;//number of seats remaining in the bus which last passenger boarded 16 | int lastPerson = 1; //passenger who is boarding the bus latest 17 | 18 | while(bidx0 && pidx=p[pidx]){ 21 | lastPerson = p[pidx];//last person boarding a bus will get updated 22 | pidx++;//for next person 23 | cc--;//capacity of this bus decreses by 1 24 | } 25 | solb = cc;//number of seats remaining in the bus which last passenger boarded 26 | bidx++;//lets try to fill the next bus 27 | } 28 | int ans = lastPerson; 29 | if(solb>0 || bidx> graph = new ArrayList<>(); 10 | for(int i =0;i()); 11 | int[] indegree = new int[n]; 12 | for(int[] e: pre){ 13 | graph.get(e[1]).add(e[0]); 14 | indegree[e[0]]++; 15 | } 16 | Queue q = new LinkedList<>(); 17 | for(int i = 0;i0){ 22 | int front =q.remove(); 23 | ans[idx] = front; 24 | idx++; 25 | for(int nbr:graph.get(front)){ 26 | indegree[nbr]--; 27 | if(indegree[nbr] == 0) q.add(nbr); 28 | } 29 | } 30 | if(idx0) 10 | { 11 | int n=sc.nextInt(); 12 | int z=sc.nextInt(); 13 | 14 | int a[]=new int[n]; 15 | for(int i=0;i> graph){ 13 | vis[i] = c; 14 | int nbrc = c == 1?2:1; 15 | for(int nbr:graph.get(i)){ 16 | if(vis[nbr] == c) return false; 17 | else if(vis[nbr] == 0){ 18 | boolean check = dfs(nbr,nbrc,vis,graph); 19 | if(!check) return false; 20 | } 21 | } 22 | return true; 23 | } 24 | public int possibleBipartition(int n, int[][] dislikes) { 25 | // Write your code her 26 | ArrayList> graph = new ArrayList<>(); 27 | for(int i = 0;i<=n;i++) graph.add(new ArrayList<>()); 28 | for(int[] e: dislikes) { 29 | graph.get(e[0]).add(e[1]); 30 | graph.get(e[1]).add(e[0]); 31 | } 32 | int[] vis = new int[n+1]; 33 | Queue q = new LinkedList<>(); 34 | for(int i = 1;i<=n;i++){ 35 | if(vis[i]!=0) continue; 36 | boolean check = dfs(i,1,vis,graph); 37 | if(!check) return 0; 38 | } 39 | return 1; 40 | } 41 | } 42 | public class Main { 43 | public static void main(String[] args) { 44 | Scanner sc = new Scanner(System.in); 45 | int N= sc.nextInt(); 46 | int M= sc.nextInt(); 47 | 48 | int dislike[][] = new int[M][2]; 49 | 50 | for(int i=0; i rating than left neighbour) 12 | for(int i = 1;i A[i-1]){ 14 | candies[i] = candies[i-1]+1; 15 | } 16 | } 17 | //right condition 18 | for(int i = n-2;i>=0;i--){ 19 | if(A[i] > A[i+1]){ 20 | candies[i] = Math.max(candies[i],candies[i+1]+1); 21 | } 22 | } 23 | int total = 0; 24 | for(int x: candies) total+=x; 25 | return total; 26 | } 27 | } 28 | 29 | public class Main { 30 | public static void main(String[] args) { 31 | Scanner sc = new Scanner(System.in); 32 | 33 | int n = sc.nextInt(); 34 | int[] A = new int[n]; 35 | for(int i=0;i{ 50 | //desc, this means that we should return -1 if pwr of a > pwr b 51 | double pwra = (double)(1.0*a.value/a.weight); //value to weight ratio of a 52 | double pwrb = (double)(1.0*b.value/b.weight); 53 | return (pwra > pwrb)? -1 : 1; 54 | }); 55 | 56 | double ans = 0.0; 57 | 58 | for(int i = 0;i= arr[i].weight){//fully take the item 60 | ans+=arr[i].value; 61 | capacity-=arr[i].weight; 62 | }else{// my bag has lesser capacity than the item,take the item partially 63 | ans+= (double)(1.0*arr[i].value/arr[i].weight)*(1.0*capacity); //weight of 1 kg of that item * my bag capacity 64 | capacity = 0; 65 | break; 66 | } 67 | } 68 | return ans; 69 | 70 | } 71 | } 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /Greedy_1/JobSeq.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | class Job { 6 | int id, profit, deadline; 7 | Job(int x, int y, int z){ 8 | this.id = x; 9 | this.deadline = y; 10 | this.profit = z; 11 | } 12 | } 13 | 14 | class Main { 15 | public static void main(String[] args) throws IOException{ 16 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 17 | 18 | 19 | String inputLine[] = br.readLine().trim().split(" "); 20 | 21 | int n = Integer.parseInt(inputLine[0]); 22 | Job[] arr = new Job[n]; 23 | inputLine = br.readLine().trim().split(" "); 24 | 25 | //adding id, deadline, profit 26 | for(int i=0, k=0; i{ 50 | return b.profit-a.profit; 51 | }); 52 | 53 | for(int i = 0;i0 && days[bestPossibleDay]==true) bestPossibleDay--; 56 | //if bestPossibleDay = 0, this means there is no possible day to do this job 57 | if(bestPossibleDay == 0) continue; 58 | //if we are able to do a job, reserve the day[bestPossibleDay], increment the count and profit 59 | days[bestPossibleDay] = true; 60 | cnt++; 61 | totalProfit+=arr[i].profit; 62 | } 63 | int[] ans= {cnt,totalProfit}; 64 | return ans; 65 | } 66 | } 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Greedy_1/LargestPerm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Solution{ 6 | public static int[] largestPermutation(int[] A, int b) { 7 | //Write your code here 8 | int n = A.length; 9 | int[] index = new int[n+1]; 10 | for(int i = 0;i0){ 16 | int idealVal = n-i; 17 | if(A[i] != idealVal){ 18 | //need to do a swap 19 | int currVal = A[i]; 20 | int cvi = i; 21 | int ivi = index[idealVal]; 22 | 23 | index[currVal] = ivi; 24 | index[idealVal] = cvi; 25 | 26 | A[i] = idealVal; 27 | A[ivi] = currVal; 28 | b--; 29 | } 30 | i++; 31 | } 32 | return A; 33 | } 34 | } 35 | 36 | public class Main { 37 | public static void main (String[] args) { 38 | Scanner sc = new Scanner(System.in); 39 | 40 | int n = sc.nextInt(); 41 | int[] A = new int[n]; 42 | for(int i=0;i pq = new PriorityQueue<>(); 10 | for(long x: arr) pq.add(x); 11 | long cost = 0; 12 | while(pq.size()>1){ 13 | long r1 = pq.remove(); 14 | long r2 = pq.remove(); 15 | cost+=(r1+r2); 16 | pq.add(r1+r2); 17 | } 18 | return cost; 19 | } 20 | } 21 | 22 | class Main 23 | { 24 | static class FastReader{ 25 | BufferedReader br; 26 | StringTokenizer st; 27 | 28 | public FastReader(){ 29 | br = new BufferedReader(new InputStreamReader(System.in)); 30 | } 31 | 32 | String next(){ 33 | while (st == null || !st.hasMoreElements()){ 34 | try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } 35 | } 36 | return st.nextToken(); 37 | } 38 | 39 | String nextLine(){ 40 | String str = ""; 41 | try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } 42 | return str; 43 | } 44 | 45 | Integer nextInt(){ 46 | return Integer.parseInt(next()); 47 | } 48 | 49 | Long nextLong(){ 50 | return Long.parseLong(next()); 51 | } 52 | } 53 | 54 | public static void main(String args[]) 55 | { 56 | FastReader sc = new FastReader(); 57 | PrintWriter out = new PrintWriter(System.out); 58 | int n = sc.nextInt(); 59 | long arr[] = new long[n]; 60 | 61 | for(int i=0; i res = ob.huffmanCodes(S,f,N); 18 | for(int i = 0; i < res.size(); i++) 19 | { 20 | System.out.print(res.get(i)+" "); 21 | } 22 | System.out.println(); 23 | 24 | } 25 | } 26 | 27 | class Solution { 28 | 29 | public class Node{ 30 | int freq; 31 | char c; 32 | Node left; 33 | Node right; 34 | Node(char c,int freq){ 35 | this.c = c; 36 | this.freq = freq; 37 | this.left = null; 38 | this.right = null; 39 | } 40 | } 41 | 42 | public ArrayList huffmanCodes(String S, int f[], int N){ 43 | // Code here 44 | PriorityQueue pq = new PriorityQueue<>((a,b)->{ 45 | // return a.freq-b.freq; 46 | return a.freq 1){ 56 | Node smaller = pq.remove(); 57 | Node larger = pq.remove(); 58 | 59 | Node nn = new Node('.',smaller.freq + larger.freq); 60 | nn.left = smaller; 61 | nn.right = larger; 62 | 63 | pq.add(nn); 64 | } 65 | 66 | Node root = pq.remove(); //root of the huffman tree 67 | ArrayList ans = new ArrayList<>(); 68 | dfs(root,ans,""); 69 | return ans; 70 | } 71 | 72 | public void dfs(Node root,ArrayList ans,String psf){ 73 | if(root.left == null && root.right == null){ 74 | ans.add(psf); 75 | return; 76 | } 77 | dfs(root.left,ans,psf+"0"); 78 | dfs(root.right,ans,psf+"1"); 79 | } 80 | 81 | } 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /Greedy_2/HuffmanDecoding.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | abstract class Node implements Comparable { 4 | public int frequency; 5 | public char data; 6 | public Node left, right; 7 | public Node(int freq) { 8 | frequency = freq; 9 | } 10 | public int compareTo(Node tree) { 11 | return frequency - tree.frequency; 12 | } 13 | } 14 | class HuffmanLeaf extends Node { 15 | 16 | public HuffmanLeaf(int freq, char val) { 17 | super(freq); 18 | data = val; 19 | } 20 | } 21 | class HuffmanNode extends Node { 22 | public HuffmanNode(Node l, Node r) { 23 | super(l.frequency + r.frequency); 24 | left = l; 25 | right = r; 26 | } 27 | } 28 | 29 | class Solution { 30 | 31 | /* 32 | class Node 33 | public int frequency; 34 | public char data; 35 | public Node left, right; 36 | 37 | */ 38 | 39 | static String decode(String S, Node root){ 40 | //Write your code here 41 | String ans = ""; 42 | Node curr = root; 43 | 44 | for(int i = 0;i trees = new PriorityQueue(); 66 | for (int i = 0; i < charFreqs.length; i++) 67 | if (charFreqs[i] > 0) 68 | trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); 69 | assert trees.size() > 0; 70 | while (trees.size() > 1) { 71 | Node a = trees.poll(); 72 | Node b = trees.poll(); 73 | trees.offer(new HuffmanNode(a, b)); 74 | } 75 | return trees.poll(); 76 | } 77 | public static Map mapA=new HashMap(); 78 | public static void printCodes(Node tree, StringBuffer prefix) { 79 | assert tree != null; 80 | if (tree instanceof HuffmanLeaf) { 81 | HuffmanLeaf leaf = (HuffmanLeaf)tree; 82 | mapA.put(leaf.data,prefix.toString()); 83 | 84 | } else if (tree instanceof HuffmanNode) { 85 | HuffmanNode node = (HuffmanNode)tree; 86 | prefix.append('0'); 87 | printCodes(node.left, prefix); 88 | prefix.deleteCharAt(prefix.length()-1); 89 | prefix.append('1'); 90 | printCodes(node.right, prefix); 91 | prefix.deleteCharAt(prefix.length()-1); 92 | } 93 | } 94 | public static void main(String[] args) { 95 | Scanner input = new Scanner(System.in); 96 | String test= input.next(); 97 | int[] charFreqs = new int[256]; 98 | for (char c : test.toCharArray()) 99 | charFreqs[c]++; 100 | Node tree = buildTree(charFreqs); 101 | printCodes(tree, new StringBuffer()); 102 | StringBuffer s = new StringBuffer(); 103 | for(int i = 0; i < test.length(); i++) { 104 | char c = test.charAt(i); 105 | s.append(mapA.get(c)); 106 | } 107 | System.out.println(Solution.decode(s.toString(), tree)); 108 | 109 | } 110 | } -------------------------------------------------------------------------------- /Greedy_2/MiceToHoles.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Main { 5 | public static void main(String args[]) throws IOException { 6 | BufferedReader read = 7 | new BufferedReader(new InputStreamReader(System.in)); 8 | 9 | int N = Integer.parseInt(read.readLine()); 10 | String S[] = read.readLine().split(" "); 11 | String st[] = read.readLine().split(" "); 12 | 13 | int[] M = new int[N]; 14 | int[] H = new int[N]; 15 | 16 | for(int i=0 ; i capacity) return false; 44 | return true; 45 | } 46 | } 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Prefix_1/MaximumSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main { 6 | 7 | public static int maximumSum(int[] A, int[][] ops) { 8 | int[] freq = new int[A.length]; 9 | 10 | //iterate on all the operations 11 | for(int i = 0;i=0?pref[i-1]:0); 31 | } 32 | } 33 | public static int getXorInRange(int[] pref,int sp,int ep){ 34 | if(sp == 0) return pref[ep]; 35 | return pref[ep]^pref[sp-1]; 36 | } 37 | public static int[] xorQueries(int[] A, int[][] q) { 38 | // your code goes here 39 | int[] pref = new int[A.length]; 40 | build(pref,A); 41 | int[] ans =new int[q.length]; 42 | for(int i = 0;i=0?pref[i][j-1]:0; 19 | int C = i-1>=0?pref[i-1][j]:0; 20 | int D = i-1>=0 && j-1>=0?pref[i-1][j-1]:0; 21 | pref[i][j] = A + B + C - D; 22 | } 23 | } 24 | } 25 | public int getQuery(int[][] pref,int r1,int c1,int r2,int c2){ 26 | // System.out.println(r2+" "+c2) 27 | int A = pref[r2][c2]; 28 | int B = c1-1>=0?pref[r2][c1-1]:0; 29 | int C = r1-1>=0?pref[r1-1][c2]:0; 30 | int D = r1-1>=0 && c1-1>=0?pref[r1-1][c1-1]:0; 31 | return A - B - C + D; 32 | } 33 | public List solve(int arr[][], Pair q[]) { 34 | // Your code here 35 | int[][] pref = new int[arr.length][arr[0].length]; 36 | build(pref,arr); 37 | List ans = new ArrayList<>(); 38 | for(int i = 0;i ans = obj.solve(matrix, query); 74 | for(int x: ans) 75 | System.out.println(x); 76 | sc.close(); 77 | } 78 | } -------------------------------------------------------------------------------- /Prefix_2/GridGame.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long rangeSum(long[] pref,int l,int r){ 3 | if(r<0) return 0; 4 | if(l == 0) return pref[r]; 5 | return pref[r] - pref[l-1]; 6 | } 7 | 8 | public int kadanes(int[] arr){ 9 | int maxSum = Integer.MIN_VALUE; 10 | int currTrain = Integer.MIN_VALUE; 11 | 12 | for(int i = 0;iend) 17 | return null; 18 | int mid=(start+end)/2; 19 | 20 | if(root==null) 21 | root=new Node(arr[mid]); 22 | 23 | root.left=constructBST(arr,start,mid-1, root.left); 24 | root.right=constructBST(arr,mid+1,end, root.right); 25 | 26 | return root; 27 | 28 | } 29 | } 30 | 31 | public class Main { 32 | public static void main(String[] args) throws Throwable { 33 | Scanner sc = new Scanner(System.in); 34 | int n = sc.nextInt(); 35 | int p = sc.nextInt(); 36 | int q = sc.nextInt(); 37 | int arr[]=new int[n]; 38 | for (int i = 0; i < n; i++) 39 | { 40 | arr[i] = sc.nextInt(); 41 | } 42 | 43 | Arrays.sort(arr); 44 | Node root=null; 45 | BinarySearchTree bst=new BinarySearchTree(); 46 | root=bst.constructBST(arr,0,n-1,root); 47 | 48 | Solution Accio = new Solution(); 49 | Node ans=Accio.LCA(root,p,q); 50 | System.out.println(ans.data); 51 | sc.close(); 52 | 53 | } 54 | } 55 | 56 | class Solution 57 | { 58 | Node LCA(Node node, int n1, int n2){ 59 | if(node == null) return null; 60 | // Your code here 61 | if(node.data > n1 && node.data > n2){ 62 | return LCA(node.left,n1,n2); 63 | }else if(node.data < n1 && node.data < n2){ 64 | return LCA(node.right,n1,n2); 65 | } 66 | //if we are standing in this line of code this means, value node lies between n1 & n2 67 | return node; 68 | } 69 | } -------------------------------------------------------------------------------- /Revision/LongestKRepeatingChars.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | 5 | public int getAns(String s,int x,int k){ 6 | int ans = 0; 7 | int sp =0; 8 | int ep = 0; 9 | int unique = 0; 10 | int charAtLeastK = 0; 11 | int[] freq = new int[150]; 12 | 13 | while(epx){ 19 | freq[s.charAt(sp)]--; 20 | if(freq[s.charAt(sp)] == 0) unique--; 21 | if(freq[s.charAt(sp)] == k-1) charAtLeastK--; 22 | sp++; 23 | } 24 | 25 | if(unique == charAtLeastK) ans = Math.max(ans,ep-sp+1); 26 | ep++; 27 | } 28 | return ans; 29 | } 30 | 31 | public int longestSubstring(String s, int k) { 32 | // write code here 33 | int ans = 0; 34 | for(int i = 0;i<=26;i++) ans = Math.max(ans,getAns(s,i,k)); 35 | return ans; 36 | } 37 | } 38 | 39 | public class Main { 40 | public static void main(String[] args) { 41 | Scanner scn = new Scanner(System.in); 42 | String str = scn.next(); 43 | int k = scn.nextInt(); 44 | Solution Obj = new Solution(); 45 | System.out.println(Obj.longestSubstring(str,k)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Revision/NumberOfDistinctIslands.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | static int[] dr = {-1, 0, 1, 0}; 5 | static int[] dc = {0, 1, 0, -1}; 6 | 7 | private static void dfs(int r, int c, boolean[][] visited, int[][] grid, int x0, int y0, ArrayList curr) { 8 | int rows = grid.length; 9 | int cols = grid[0].length; 10 | visited[r][c] = true; 11 | for(int i = 0; i < 4; i++) { 12 | int nr = r + dr[i]; 13 | int nc = c + dc[i]; 14 | if(nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue; 15 | if(visited[nr][nc] == false && grid[nr][nc] == 1) { 16 | curr.add(Integer.toString(x0-nr) + "-" + Integer.toString(y0-nc)); 17 | dfs(nr, nc, visited, grid, x0, y0, curr); 18 | } 19 | } 20 | } 21 | 22 | public static int countDistinctIslands(int[][] grid) { 23 | 24 | int row = grid.length; 25 | int col = grid[0].length; 26 | 27 | boolean[][] visited = new boolean[row][col]; 28 | // HashMap hm = new HashMap<>(); 29 | HashSet> hm = new HashSet<> (); 30 | for(int i = 0; i < row; i++){ 31 | for(int j = 0; j < col; j++) { 32 | if(visited[i][j] == false && grid[i][j] == 1) { 33 | // island = ""; 34 | ArrayList curr = new ArrayList(); 35 | dfs(i, j, visited, grid, i, j, curr); 36 | hm.add(curr); 37 | // hm.put(island, hm.getOrDefault(island, 0) + 1); 38 | } 39 | } 40 | } 41 | return hm.size(); 42 | } 43 | } 44 | 45 | 46 | public class Main { 47 | public static void main(String[] args) { 48 | Scanner sc = new Scanner(System.in); 49 | int n = sc.nextInt(); 50 | int m = sc.nextInt(); 51 | int[][] grid = new int[n][m]; 52 | 53 | for (int i = 0; i < n; i++) { 54 | 55 | for (int j = 0; j < m; j++) { 56 | grid[i][j] = sc.nextInt(); 57 | } 58 | } 59 | 60 | Solution ob = new Solution(); 61 | int ans = ob.countDistinctIslands(grid); 62 | System.out.println(ans); 63 | } 64 | } -------------------------------------------------------------------------------- /Revision/allThreeCharacters.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class Main { 6 | public static void main(String args[]) { 7 | 8 | Scanner sc = new Scanner(System.in); 9 | String s = sc.nextLine(); 10 | 11 | Solution obj= new Solution(); 12 | System.out.println(obj.numberOfSubstrings(s)); 13 | } 14 | } 15 | class Solution{ 16 | public static int numberOfSubstrings(String s) { 17 | int len = s.length(); 18 | int letter[] = new int[3]; 19 | int count = 0; 20 | int result = 0; 21 | int start = 0, end = 0; 22 | 23 | while(end < len){ 24 | char ch = s.charAt(end); 25 | 26 | if(letter[ch-'a'] == 0){ 27 | count++; 28 | } 29 | letter[ch-'a']++; 30 | while(count == 3){ 31 | char c = s.charAt(start); 32 | if(letter[c-'a'] == 1){ 33 | count--; 34 | } 35 | letter[c-'a']--; 36 | start++; 37 | } 38 | result += start; 39 | end++; 40 | } 41 | return result; 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Revision/sumRange.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Node { 3 | int data; 4 | Node left, right; 5 | public Node(int item) 6 | { 7 | data = item; 8 | left = right = null; 9 | } 10 | } 11 | 12 | class BinarySearchTree 13 | { 14 | Node constructBST(int[]arr,int start,int end,Node root) 15 | { 16 | if(start>end) 17 | return null; 18 | int mid=(start+end)/2; 19 | 20 | if(root==null) 21 | root=new Node(arr[mid]); 22 | 23 | root.left=constructBST(arr,start,mid-1, root.left); 24 | root.right=constructBST(arr,mid+1,end, root.right); 25 | 26 | return root; 27 | 28 | } 29 | } 30 | 31 | public class Main { 32 | public static void main(String[] args) throws Throwable { 33 | Scanner sc = new Scanner(System.in); 34 | int t = sc.nextInt(); 35 | while(t-->0){ 36 | int n = sc.nextInt(); 37 | int l = sc.nextInt(); 38 | int r = sc.nextInt(); 39 | int arr[]=new int[n]; 40 | for (int i = 0; i < n; i++) 41 | { 42 | arr[i] = sc.nextInt(); 43 | } 44 | 45 | Arrays.sort(arr); 46 | Node root=null; 47 | BinarySearchTree bst=new BinarySearchTree(); 48 | root=bst.constructBST(arr,0,n-1,root); 49 | 50 | Solution A = new Solution(); 51 | long ans=A.rangeSum(root,l,r); 52 | System.out.println(ans); 53 | } 54 | } 55 | } 56 | 57 | class Solution { 58 | long rangeSum(Node root, int l, int r){ 59 | // write code here 60 | if(root == null) return 0; 61 | if(root.data < l) return rangeSum(root.right,l,r); 62 | else if(root.data > r) return rangeSum(root.left,l,r); 63 | //if we are standing on this line of code, 64 | // we lie in the range, this means that 65 | // we will contribute + our left subtree can have answer + right as well 66 | return rangeSum(root.left,l,r) + root.data + rangeSum(root.right,l,r); 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /Revision/trim.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Node { 4 | int val; 5 | Node left, right; 6 | public Node(int item){ 7 | val = item; 8 | left = right = null; 9 | } 10 | } 11 | 12 | class BinarySearchTree 13 | { 14 | Node constructBST(int[]arr,int start,int end,Node root) 15 | { 16 | if(start>end)return null; 17 | int mid=(start+end)/2; 18 | if(root==null)root=new Node(arr[mid]); 19 | root.left=constructBST(arr,start,mid-1, root.left); 20 | root.right=constructBST(arr,mid+1,end, root.right); 21 | return root; 22 | } 23 | 24 | void printInorder(Node node){ 25 | if (node == null) 26 | return; 27 | printInorder(node.left); 28 | System.out.print(node.val + " "); 29 | printInorder(node.right); 30 | } 31 | } 32 | 33 | class Solution{ 34 | public static Node trimTree(Node root, int low, int high){ 35 | if(root==null) return null; 36 | 37 | if(root.valhigh){ 41 | return trimTree(root.left,low,high); 42 | } 43 | 44 | root.left=trimTree(root.left,low,high); 45 | root.right=trimTree(root.right,low,high); 46 | return root; 47 | } 48 | } 49 | 50 | public class Main { 51 | public static void main(String[] args) throws Throwable { 52 | Scanner sc = new Scanner(System.in); 53 | int n = sc.nextInt(); 54 | int low = sc.nextInt(); 55 | int high = sc.nextInt(); 56 | int arr[]=new int[n]; 57 | for (int i = 0; i < n; i++){ 58 | arr[i] = sc.nextInt(); 59 | } 60 | Node root=null; 61 | BinarySearchTree bst=new BinarySearchTree(); 62 | root=bst.constructBST(arr,0,n-1,root); 63 | Solution A = new Solution(); 64 | Node ans = A.trimTree(root,low,high); 65 | bst.printInorder(ans); 66 | } 67 | } -------------------------------------------------------------------------------- /SlidingWindow2/minwindowSubstring.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Solution { 5 | 6 | public boolean allCharactersPresent(int[] tf,int[] cwf){ 7 | for(int i = 0;i cwf[i]) return false; 9 | } 10 | return true; 11 | } 12 | 13 | public String minWindow(String s, String t) { 14 | // write code here 15 | int sp = 0; 16 | int ep = 0; 17 | int[] cwf = new int[257]; 18 | int[] tf = new int[257]; 19 | 20 | int os = -1;// start point for my answer substring 21 | int oe =-1;//end point for my answer substring 22 | int anssize = Integer.MAX_VALUE; 23 | 24 | //fill the tf array 25 | for(int i = 0;i dq = new LinkedList<>(); 7 | int sp = 0; 8 | int ep = 0; 9 | int[] ans = new int[N-K+1]; 10 | 11 | while(ep0 && arr[dq.getLast()] < arr[ep]) dq.removeLast(); 13 | dq.addLast(ep); 14 | ep++; 15 | } 16 | ans[0] = arr[dq.getFirst()]; 17 | 18 | while(ep0 && arr[dq.getLast()] < arr[ep]) dq.removeLast(); 23 | dq.addLast(ep); 24 | ep++; 25 | // number in front is the maximum one, but that can or cannot be in range 26 | // remove until you find a number who is in range 27 | while(dq.getFirst() ideal,HashMap cwin ){ 5 | for(String s: cwin.keySet()){ 6 | //if the word is not present in ideal hashmap 7 | if(!ideal.containsKey(s)) return true; 8 | if(cwin.get(s) > ideal.get(s)) return true; 9 | } 10 | return false; 11 | } 12 | public List findSubstring(String s, String[] words) { 13 | // write code here 14 | List ans = new ArrayList<>(); 15 | // ideally my answer strings should have all the strings of words[] 16 | HashMap ideal = new HashMap<>(); 17 | 18 | for(String ss: words){ 19 | ideal.put(ss,ideal.getOrDefault(ss,0)+1); 20 | } 21 | // helper variables 22 | int wordLen = words[0].length(); 23 | int n = s.length(); 24 | int totalWords = words.length; 25 | 26 | for(int i = 0;i cwhm = new HashMap<>(); 30 | 31 | while(ep+wordLen<=n){ 32 | String curr = s.substring(ep,ep+wordLen); 33 | cwhm.put(curr,cwhm.getOrDefault(curr,0)+1); 34 | ep+=wordLen; 35 | 36 | //after adding this word, i can have excess words 37 | while(sp indexes = Obj.findSubstring(str,words); 68 | Collections.sort(indexes); 69 | for(int i=0;iend) 17 | return null; 18 | int mid=(start+end)/2; 19 | 20 | if(root==null) 21 | root=new Node(arr[mid]); 22 | 23 | root.left=constructBST(arr,start,mid-1, root.left); 24 | root.right=constructBST(arr,mid+1,end, root.right); 25 | 26 | return root; 27 | 28 | } 29 | } 30 | 31 | public class Main { 32 | public static void main(String[] args) throws Throwable { 33 | Scanner sc = new Scanner(System.in); 34 | int n = sc.nextInt(); 35 | 36 | int arr[]=new int[n]; 37 | for (int i = 0; i < n; i++) 38 | { 39 | arr[i] = sc.nextInt(); 40 | } 41 | int k=sc.nextInt(); 42 | Arrays.sort(arr); 43 | Node root=null; 44 | BinarySearchTree bst=new BinarySearchTree(); 45 | root=bst.constructBST(arr,0,n-1,root); 46 | 47 | Solution Accio = new Solution(); 48 | int ans=Accio.solve(root,k); 49 | System.out.println(ans); 50 | sc.close(); 51 | 52 | } 53 | } 54 | class Solution 55 | { 56 | 57 | class Pair{ 58 | Node node; 59 | int state; 60 | Pair(Node node,int state){ 61 | this.node = node; 62 | this.state = state; 63 | } 64 | } 65 | 66 | Node getNextReverse(Stack st){ 67 | while(st.size()>0){ 68 | Pair top = st.peek(); 69 | if(top.state == 1){ 70 | //pre 71 | if(top.node.right != null) st.push(new Pair(top.node.right,1)); 72 | top.state++; 73 | }else if(top.state == 2){ 74 | //in 75 | if(top.node.left != null) st.push(new Pair(top.node.left,1)); 76 | top.state++; 77 | return top.node; 78 | }else{ 79 | st.pop(); 80 | } 81 | } 82 | return null; //dummy return 83 | } 84 | 85 | int solve(Node node, int k){ 86 | // your cod here 87 | Stack st = new Stack<>(); 88 | st.push(new Pair(node,1)); 89 | 90 | Node curr = getNextReverse(st); 91 | 92 | while(curr != null && k>1){ 93 | curr = getNextReverse(st); 94 | k--; 95 | } 96 | return curr.data; 97 | 98 | } 99 | } 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /contestDiscussionSlidingWindow/groceryStore2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int m = sc.nextInt(); 8 | int n = sc.nextInt(); 9 | int[][] arr = new int[m][n]; 10 | for (int i = 0; i < m; i++) { 11 | for (int j = 0; j < n; j++) { 12 | arr[i][j] = sc.nextInt(); 13 | } 14 | } 15 | Solution s = new Solution(); 16 | int[] ans = s.bestProducts(arr); 17 | for (int i = 0; i < m; i++) { 18 | System.out.println(ans[i]); 19 | } 20 | } 21 | } 22 | 23 | class Solution { 24 | public static int[] bestProducts(int[][] arr) { 25 | // Write your code 26 | int n = arr.length; 27 | int m = arr[0].length; 28 | int[] ans = new int[n]; 29 | 30 | for(int i = 0;i maxi){ 37 | maxi = arr[i][j]; 38 | maxIdx = j; 39 | } 40 | } 41 | ans[i] = maxIdx; 42 | } 43 | return ans; 44 | } 45 | } 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /contestDiscussionSlidingWindow/matrixChallenge.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | class Main 4 | { 5 | public static void main(String args[]) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | 9 | int m,n,target; 10 | m=sc.nextInt(); 11 | n=sc.nextInt(); 12 | target=sc.nextInt(); 13 | 14 | int matrix[][]=new int[m][n]; 15 | 16 | for(int i=0;i=0;i--){ 10 | rMax[i] = Math.max(nums[i],rMax[i+1]); 11 | } 12 | 13 | int i = 0; 14 | int j = 1; 15 | int ans = 0; 16 | 17 | while(j> fourSum(int[] nums, int target) { 5 | // Write your code here 6 | Arrays.sort(nums); 7 | int n = nums.length; 8 | List> ans = new ArrayList<>(); 9 | for(int i = 0;i curr = new ArrayList<>(); 21 | curr.add(nums[i]); 22 | curr.add(nums[j]); 23 | curr.add(nums[l]); 24 | curr.add(nums[r]); 25 | ans.add(curr); 26 | l++; 27 | while(ll && nums[r]==nums[r+1]) r--; 30 | }else if(suml && nums[r]==nums[r+1]) r--; 36 | } 37 | } 38 | //take j to the last index of the same value 39 | while(j+1> res = Obj.fourSum(nums, k); 61 | 62 | 63 | for(int i= 0; i>() { 69 | public int compare(List frst, List scnd) { 70 | int i=0; 71 | while(frst.get(i)==scnd.get(i)) i++; 72 | return frst.get(i)-scnd.get(i); 73 | } 74 | }); 75 | 76 | for(int i=0; i k){ 18 | if(arr[sp] == 0) numOfZeroesInCurrWindow--; 19 | sp++; 20 | } 21 | //on this line of code, our window will always be valid 22 | ans = Math.max(ans,ep-sp+1); 23 | ep++; 24 | } 25 | return ans; 26 | } 27 | 28 | } 29 | 30 | public class Main { 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | int n= sc.nextInt(); 34 | int k= sc.nextInt(); 35 | int array[] = new int[n]; 36 | 37 | for(int i=0; i= k){ 15 | winProd/=nums[sp]; 16 | sp++; 17 | } 18 | 19 | ans += (ep-sp+1); 20 | ep++; 21 | } 22 | return ans; 23 | } 24 | } 25 | 26 | public class Main { 27 | public static void main(String[] args) { 28 | Scanner sc = new Scanner(System.in); 29 | int n; 30 | n = sc.nextInt(); 31 | int arr[] = new int[n]; 32 | for (int i = 0; i < n; i++) 33 | arr[i] = sc.nextInt(); 34 | int k; 35 | k = sc.nextInt(); 36 | Solution Obj = new Solution(); 37 | int result = Obj.numSubarrayProductLessThanK(arr, k); 38 | System.out.println(result); 39 | sc.close(); 40 | } 41 | } -------------------------------------------------------------------------------- /sliding_twoPointers/twoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main { 6 | 7 | public static int[] twoSum(int[] arr, int target) { 8 | int n = arr.length; 9 | int l = 0; 10 | int r = n-1; 11 | int[] ans = new int[2]; 12 | while(l>= 1; 18 | } 19 | 20 | // if (decimal < 0) { 21 | // binary.append('-'); 22 | // } 23 | 24 | return binary.reverse().toString(); 25 | } 26 | 27 | public static void main(String[] args) { 28 | Scanner scn = new Scanner(System.in); 29 | int n = -77; 30 | System.out.println(decimalToBinary(n) + " " + n); 31 | int bit = 0; 32 | while (bit < 32) { 33 | System.out.println(decimalToBinary(n) + " " + n); 34 | n >>= 1; 35 | bit++; 36 | } 37 | scn.close(); 38 | } 39 | } 40 | // 1 11111111111111111111111110110011 -77 41 | // 0 00000000000000000000000001001101 77 42 | --------------------------------------------------------------------------------