├── Height of Binary Tree ├── c++ └── java ├── Strings Rotations of Each Other ├── Java └── C++ ├── Union of Arrays with Duplicates ├── java └── c++ ├── Number of occurrence ├── c++ └── java ├── Two Sum - Pair with Given Sum ├── java └── C++ ├── Rotate by 90 degree ├── c++ └── java ├── Remove the balls ├── java └── c++ ├── Count pairs with given sum ├── java └── C++ ├── Implement Pow ├── java └── c++ ├── Inorder Traversal ├── c++ │ ├── using Recursion │ └── using Stack └── java │ ├── using Recursion │ └── using Stack ├── Non-overlapping Intervals ├── java └── c++ ├── Diameter of a Binary Tree ├── c++ └── java ├── Symmetric Tree ├── c++ └── java ├── Intersection of Two arrays with Duplicate Elements ├── c++ └── java ├── Detect Loop in linked list ├── java └── c++ ├── Merge Without Extra Space ├── c++ └── java ├── Count Pairs whose sum is less than target └── java and c++ ├── BST with Dead End ├── java └── c++ ├── Non Repeating Character ├── Java └── C++ ├── Subarrays with sum K ├── c++ └── java ├── k largest elements ├── java └── c++ ├── Count Subarrays with given XOR ├── java └── c++ ├── Longest Subarray with Sum K ├── java └── c++ ├── Rotate a Linked List ├── java └── c++ ├── Kth Missing Positive Number in a Sorted Array └── c++ and java ├── Reverse a linked list ├── java └── c++ ├── Find H-Index ├── c++ └── java ├── Next Greater Element ├── java └── c++ ├── Container With Most Water └── java and c++ ├── Search in a Row-Column sorted matrix └── java and c++ ├── Lowest Common Ancestor in a BST ├── java └── c++ ├── Find the first node of loop in linked list ├── java └── c++ ├── Print Anagrams Together ├── java └── c++ ├── Exactly one swap ├── java └── c++ ├── Sorted and rotated minimum ├── java └── c++ ├── Parenthesis Checker ├── java └── c++ ├── Equilibrium Point └── java and c++ ├── K closest elements ├── java └── c++ ├── Longest valid Parentheses ├── java └── c++ ├── K-th element of two Arrays ├── c++ └── java ├── K Closest Points to Origin ├── java └── c++ ├── Largest subarray of 0's and 1's └── java and c++ ├── Trapping Rain Water ├── with extra space └── java and c++ ├── Count the number of possible triangles └── java and c++ ├── Smallest Divisor ├── java └── c++ ├── Count distinct elements in every window ├── java └── c++ ├── Indexes of Subarray Sum └── java and c++ ├── Koko Eating Bananas ├── java └── c++ ├── Sort 0s, 1s and 2s ├── Java └── C++ ├── Overlapping Intervals ├── java └── c++ ├── K Sized Subarray Maximum ├── java └── c++ ├── Group Balls by Sequence ├── java └── c++ ├── Remove loop in Linked List ├── java └── c++ ├── Permutations of a String ├── java └── c++ ├── Case-specific Sorting of Strings ├── c++ └── java ├── Insert Interval ├── java └── c++ ├── Merge K sorted linked lists ├── java └── c++ ├── Search in a row-wise sorted matrix └── java and c++ ├── Search in a sorted Matrix └── java and c++ ├── Search in Rotated Sorted Array ├── c++ └── java ├── Product array puzzle ├── java └── c++ ├── Longest substring with distinct characters └── java and c++ ├── Longest Increasing Subsequence └── java ├── Construct Tree from Inorder & Preorder ├── java └── c++ ├── Level order traversal ├── java └── c++ ├── Maximum sum of Non-adjacent nodes ├── java └── c++ ├── Longest Consecutive Subsequence ├── java └── c++ ├── Aggressive Cows ├── C++ └── java ├── Min Chars to Add for Palindrome ├── Java └── C++ ├── Sum Pair closest to target └── java and c++ ├── Count Inversions ├── java └── c++ ├── Pair Sum in BST ├── java └── c++ ├── Evaluation of Postfix Expression ├── java └── c++ ├── Merge two sorted linked lists ├── java └── c++ ├── Allocate Minimum Pages ├── java └── C++ ├── Clone List with Next and Random ├── no extra space │ ├── c++ │ └── java └── with extra space │ ├── java │ └── c++ ├── Coin Piles ├── java └── c++ ├── Get Min from Stack ├── c++ └── java ├── Pair with given sum in a sorted array └── java and c++ ├── Equalize the Towers ├── java └── c++ ├── Police and Thieves └── java ├── Find all possible palindromic partitions of a String ├── c++ └── java ├── Set Matrix Zeroes └── java ├── Word Search ├── java └── c++ ├── Decode the string ├── java └── c++ ├── LRU Cache ├── java └── c++ ├── N-Queen Problem ├── java └── c++ ├── Fixing Two nodes of a BST ├── c++ └── java ├── Find All Triplets with Zero Sum ├── java └── C++ ├── Find median in a stream ├── java └── c++ ├── Count all triplets with given sum in sorted array └── java and c++ ├── Longest Bounded-Difference Subarray ├── java └── c++ ├── Linked List Group Reverse ├── java └── c++ ├── Add Number Linked Lists ├── java └── c++ ├── Search Pattern (KMP-Algorithm) ├── Java └── C++ ├── Solve the Sudoku ├── c++ └── java ├── Tree Boundary Traversal ├── java └── c++ ├── Spirally traversing a matrix └── java and c++ └── Sum-string ├── java └── c++ /Height of Binary Tree/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int height(Node* node) { 4 | if (node == NULL) 5 | return -1; 6 | return 1 + max(height(node->left), height(node->right)); 7 | } 8 | }; -------------------------------------------------------------------------------- /Strings Rotations of Each Other/Java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | // Function to check if two strings are rotations of each other or not. 4 | public static boolean areRotations(String s1, String s2) { 5 | // Your code here 6 | s1 = s1+s1; 7 | return s1.lastIndexOf(s2)>=0; 8 | } 9 | } -------------------------------------------------------------------------------- /Height of Binary Tree/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find the height of a binary tree. 3 | int height(Node node) { 4 | // code here 5 | if(node == null){ 6 | return -1; 7 | } 8 | 9 | return Math.max(height(node.left), height(node.right))+1; 10 | } 11 | } -------------------------------------------------------------------------------- /Union of Arrays with Duplicates/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int findUnion(int a[], int b[]) { 3 | // code here 4 | Set hst = new HashSet(); 5 | for(int i: a){ 6 | hst.add(i); 7 | } 8 | for(int i: b){ 9 | hst.add(i); 10 | } 11 | return hst.size(); 12 | } 13 | } -------------------------------------------------------------------------------- /Number of occurrence/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countFreq(vector& arr, int target) { 4 | auto low = lower_bound(arr.begin(), arr.end(), target); 5 | 6 | if (low == arr.end() || *low != target) 7 | return 0; 8 | 9 | auto high = upper_bound(low, arr.end(), target); 10 | 11 | return high - low; 12 | } 13 | }; -------------------------------------------------------------------------------- /Two Sum - Pair with Given Sum/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean twoSum(int arr[], int target) { 3 | // code here 4 | Set hst = new HashSet(); 5 | for(int i: arr){ 6 | if(hst.contains(target-i)){ 7 | return true; 8 | } 9 | hst.add(i); 10 | } 11 | return false; 12 | } 13 | } -------------------------------------------------------------------------------- /Two Sum - Pair with Given Sum/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool twoSum(vector& arr, int target) { 4 | unordered_set hst; 5 | for (int i : arr) { 6 | if (hst.find(target - i) != hst.end()) { 7 | return true; 8 | } 9 | hst.insert(i); 10 | } 11 | return false; 12 | } 13 | 14 | }; -------------------------------------------------------------------------------- /Rotate by 90 degree/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to rotate matrix anticlockwise by 90 degrees. 4 | void rotateby90(vector>& mat) { 5 | // code here 6 | for(int i=0;i st = new Stack(); 5 | for(int i=0;i mp =new HashMap(); 6 | int count =0; 7 | for(int i: arr){ 8 | if(mp.containsKey(target-i)){ 9 | count+=mp.get(target-i); 10 | } 11 | mp.put(i, mp.getOrDefault(i,0)+1); 12 | } 13 | return count; 14 | } 15 | } -------------------------------------------------------------------------------- /Implement Pow/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | double power(double b, int e) { 3 | // code here 4 | if(e<0){ 5 | return 1/power(b,-e); 6 | } 7 | if(e==1){ 8 | return b; 9 | } 10 | if(e==0) 11 | return 1; 12 | double halfPow = power(b, e/2); 13 | if(e%2==0){ 14 | return halfPow*halfPow; 15 | } 16 | return b*halfPow*halfPow; 17 | } 18 | } -------------------------------------------------------------------------------- /Inorder Traversal/c++/using Recursion: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector inOrder(Node* root) { 4 | vector ans; 5 | solve(root, ans); 6 | return ans; 7 | } 8 | 9 | private: 10 | void solve(Node* root, vector& ans) { 11 | if (root == nullptr) 12 | return; 13 | solve(root->left, ans); 14 | ans.push_back(root->data); 15 | solve(root->right, ans); 16 | } 17 | }; -------------------------------------------------------------------------------- /Non-overlapping Intervals/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int minRemoval(int intervals[][]) { 3 | // code here 4 | Arrays.sort(intervals, (a,b)->a[1]-b[1]); 5 | int end = intervals[0][1], cn = 1; 6 | for(int i=1;i=end){ 8 | cn++; 9 | end=intervals[i][1]; 10 | } 11 | } 12 | return intervals.length-cn; 13 | } 14 | } -------------------------------------------------------------------------------- /Union of Arrays with Duplicates/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to return the count of number of elements in union of two arrays. 4 | int findUnion(vector& a, vector& b) { 5 | // code here 6 | unordered_set hst; 7 | for (int i : a) { 8 | hst.insert(i); 9 | } 10 | for (int i : b) { 11 | hst.insert(i); 12 | } 13 | return hst.size(); 14 | } 15 | }; -------------------------------------------------------------------------------- /Diameter of a Binary Tree/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int ans = 0; 3 | int diameter(Node* root) { 4 | // Your code here 5 | calc(root); 6 | return ans; 7 | } 8 | int calc(Node* root){ 9 | if(root==null){ 10 | return 0; 11 | } 12 | int left = calc(root->left); 13 | int right = calc(root->right); 14 | ans=max(ans, left+right); 15 | return max(left, right)+1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Symmetric Tree/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSymmetric(Node* root) { 4 | if (root == nullptr) return true; 5 | return isMirror(root->left, root->right); 6 | } 7 | 8 | bool isMirror(Node* l, Node* r) { 9 | if (l == nullptr && r == nullptr) return true; 10 | if (l == nullptr || r == nullptr || l->data != r->data) return false; 11 | return isMirror(l->left, r->right) && isMirror(l->right, r->left); 12 | } 13 | }; -------------------------------------------------------------------------------- /Intersection of Two arrays with Duplicate Elements/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersectionWithDuplicates(vector& a, vector& b) { 4 | unordered_set aSet(a.begin(), a.end()); 5 | vector res; 6 | 7 | for (int i : b) { 8 | if (aSet.find(i) != aSet.end()) { 9 | res.push_back(i); 10 | aSet.erase(i); 11 | } 12 | } 13 | 14 | return res; 15 | } 16 | }; -------------------------------------------------------------------------------- /Remove the balls/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector &color, vector &radius) { 4 | // code here 5 | stack st; 6 | for (int i = 0; i < color.size(); ++i) { 7 | if (!st.empty() && color[st.top()] == color[i] && radius[st.top()] == radius[i]) { 8 | st.pop(); 9 | } else { 10 | st.push(i); 11 | } 12 | } 13 | return st.size(); 14 | } 15 | }; -------------------------------------------------------------------------------- /Detect Loop in linked list/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to check if the linked list has a loop. 3 | public static boolean detectLoop(Node head) { 4 | // Add code here 5 | Node slow=head, fast=head; 6 | while(fast!=null && fast.next!=null){ 7 | slow = slow.next; 8 | fast = fast.next.next; 9 | if(slow == fast){ 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | } -------------------------------------------------------------------------------- /Merge Without Extra Space/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void mergeArrays(vector& a, vector& b) { 4 | int n = a.size(), m = b.size(); 5 | int i = n - 1, j = 0; 6 | 7 | while (i >= 0 && j < m) { 8 | if (a[i] > b[j]) { 9 | swap(a[i], b[j]); 10 | } 11 | i--; 12 | j++; 13 | } 14 | 15 | sort(a.begin(), a.end()); 16 | sort(b.begin(), b.end()); 17 | } 18 | }; -------------------------------------------------------------------------------- /Count Pairs whose sum is less than target/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int countPairs(int arr[], int target) { 3 | // Your code here 4 | Arrays.sort(arr); 5 | int cn=0, st=0, end=arr.length-1; 6 | while(stleft, dia); 8 | int r = go(n->right, dia); 9 | 10 | if (l + r + 1 > *dia) 11 | *dia = l + r + 1; 12 | 13 | return 1 + max(l, r); 14 | } 15 | 16 | int diameter(Node* root) { 17 | int dia = 0; 18 | go(root, &dia); 19 | return dia - 1; 20 | } 21 | }; -------------------------------------------------------------------------------- /BST with Dead End/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isDeadEnd(Node root) { 3 | // Code here. 4 | return chec(root, 0, Integer.MAX_VALUE); 5 | } 6 | static boolean chec(Node root, int min, int max){ 7 | if(root==null){ 8 | return false; 9 | } 10 | if(min+1 == root.data && max-1 == root.data){ 11 | return true; 12 | } 13 | return chec(root.left, min, root.data) || chec(root.right, root.data, max); 14 | } 15 | } -------------------------------------------------------------------------------- /Non Repeating Character/Java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find the first non-repeating character in a string. 3 | static char nonRepeatingChar(String s) { 4 | // Your code here 5 | int[] freq = new int[26]; 6 | for(char ch: s.toCharArray()){ 7 | freq[ch-'a']++; 8 | } 9 | for(char ch: s.toCharArray()){ 10 | if(freq[ch-'a']==1){ 11 | return ch; 12 | } 13 | } 14 | return '$'; 15 | } 16 | } -------------------------------------------------------------------------------- /Subarrays with sum K/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubarrays(vector &arr, int k) { 4 | // code here 5 | int ans = 0, currSum = 0; 6 | unordered_map mp; 7 | mp[0] = 1; 8 | 9 | for (int i : arr) { 10 | currSum += i; 11 | 12 | if (mp.count(currSum - k)) { 13 | ans += mp[currSum - k]; 14 | } 15 | mp[currSum]++; 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /k largest elements/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList kLargest(int[] arr, int k) { 3 | // Your code here 4 | PriorityQueue pq = new PriorityQueue<>(); 5 | for(int i: arr){ 6 | pq.add(i); 7 | if(pq.size()>k) 8 | pq.poll(); 9 | } 10 | ArrayList ans = new ArrayList(); 11 | while(!pq.isEmpty()){ 12 | ans.add(0, pq.poll()); 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /Subarrays with sum K/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSubarrays(int arr[], int k) { 3 | // code here 4 | int ans =0, currSum=0; 5 | Map mp = new HashMap(); 6 | mp.put(0, 1); 7 | for(int i: arr){ 8 | currSum+=i; 9 | if(mp.containsKey(currSum-k)){ 10 | ans+=mp.get(currSum-k); 11 | } 12 | mp.put(currSum, mp.getOrDefault(currSum, 0)+1); 13 | } 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Count Subarrays with given XOR/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long subarrayXor(int arr[], int k) { 3 | // code here 4 | long ans=0; 5 | Map mp = new HashMap(); 6 | int currXOR=0; 7 | mp.put(0,1); 8 | for(int i: arr){ 9 | currXOR=currXOR^i; 10 | if(mp.containsKey(currXOR^k)) 11 | ans+=mp.get(currXOR^k); 12 | mp.put(currXOR, mp.getOrDefault(currXOR,0)+1); 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /Longest Subarray with Sum K/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestSubarray(int[] arr, int k) { 3 | // code here 4 | int currSum=0, ans=0; 5 | Map mp = new HashMap(); 6 | mp.put(0, -1); 7 | for(int i=0;idata && max - 1 == root->data) { 14 | return true; 15 | } 16 | 17 | return check(root->left, min, root->data) || 18 | check(root->right, root->data, max); 19 | } 20 | }; -------------------------------------------------------------------------------- /Merge Without Extra Space/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to merge the arrays. 3 | public void mergeArrays(int a[], int b[]) { 4 | // code here 5 | int n = a.length, m = b.length; 6 | int i = n-1, j = 0; 7 | while(i>=0 && jb[j]){ 9 | int tmp = a[i]; 10 | a[i]=b[j]; 11 | b[j]=tmp; 12 | } 13 | i--; 14 | j++; 15 | } 16 | Arrays.sort(a); 17 | Arrays.sort(b); 18 | } 19 | } -------------------------------------------------------------------------------- /Rotate a Linked List/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public Node rotate(Node head, int k) { 3 | int len=1; 4 | Node tmp = head; 5 | while(tmp.next!=null){ 6 | len++; 7 | tmp=tmp.next; 8 | } 9 | k=k%len; 10 | if(k==0) 11 | return head; 12 | tmp.next = head; 13 | tmp=head; 14 | for(int i=1;i inOrder(Node root) { 4 | // Code 5 | ArrayList ans = new ArrayList(); 6 | solve(root, ans); 7 | return ans; 8 | } 9 | void solve(Node root, ArrayList ans) { 10 | if(root == null) 11 | return; 12 | solve(root.left, ans); 13 | ans.add(root.data); 14 | solve(root.right, ans); 15 | } 16 | } -------------------------------------------------------------------------------- /Intersection of Two arrays with Duplicate Elements/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList intersectionWithDuplicates(int[] a, int[] b) { 3 | // code here 4 | Set aSet = new HashSet(); 5 | for(int i:a){ 6 | aSet.add(i); 7 | } 8 | ArrayList res = new ArrayList(); 9 | for(int i: b){ 10 | if(aSet.contains(i)){ 11 | res.add(i); 12 | aSet.remove(i); 13 | } 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /Kth Missing Positive Number in a Sorted Array/c++ and java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthMissing(int[] arr, int k) { 3 | // code here 4 | int lo=0, hi = arr.length-1; 5 | int ans = arr.length + k; 6 | while(lo <= hi){ 7 | int mid = (lo+hi)/2; 8 | if(arr[mid] > mid + k){ 9 | hi = mid - 1; 10 | ans = mid + k; 11 | } 12 | else { 13 | lo = mid + 1; 14 | } 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Reverse a linked list/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node reverseList(Node head) { 3 | // code here 4 | Node tmpHead = null; 5 | while(head!=null){ 6 | Node nex = head.next; 7 | if(tmpHead == null) { 8 | tmpHead = head; 9 | tmpHead.next = null; 10 | } 11 | else { 12 | head.next = tmpHead; 13 | tmpHead = head; 14 | } 15 | head = nex; 16 | } 17 | return tmpHead; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Symmetric Tree/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSymmetric(Node root) { 3 | // Code here 4 | if(root == null){ 5 | return true; 6 | } 7 | return chec(root.left, root.right); 8 | } 9 | static boolean chec(Node l, Node r){ 10 | if(l==null && r == null){ 11 | return true; 12 | } 13 | if(l == null || r == null || l.data != r.data){ 14 | return false; 15 | } 16 | return chec(l.left, r.right) && chec(l.right, r.left); 17 | } 18 | } -------------------------------------------------------------------------------- /Strings Rotations of Each Other/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to check if two strings are rotations of each other or not. 4 | bool areRotations(string &s1, string &s2) { 5 | // Your code here 6 | if (s1.length() != s2.length()) { 7 | return false; 8 | } 9 | 10 | // Concatenate s1 with itself 11 | string concatenated = s1 + s1; 12 | 13 | // Check if s2 is a substring of the concatenated string 14 | return concatenated.rfind(s2) != string::npos; 15 | } 16 | }; -------------------------------------------------------------------------------- /Find H-Index/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | int len = citations.size(); 5 | vector bucket(len + 1, 0); 6 | 7 | for (int citation : citations) { 8 | bucket[min(citation, len)]++; 9 | } 10 | 11 | int count = 0; 12 | for (int hIndex = len; hIndex >= 0; hIndex--) { 13 | count += bucket[hIndex]; 14 | if (count >= hIndex) { 15 | return hIndex; 16 | } 17 | } 18 | return 0; 19 | } 20 | }; -------------------------------------------------------------------------------- /Implement Pow/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double power(double b, int e) { 4 | // Base case: any number raised to the power of 0 is 1 5 | if (e < 0) { 6 | return 1 / power(b, -e); 7 | } 8 | if (e == 1) { 9 | return b; 10 | } 11 | if (e == 0) { 12 | return 1; 13 | } 14 | 15 | double halfPow = power(b, e / 2); 16 | if (e % 2 == 0) { 17 | return halfPow * halfPow; 18 | } 19 | return b * halfPow * halfPow; 20 | } 21 | }; -------------------------------------------------------------------------------- /Detect Loop in linked list/c++: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | // Function to check if the linked list has a loop. 5 | bool detectLoop(Node* head) { 6 | if (!head) 7 | return false; 8 | 9 | Node* slow = head; 10 | Node* fast = head; 11 | 12 | while (fast && fast->next) { 13 | slow = slow->next; 14 | fast = fast->next->next; 15 | if (slow == fast) 16 | return true; 17 | } 18 | 19 | return false; 20 | } 21 | }; -------------------------------------------------------------------------------- /Find H-Index/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find hIndex 3 | public int hIndex(int[] citations) { 4 | // code here 5 | int len=citations.length; 6 | 7 | int[] bucket = new int[len+1]; 8 | 9 | for(int c: citations){ 10 | bucket[Math.min(c, len)]++; 11 | } 12 | 13 | int count=0; 14 | for(int i=len;i>=0;i--){ 15 | count+=bucket[i]; 16 | if(count >= i){ 17 | return i; 18 | } 19 | } 20 | return 0; 21 | } 22 | } -------------------------------------------------------------------------------- /Reverse a linked list/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to reverse a linked list. 4 | Node *reverseList(Node *head) { 5 | if (head == NULL) 6 | return NULL; 7 | Node *prev = NULL; 8 | Node *current = head; 9 | Node *next = current->next; 10 | 11 | while (current != NULL) { 12 | next = current->next; 13 | current->next = prev; 14 | prev = current; 15 | current = next; 16 | } 17 | 18 | return prev; 19 | } 20 | }; -------------------------------------------------------------------------------- /Next Greater Element/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find the next greater element for each element of the array. 3 | public ArrayList nextLargerElement(int[] arr) { 4 | // code here 5 | Stack st = new Stack(); 6 | ArrayList ans = new ArrayList<>(Collections.nCopies(arr.length, -1)); 7 | for(int i=0;i=0){ 8 | if(mat[i][j] == x) 9 | return true; 10 | if(mat[i][j] > x){ 11 | j--; 12 | } 13 | else 14 | i++; 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /Lowest Common Ancestor in a BST/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node LCA(Node root, Node n1, Node n2) { 3 | // code here. 4 | return solve(root, Math.min(n1.data,n2.data), Math.max(n1.data,n2.data)); 5 | } 6 | Node solve(Node root, int n1, int n2){ 7 | if(root==null) 8 | return root; 9 | if((n1root.data) || root.data == n1 || root.data == n2){ 10 | return root; 11 | } 12 | if(n2>& intervals) { 4 | sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b) { 5 | return a[1] < b[1]; 6 | }); 7 | 8 | int end = intervals[0][1]; 9 | int count = 1; 10 | for (int i = 1; i < intervals.size(); i++) { 11 | if (intervals[i][0] >= end) { 12 | count++; 13 | end = intervals[i][1]; 14 | } 15 | } 16 | 17 | return intervals.size() - count; 18 | } 19 | }; -------------------------------------------------------------------------------- /Find the first node of loop in linked list/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static Node findFirstNode(Node head) { 3 | // code here 4 | Node slow = head, fast = head; 5 | while(fast!=null && fast.next!=null){ 6 | slow = slow.next; 7 | fast = fast.next.next; 8 | if(slow == fast){ 9 | slow = head; 10 | while(slow!=fast){ 11 | slow = slow.next; 12 | fast=fast.next; 13 | } 14 | return slow; 15 | } 16 | } 17 | return null; 18 | } 19 | } -------------------------------------------------------------------------------- /Non Repeating Character/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to find the first non-repeating character in a string. 4 | char nonRepeatingChar(string &s) { 5 | int h[26] = {0}; 6 | 7 | for (int i = 0; i < s.length(); i++) { 8 | h[s[i] - 'a']++; 9 | } 10 | bool flag = false; 11 | 12 | for (int i = 0; i < s.length(); i++) { 13 | if (h[s[i] - 'a'] == 1) { 14 | flag = true; 15 | return s[i]; 16 | } 17 | } 18 | if (!flag) { 19 | return '$'; 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Print Anagrams Together/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList> anagrams(String[] arr) { 3 | // code here 4 | Map> mp = new HashMap(); 5 | 6 | for(String s: arr){ 7 | char[] ch = s.toCharArray(); 8 | Arrays.sort(ch); 9 | String sortWord = String.valueOf(ch); 10 | 11 | if(!mp.containsKey(sortWord)){ 12 | mp.put(sortWord, new ArrayList()); 13 | } 14 | mp.get(sortWord).add(s); 15 | } 16 | return new ArrayList(mp.values()); 17 | } 18 | } -------------------------------------------------------------------------------- /Exactly one swap/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int countStrings(String s) { 3 | // code here 4 | Map freq = new HashMap(); 5 | for(char ch: s.toCharArray()){ 6 | freq.put(ch, freq.getOrDefault(ch, 0)+1); 7 | } 8 | int ans = 0; 9 | int len = s.length(); 10 | boolean flag = false; 11 | for(char ch: s.toCharArray()){ 12 | if(freq.get(ch) > 1){ 13 | flag = true; 14 | } 15 | ans+=len - freq.get(ch); 16 | } 17 | ans/=2; 18 | ans+=flag ? 1 : 0; 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /Sorted and rotated minimum/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] arr) { 3 | // complete the function here 4 | int n = arr.length; 5 | if(arr[0]0&&arr[mid]arr[end]) 15 | beg=mid+1; 16 | else 17 | end=mid-1; 18 | } 19 | return arr[beg]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Sorted and rotated minimum/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& arr) { 4 | int n = arr.size(); 5 | if (arr[0] < arr[n - 1]) 6 | return arr[0]; 7 | 8 | int beg = 0, end = n - 1; 9 | while (beg <= end) { 10 | int mid = (beg + end) / 2; 11 | 12 | if (mid > 0 && arr[mid] < arr[mid - 1]) 13 | return arr[mid]; 14 | 15 | if (arr[beg] <= arr[mid] && arr[mid] > arr[end]) 16 | beg = mid + 1; 17 | else 18 | end = mid - 1; 19 | } 20 | 21 | return arr[beg]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Exactly one swap/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countStrings(string &s) { 4 | // code here 5 | unordered_map freq; 6 | for (char ch : s) { 7 | freq[ch]++; 8 | } 9 | 10 | int ans = 0; 11 | int len = s.length(); 12 | bool flag = false; 13 | 14 | for (char ch : s) { 15 | if (freq[ch] > 1) { 16 | flag = true; 17 | } 18 | ans += len - freq[ch]; 19 | } 20 | 21 | ans /= 2; 22 | if (flag) { 23 | ans += 1; 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Next Greater Element/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to find the next greater element for each element of the array. 4 | vector nextLargerElement(vector& arr) { 5 | // code here 6 | int n = arr.size(); 7 | stack st; 8 | vector ans(n, -1); // Initialize all elements as -1 9 | 10 | for (int i = 0; i < n; i++) { 11 | while (!st.empty() && arr[st.top()] < arr[i]) { 12 | ans[st.top()] = arr[i]; 13 | st.pop(); 14 | } 15 | st.push(i); 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /Parenthesis Checker/java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | static boolean isBalanced(String s) { 4 | // code here 5 | Stack st = new Stack(); 6 | for(char ch : s.toCharArray()){ 7 | if(st.isEmpty() || ch == '(' || ch == '{' || ch == '['){ 8 | st.push(ch); 9 | } 10 | else if((ch == ')' && st.peek() == '(') || 11 | (ch == ']' && st.peek() == '[') || (ch == '}' && st.peek() == '{')){ 12 | st.pop(); 13 | } 14 | else { 15 | return false; 16 | } 17 | } 18 | return st.isEmpty(); 19 | } 20 | } -------------------------------------------------------------------------------- /Lowest Common Ancestor in a BST/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* LCA(Node* root, Node* n1, Node* n2) { 4 | return solve(root, min(n1->data, n2->data), max(n1->data, n2->data)); 5 | } 6 | 7 | Node* solve(Node* root, int n1, int n2) { 8 | if (!root) return root; 9 | 10 | if ((n1 < root->data && n2 > root->data) || root->data == n1 || root->data == n2) { 11 | return root; 12 | } 13 | 14 | if (n2 < root->data) { 15 | return solve(root->left, n1, n2); 16 | } 17 | 18 | return solve(root->right, n1, n2); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Count Subarrays with given XOR/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long subarrayXor(vector &arr, int k) { 4 | // code here 5 | long ans = 0; 6 | unordered_map mp; 7 | int currXOR = 0; 8 | mp[0] = 1; 9 | 10 | for (int i : arr) { 11 | currXOR ^= i; 12 | 13 | // Check if (currXOR ^ k) exists in the map 14 | if (mp.find(currXOR ^ k) != mp.end()) { 15 | ans += mp[currXOR ^ k]; 16 | } 17 | 18 | // Update the frequency of the current XOR 19 | mp[currXOR]++; 20 | } 21 | 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Equilibrium Point/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find equilibrium point in the array. 3 | // code is almost same in java and c++ so I am not writing c++ code. Please ask if you have any doubt. 4 | public static int findEquilibrium(int arr[]) { 5 | // code here 6 | int totalSum=0; 7 | for(int i: arr){ 8 | totalSum+=i; 9 | } 10 | int currSum=0; 11 | for(int i=0;i pq = new PriorityQueue<>( 5 | (a,b)-> Math.abs(a-x)!=Math.abs(b-x) ? Math.abs(b-x) -Math.abs(a-x) : a - b); 6 | 7 | for(int i: arr){ 8 | if(i!=x){ 9 | pq.add(i); 10 | } 11 | if(pq.size()>k) 12 | pq.poll(); 13 | } 14 | int ans[] = new int[k]; 15 | int i=k-1; 16 | while(i>=0){ 17 | ans[i]=pq.poll(); 18 | i--; 19 | } 20 | return ans; 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Longest valid Parentheses/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int maxLength(String s) { 3 | // code here 4 | Stack st = new Stack(); 5 | st.push(-1); 6 | for(int i=0;i1 && s.charAt(st.peek())=='('){ 8 | st.pop(); 9 | } 10 | else { 11 | st.push(i); 12 | } 13 | } 14 | int lim = s.length(), ans=0; 15 | while(!st.isEmpty()){ 16 | int p = st.pop(); 17 | ans=Math.max(ans, lim-p-1); 18 | lim=p; 19 | } 20 | return ans; 21 | } 22 | } -------------------------------------------------------------------------------- /Count pairs with given sum/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPairs(vector &arr, int target) { 4 | // Using unordered_map instead of HashMap for O(1) average lookup 5 | unordered_map mp; 6 | int count = 0, n = arr.size(); 7 | 8 | for(int i = 0; i < n; i++) { 9 | // Check if (target - current element) exists in map 10 | if(mp.find(target - arr[i]) != mp.end()) { 11 | count += mp[target - arr[i]]; 12 | } 13 | // Increment frequency of current element 14 | mp[arr[i]]++; 15 | } 16 | 17 | return count; 18 | } 19 | }; -------------------------------------------------------------------------------- /K-th element of two Arrays/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthElement(vector& a, vector& b, int k) { 4 | // code here 5 | int i = 0, j = 0, n = a.size(), m = b.size(), ans, c = 0; 6 | 7 | while (true) { 8 | int x1 = (i < n) ? a[i] : INT_MAX; 9 | int x2 = (j < m) ? b[j] : INT_MAX; 10 | 11 | if (x1 < x2) { 12 | i++; 13 | ans = x1; 14 | } else { 15 | j++; 16 | ans = x2; 17 | } 18 | c++; 19 | if (c == k) { 20 | return ans; 21 | } 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /Longest valid Parentheses/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxLength(string& s) { 4 | // code here 5 | stack st; 6 | st.push(-1); 7 | for(int i = 0; i < s.length(); i++) { 8 | if(s[i] == ')' && st.size() > 1 && s[st.top()] == '(') { 9 | st.pop(); 10 | } else { 11 | st.push(i); 12 | } 13 | } 14 | int lim = s.length(), ans = 0; 15 | while(!st.empty()) { 16 | int p = st.top(); 17 | st.pop(); 18 | ans = max(ans, lim - p - 1); 19 | lim = p; 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /K Closest Points to Origin/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] kClosest(int[][] points, int k) { 3 | // Your code here 4 | PriorityQueue pq = new PriorityQueue<>((a,b) -> 5 | Integer.compare(distance(b), distance(a))); 6 | for(int[] pt: points){ 7 | pq.add(pt); 8 | if(pq.size()>k){ 9 | pq.poll(); 10 | } 11 | } 12 | int[][] ans = new int[k][2]; 13 | for(int i=0;i mp =new HashMap(); 6 | mp.put(0, -1); 7 | int ans=0, sum=0; 8 | for(int i=0;i &arr) { 2 | int n=arr.size(); 3 | vectorleft(n); 4 | vectorright(n); 5 | left[0]=arr[0]; 6 | right[n-1]=arr[n-1]; 7 | //fill left array 8 | for(int i=1;i=0;i--) 14 | { 15 | right[i]=max(right[i+1],arr[i]); 16 | } 17 | int water=0; 18 | for(int i=0;i kLargest(vector& arr, int k) { 4 | // Your code here 5 | priority_queue, greater> minHeap; // Min-Heap 6 | 7 | for (int num : arr) { 8 | minHeap.push(num); 9 | if (minHeap.size() > k) 10 | minHeap.pop(); // Remove the smallest element 11 | } 12 | 13 | vector ans; 14 | while (!minHeap.empty()) { 15 | ans.insert(ans.begin(), minHeap.top()); // Insert at index 0 16 | minHeap.pop(); 17 | } 18 | 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Find the first node of loop in linked list/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* findFirstNode(Node* head) { 4 | Node* slow = head; 5 | Node* fast = head; 6 | 7 | while (fast != nullptr && fast->next != nullptr) { 8 | 9 | slow = slow->next; 10 | 11 | fast = fast->next->next; 12 | 13 | if (slow == fast) { 14 | 15 | slow = head; 16 | 17 | while (slow != fast) { 18 | slow = slow->next; 19 | fast = fast->next; 20 | } 21 | 22 | return slow; 23 | } 24 | } 25 | 26 | return nullptr; 27 | } 28 | }; -------------------------------------------------------------------------------- /K-th element of two Arrays/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthElement(int a[], int b[], int k) { 3 | // code here 4 | int i =0 , j =0, n = a.length, m =b.length, ans,c =0; 5 | 6 | while(true){ 7 | int x1 = i=0;i--){ 9 | int st=0, end=i-1; 10 | while(starr[i]){ 12 | ans+=end-st; 13 | end--; 14 | } 15 | else { 16 | st++; 17 | } 18 | } 19 | } 20 | return ans; 21 | } 22 | } -------------------------------------------------------------------------------- /Rotate a Linked List/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to rotate a linked list. 4 | Node* rotate(Node* head, int k) { 5 | if (k == 0 || head == nullptr) 6 | return head; 7 | 8 | Node* curr = head; 9 | int len = 1; 10 | 11 | while (curr->next != nullptr) { 12 | curr = curr->next; 13 | len += 1; 14 | } 15 | k %= len; 16 | 17 | if (k == 0) 18 | return head; 19 | curr->next = head; 20 | curr = head; 21 | for (int i = 1; i < k; i++) 22 | curr = curr->next; 23 | 24 | head = curr->next; 25 | curr->next = nullptr; 26 | return head; 27 | } 28 | }; -------------------------------------------------------------------------------- /Smallest Divisor/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int smallestDivisor(int[] arr, int k) { 3 | // Code here 4 | int lo = 1, hi = Arrays.stream(arr).max().getAsInt(), ans=0; 5 | while(lo<=hi){ 6 | int mid = (lo+hi)/2; 7 | if(chec(arr, mid, k)){ 8 | ans=mid; 9 | hi=mid-1; 10 | } 11 | else { 12 | lo=mid+1; 13 | } 14 | } 15 | return ans; 16 | } 17 | static boolean chec(int[] arr, int possibleAns, int k){ 18 | int sum=0; 19 | for(int i: arr){ 20 | sum+=i%possibleAns == 0?i/possibleAns : i/possibleAns +1; 21 | } 22 | return sum<=k; 23 | } 24 | } -------------------------------------------------------------------------------- /Count distinct elements in every window/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList countDistinct(int arr[], int k) { 3 | // code here 4 | ArrayList ans = new ArrayList(); 5 | Map mp = new HashMap(); 6 | k--; 7 | for(int i=0;i subarraySum(int[] arr, int target) { 3 | // code here 4 | int currSum=0; 5 | Map mp = new HashMap(); 6 | ArrayList ans = new ArrayList(); 7 | mp.put(0, -1); 8 | for(int i=0;i k){ 15 | lo=bananaPerHour+1; 16 | } 17 | else { 18 | ans=bananaPerHour; 19 | hi=bananaPerHour-1; 20 | } 21 | } 22 | return ans; 23 | } 24 | } -------------------------------------------------------------------------------- /Sort 0s, 1s and 2s/Java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to sort an array of 0s, 1s, and 2s 3 | public void sort012(int[] arr) { 4 | // code here 5 | int beg=0, end=arr.length-1, i=0; 6 | while(i<=end){ 7 | if(arr[i]==0){ 8 | swap(arr,i, beg); 9 | beg++; 10 | i++; 11 | } 12 | else if(arr[i]==2){ 13 | swap(arr, i, end); 14 | end--; 15 | } 16 | else { 17 | i++; 18 | } 19 | } 20 | } 21 | static void swap(int[] arr, int i, int j){ 22 | int tmp=arr[i]; 23 | arr[i]=arr[j]; 24 | arr[j]=tmp; 25 | } 26 | } -------------------------------------------------------------------------------- /Overlapping Intervals/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List mergeOverlap(int[][] arr) { 3 | // Code here // Code here 4 | List ans = new ArrayList(); 5 | Arrays.sort(arr, (a,b)->a[0]-b[0]); 6 | int str = arr[0][0], end = arr[0][1]; 7 | for(int i=1;i> anagrams(vector& arr) { 4 | // Map to group anagrams 5 | unordered_map> mp; 6 | 7 | for (string& s : arr) { 8 | string sortedWord = s; 9 | sort(sortedWord.begin(), sortedWord.end()); 10 | 11 | if (!mp.count(sortedWord)) { 12 | mp[sortedWord] = vector(); 13 | } 14 | mp[sortedWord].push_back(s); 15 | } 16 | 17 | vector> result; 18 | for (auto& entry : mp) { 19 | result.push_back(entry.second); 20 | } 21 | 22 | return result; 23 | } 24 | }; -------------------------------------------------------------------------------- /Smallest Divisor/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestDivisor(vector& arr, int k) { 4 | int lo = 1, hi = *max_element(arr.begin(), arr.end()), ans = 0; 5 | 6 | while (lo <= hi) { 7 | int mid = (lo + hi) / 2; 8 | if (chec(arr, mid, k)) { 9 | ans = mid; 10 | hi = mid - 1; 11 | } else { 12 | lo = mid + 1; 13 | } 14 | } 15 | return ans; 16 | } 17 | 18 | bool chec(vector& arr, int possibleAns, int k) { 19 | int sum = 0; 20 | for (int i : arr) { 21 | sum += (i + possibleAns - 1) / possibleAns; // ceil(i / possibleAns) 22 | } 23 | return sum <= k; 24 | } 25 | }; -------------------------------------------------------------------------------- /K Sized Subarray Maximum/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList maxOfSubarrays(int arr[], int k) { 3 | // code here 4 | int n=arr.length; 5 | ArrayList ans = new ArrayList(); 6 | Deque deque = new LinkedList(); 7 | 8 | for(int i=0;i=k-1){ 17 | ans.add(arr[deque.peekFirst()]); 18 | } 19 | } 20 | return ans; 21 | } 22 | } -------------------------------------------------------------------------------- /Trapping Rain Water/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWater(int arr[]) { 3 | // code here 4 | int ans=0, lmax=0, rmax=0, i=0, j=arr.length-1; 5 | while(i map = new TreeMap<>(); 6 | for (int val : arr) map.put(val, map.getOrDefault(val, 0) + 1); 7 | 8 | for (var p : map.entrySet()) { 9 | int val = p.getKey(), freq = p.getValue(); 10 | if (freq == 0) continue; 11 | for (int i = 1; i < k; i++) { 12 | int v = val + i; 13 | int f = map.getOrDefault(v, 0); 14 | if (f < freq) { 15 | return false; 16 | } 17 | 18 | map.put(v, f - freq); 19 | } 20 | } 21 | 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /Rotate by 90 degree/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to rotate matrix anticlockwise by 90 degrees. 3 | static void rotateby90(int mat[][]) { 4 | // code here 5 | int n = mat.length; 6 | for(int i=0;i& arr) { 4 | int beg = 0, end = arr.size() - 1, i = 0; 5 | 6 | while (i <= end) { 7 | if (arr[i] == 0) { 8 | swap(arr, i, beg); 9 | beg++; 10 | i++; 11 | } else if (arr[i] == 2) { 12 | swap(arr, i, end); 13 | end--; 14 | } else { 15 | i++; 16 | } 17 | } 18 | } 19 | 20 | private: 21 | // Utility function to swap two elements in the array 22 | void swap(vector& arr, int i, int j) { 23 | int temp = arr[i]; 24 | arr[i] = arr[j]; 25 | arr[j] = temp; 26 | } 27 | }; -------------------------------------------------------------------------------- /Remove loop in Linked List/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to remove a loop in the linked list. 3 | public static void removeLoop(Node head) { 4 | // code here 5 | Node slow=head, fast = head, prev = head; 6 | while(fast!=null && fast.next!=null){ 7 | slow = slow.next; 8 | prev = fast; 9 | fast = fast.next.next; 10 | if(slow == fast){ 11 | slow = head; 12 | prev = prev.next; 13 | while(slow!=fast){ 14 | slow = slow.next; 15 | fast=fast.next; 16 | prev = prev.next; 17 | } 18 | prev.next = null; 19 | return; 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Inorder Traversal/java/using Stack: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to return a list containing the inorder traversal of the tree. 3 | ArrayList inOrder(Node root) { 4 | // Code 5 | ArrayList ans = new ArrayList(); 6 | Stack st = new Stack(); 7 | while(root!=null){ 8 | st.push(root); 9 | root=root.left; 10 | } 11 | while(!st.isEmpty()){ 12 | Node tmp = st.pop(); 13 | ans.add(tmp.data); 14 | if(tmp.right!=null){ 15 | tmp = tmp.right; 16 | while(tmp!=null){ 17 | st.push(tmp); 18 | tmp = tmp.left; 19 | } 20 | } 21 | } 22 | return ans; 23 | } 24 | } -------------------------------------------------------------------------------- /Koko Eating Bananas/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kokoEat(vector& arr, int k) { 4 | // Code here 5 | int lo = 1, hi = 0, ans = 0; 6 | 7 | for (int i : arr) { 8 | hi = max(hi, i); 9 | } 10 | 11 | while (lo <= hi) { 12 | int bananaPerHour = (lo + hi) / 2; 13 | int totHr = 0; 14 | 15 | for (int i : arr) { 16 | totHr += (i + bananaPerHour - 1) / bananaPerHour; // Ceiling division 17 | } 18 | 19 | if (totHr > k) { 20 | lo = bananaPerHour + 1; 21 | } else { 22 | ans = bananaPerHour; 23 | hi = bananaPerHour - 1; 24 | } 25 | } 26 | 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /Permutations of a String/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public ArrayList findPermutation(String s) { 4 | // Code here 5 | Set ans = new HashSet(); 6 | boolean[] visit = new boolean[s.length()]; 7 | makePermutation(s, ans, "", visit); 8 | return new ArrayList(ans); 9 | } 10 | static void makePermutation(String s, Set ans, String curr, boolean[] visit){ 11 | if(curr.length() == s.length()){ 12 | ans.add(curr); 13 | return; 14 | } 15 | for(int i=0;i findPermutation(string &s) { 4 | set ans; 5 | vector visit(s.length(), false); 6 | makePermutation(s, ans, "", visit); 7 | return vector(ans.begin(), ans.end()); 8 | } 9 | 10 | private: 11 | void makePermutation(const string &s, set &ans, string curr, vector &visit) { 12 | if (curr.length() == s.length()) { 13 | ans.insert(curr); 14 | return; 15 | } 16 | for (int i = 0; i < s.length(); i++) { 17 | if (!visit[i]) { 18 | visit[i] = true; 19 | makePermutation(s, ans, curr + s[i], visit); 20 | visit[i] = false; 21 | } 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /Case-specific Sorting of Strings/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string caseSort(string& s) { 4 | // code here 5 | vector lower, upper; 6 | 7 | // Separate characters by case 8 | for (char ch : s) { 9 | if (islower(ch)) 10 | lower.push_back(ch); 11 | else 12 | upper.push_back(ch); 13 | } 14 | 15 | sort(lower.begin(), lower.end()); 16 | sort(upper.begin(), upper.end()); 17 | 18 | string ans = ""; 19 | int lIndex = 0, uIndex = 0; 20 | 21 | for (char ch : s) { 22 | if (islower(ch)) 23 | ans += lower[lIndex++]; 24 | else 25 | ans += upper[uIndex++]; 26 | } 27 | 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Insert Interval/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static ArrayList insertInterval(int[][] intervals, int[] newInterval) { 3 | // code here 4 | ArrayList ans = new ArrayList(); 5 | int i=0, len = intervals.length; 6 | while(i arr) { 4 | // Add your code here. 5 | PriorityQueue pq = new PriorityQueue<>((a,b)->a.data-b.data); 6 | for(Node n: arr){ 7 | pq.add(n); 8 | } 9 | Node newHead=null, tail=null; 10 | while(!pq.isEmpty()){ 11 | Node tmp = pq.poll(); 12 | if(newHead == null){ 13 | newHead = tmp; 14 | tail=tmp; 15 | } 16 | else { 17 | tail.next = tmp; 18 | tail = tmp; 19 | } 20 | if(tmp.next!=null){ 21 | pq.add(tmp.next); 22 | } 23 | } 24 | return newHead; 25 | } 26 | } -------------------------------------------------------------------------------- /Search in a row-wise sorted matrix/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to search a given number in row-column sorted matrix. 3 | // java and c++ code is almost same so I am not writing c++ code. Please ask if you have any doubt. 4 | public boolean searchRowMatrix(int[][] mat, int x) { 5 | // code here 6 | for(int i =0;i< mat.length;i++){ 7 | int lo = 0, hi = mat[0].length-1; 8 | while(lo<=hi){ 9 | int mid = (lo+hi)/2; 10 | if(mat[i][mid] == x) 11 | return true; 12 | if(mat[i][mid] < x){ 13 | lo = mid +1; 14 | } 15 | else { 16 | hi = mid-1; 17 | } 18 | } 19 | } 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /Inorder Traversal/c++/using Stack: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector inOrder(Node* root) { 4 | vector ans; 5 | stack st; 6 | 7 | while (root != nullptr) { 8 | st.push(root); 9 | root = root->left; 10 | } 11 | 12 | while (!st.empty()) { 13 | Node* tmp = st.top(); 14 | st.pop(); 15 | ans.push_back(tmp->data); 16 | 17 | if (tmp->right != nullptr) { 18 | tmp = tmp->right; 19 | while (tmp != nullptr) { 20 | st.push(tmp); 21 | tmp = tmp->left; 22 | } 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Overlapping Intervals/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> mergeOverlap(vector>& arr) { 4 | vector> ans; 5 | 6 | // Sort intervals based on the start time 7 | sort(arr.begin(), arr.end(), [](const vector& a, const vector& b) { 8 | return a[0] < b[0]; 9 | }); 10 | 11 | int start = arr[0][0], end = arr[0][1]; 12 | 13 | for (int i = 1; i < arr.size(); i++) { 14 | if (arr[i][0] <= end) { 15 | end = max(end, arr[i][1]); 16 | } else { 17 | ans.push_back({start, end}); 18 | start = arr[i][0]; 19 | end = arr[i][1]; 20 | } 21 | } 22 | 23 | ans.push_back({start, end}); 24 | 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Search in a sorted Matrix/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to search a given number in row-column sorted matrix. 3 | public boolean searchMatrix(int[][] mat, int x) { 4 | // code here 5 | // code for java and c++ is almost same so I am not writing c++ code. Please ask if you have any doubt. 6 | int n = mat.length; 7 | int m = mat[0].length; 8 | int beg = 0, end = n*m -1; 9 | while(beg <= end){ 10 | int mid = (beg + end)/2; 11 | int rNo = mid/m; 12 | int cNo = mid%m; 13 | if(mat[rNo][cNo] == x) 14 | return true; 15 | if(mat[rNo][cNo] < x) { 16 | beg = mid +1; 17 | } 18 | else 19 | end = mid-1; 20 | } 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /Search in Rotated Sorted Array/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& arr, int key) { 4 | int beg = 0, end = arr.size() - 1; 5 | while (beg <= end) { 6 | int mid = (beg + end) / 2; 7 | if (arr[mid] == key) { 8 | return mid; 9 | } 10 | if (arr[beg] <= arr[mid]) { 11 | if (arr[beg] <= key && key < arr[mid]) { 12 | end = mid - 1; 13 | } else { 14 | beg = mid + 1; 15 | } 16 | } else { 17 | if (arr[mid] < key && key <= arr[end]) { 18 | beg = mid + 1; 19 | } else { 20 | end = mid - 1; 21 | } 22 | } 23 | } 24 | return -1; 25 | } 26 | }; -------------------------------------------------------------------------------- /Product array puzzle/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int[] productExceptSelf(int arr[]) { 3 | // code here 4 | int n = arr.length, totalProd = 1, zeroCnt = 0; 5 | int[] res = new int[n]; 6 | for(int i: arr){ 7 | if(i==0){ 8 | zeroCnt++; 9 | } 10 | else{ 11 | totalProd*=i; 12 | } 13 | } 14 | if(zeroCnt > 1){ 15 | return res; 16 | } 17 | if(zeroCnt == 1){ 18 | for(int i=0;i countDistinct(vector &arr, int k) { 4 | // code here. 5 | vector ans; 6 | unordered_map mp; 7 | k--; // Adjust k for zero-based indexing 8 | int n = arr.size(); 9 | for (int i = 0; i < n; i++) { 10 | mp[arr[i]]++; 11 | 12 | if (i < k) { 13 | continue; 14 | } 15 | 16 | ans.push_back(mp.size()); 17 | 18 | // Handle the element sliding out of the window 19 | if (mp[arr[i - k]] == 1) { 20 | mp.erase(arr[i - k]); 21 | } else { 22 | mp[arr[i - k]]--; 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Longest substring with distinct characters/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // code in java and c++ is almost same so I am not writing c++ code. Please ask if you have any doubt. 3 | public int longestUniqueSubstr(String s) { 4 | // code here 5 | int[] freq = new int[26]; 6 | int i=0, j=0, ans=0; 7 | while(j0){ 10 | ans=Math.max(ans, j-i); 11 | while(iinorder.length || str> end){ 10 | return null; 11 | } 12 | Node root = new Node(preorder[pos]); 13 | int div = 0; 14 | for(int i=str;i<=end;i++){ 15 | if(preorder[pos] == inorder[i]){ 16 | div = i; 17 | break; 18 | } 19 | } 20 | pos++; 21 | root.left = solve(inorder, preorder, str, div-1); 22 | root.right = solve(inorder, preorder, div+1, end); 23 | return root; 24 | } 25 | } -------------------------------------------------------------------------------- /Level order traversal/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList> levelOrder(Node root) { 3 | // Your code here 4 | ArrayList> ans = new ArrayList(); 5 | Queue q = new LinkedList(); 6 | q.add(root); 7 | while(!q.isEmpty()){ 8 | int size = q.size(); 9 | ArrayList level = new ArrayList(); 10 | while(size-->0){ 11 | Node tmp = q.poll(); 12 | level.add(tmp.data); 13 | if(tmp.left!=null){ 14 | q.add(tmp.left); 15 | } 16 | if(tmp.right!=null){ 17 | q.add(tmp.right); 18 | } 19 | 20 | } 21 | ans.add(level); 22 | } 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /Case-specific Sorting of Strings/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static String caseSort(String s) { 3 | // code here 4 | ArrayList lower = new ArrayList(); 5 | ArrayList upper = new ArrayList(); 6 | for(char ch: s.toCharArray()){ 7 | if(Character.isLowerCase(ch)) 8 | lower.add(ch); 9 | else 10 | upper.add(ch); 11 | } 12 | Collections.sort(lower); 13 | Collections.sort(upper); 14 | StringBuilder ans = new StringBuilder(); 15 | int lIndex =0 , uIndex = 0; 16 | for(char ch: s.toCharArray()){ 17 | if(Character.isLowerCase(ch)) 18 | ans.append(lower.get(lIndex++)); 19 | else 20 | ans.append(upper.get(uIndex++)); 21 | } 22 | return ans.toString(); 23 | } 24 | } -------------------------------------------------------------------------------- /Search in Rotated Sorted Array/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int search(int[] arr, int key) { 3 | // Complete this function 4 | int beg = 0, end = arr.length-1; 5 | while(beg<=end){ 6 | int mid = (beg+end)/2; 7 | if(arr[mid]==key){ 8 | return mid; 9 | } 10 | if(arr[beg]<=arr[mid]){ 11 | if(arr[beg]<=key && key< arr[mid]){ 12 | end=mid-1; 13 | } 14 | else{ 15 | beg=mid+1; 16 | } 17 | } 18 | else { 19 | if(arr[mid]> levelOrder(Node *root) { 4 | // Your code here 5 | vector> ans; 6 | if (!root) return ans; 7 | 8 | queue q; 9 | q.push(root); 10 | 11 | while (!q.empty()) { 12 | int size = q.size(); 13 | vector level; 14 | 15 | while (size-- > 0) { 16 | Node* tmp = q.front(); 17 | q.pop(); 18 | level.push_back(tmp->data); 19 | 20 | if (tmp->left) { 21 | q.push(tmp->left); 22 | } 23 | if (tmp->right) { 24 | q.push(tmp->right); 25 | } 26 | } 27 | ans.push_back(level); 28 | } 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /Maximum sum of Non-adjacent nodes/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to return the maximum sum of non-adjacent nodes. 3 | public int getMaxSum(Node root) { 4 | // code here 5 | Map mp = new HashMap(); 6 | return getMax(root, mp); 7 | } 8 | static int getMax(Node root, Map mp){ 9 | if(root == null) { 10 | return 0; 11 | } 12 | if(mp.containsKey(root)){ 13 | return mp.get(root); 14 | } 15 | int sum = root.data; 16 | if(root.left!=null){ 17 | sum+=getMax(root.left.left, mp)+getMax(root.left.right, mp); 18 | } 19 | if(root.right!=null){ 20 | sum+=getMax(root.right.left, mp)+getMax(root.right.right, mp); 21 | } 22 | mp.put(root, Math.max(sum, getMax(root.left, mp) + getMax(root.right, mp))); 23 | return mp.get(root); 24 | } 25 | } -------------------------------------------------------------------------------- /K Sized Subarray Maximum/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxOfSubarrays(vector& arr, int k) { 4 | // code here 5 | int n = arr.size(); 6 | vector res; 7 | deque dq; // Deque to store indices 8 | 9 | for (int i = 0; i < n; i++) { 10 | // Remove elements that are out of this window 11 | if (!dq.empty() && dq.front() == i - k) 12 | dq.pop_front(); 13 | 14 | // Remove elements smaller than current one 15 | while (!dq.empty() && arr[dq.back()] <= arr[i]) 16 | dq.pop_back(); 17 | 18 | // Add current index to deque 19 | dq.push_back(i); 20 | 21 | // Store result after the first window is filled 22 | if (i >= k - 1) 23 | res.push_back(arr[dq.front()]); 24 | } 25 | 26 | return res; 27 | 28 | } 29 | }; -------------------------------------------------------------------------------- /Longest Consecutive Subsequence/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Function to return length of longest subsequence of consecutive integers. 4 | public int longestConsecutive(int[] arr) { 5 | // code here 6 | Set hst = new HashSet(); 7 | for(int i: arr){ 8 | hst.add(i); 9 | } 10 | int ans = 0; 11 | for(int i: arr){ 12 | int curr=0, tmp=i, tmp2=i-1; 13 | if(hst.contains(i)){ 14 | while(hst.contains(tmp)){ 15 | curr++; 16 | hst.remove(tmp); 17 | tmp++; 18 | } 19 | while(hst.contains(tmp2)){ 20 | curr++; 21 | hst.remove(tmp2); 22 | tmp2--; 23 | } 24 | } 25 | ans=Math.max(ans, curr); 26 | } 27 | return ans; 28 | } 29 | } -------------------------------------------------------------------------------- /Longest Consecutive Subsequence/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | // Function to return length of longest subsequence of consecutive integers. 5 | int longestConsecutive(vector& arr) { 6 | // Using an unordered set to store unique elements 7 | unordered_set hst(arr.begin(), arr.end()); 8 | 9 | int ans = 0; 10 | for (int i : arr) { 11 | int curr = 0, tmp = i, tmp2 = i - 1; 12 | 13 | if (hst.count(i)) { 14 | while (hst.count(tmp)) { 15 | curr++; 16 | hst.erase(tmp); 17 | tmp++; 18 | } 19 | while (hst.count(tmp2)) { 20 | curr++; 21 | hst.erase(tmp2); 22 | tmp2--; 23 | } 24 | } 25 | ans = max(ans, curr); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /Aggressive Cows/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool isPossible(int mid, int k, vector& stalls) { 5 | int count = 1, lastCow = stalls[0]; 6 | for (int i = 1; i < stalls.size(); i++) { 7 | if (stalls[i] - lastCow >= mid) { 8 | count++; 9 | lastCow = stalls[i]; 10 | if (count >= k) { 11 | return true; 12 | } 13 | } 14 | } 15 | return false; 16 | } 17 | 18 | int aggressiveCows(vector& stalls, int k) { 19 | sort(stalls.begin(), stalls.end()); 20 | int n = stalls.size(); 21 | int low = 0, high = stalls[n - 1] - stalls[0], ans = 0; 22 | 23 | while (low <= high) { 24 | int mid = (low + high) / 2; 25 | if (isPossible(mid, k, stalls)) { 26 | ans = mid; 27 | low = mid + 1; 28 | } else { 29 | high = mid - 1; 30 | } 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Min Chars to Add for Palindrome/Java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int minChar(String s) { 3 | //Write your code here 4 | String rev = new StringBuilder(s).reverse().toString(); 5 | String newString = s+"$"+rev; 6 | int len = lps(newString); 7 | return s.length()-len; 8 | } 9 | static int lps(String s){ 10 | int[] lps = new int[s.length()]; 11 | int size = s.length(), len=0, i=1; 12 | while(i sumClosest(int[] arr, int target) { 4 | // code here 5 | Arrays.sort(arr); 6 | List ans = new ArrayList(); 7 | int st=0, end=arr.length-1, currClose=Integer.MAX_VALUE; 8 | while(sttarget){ 20 | end--; 21 | } 22 | else { 23 | return ans; 24 | } 25 | } 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /Count Inversions/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to count inversions in the array. 3 | static int inversionCount(int arr[]) { 4 | // Your Code Here 5 | return mergeSort(arr, 0, arr.length-1); 6 | } 7 | static int mergeSort(int[] arr, int le, int ri){ 8 | if(le >= ri){ 9 | return 0; 10 | } 11 | int mid = (le+ri)/2; 12 | int leftInversion = mergeSort(arr, le, mid); 13 | int rightInversion = mergeSort(arr, mid+1, ri); 14 | int m = merge(arr, le, mid, ri); 15 | return leftInversion + rightInversion + m; 16 | } 17 | static int merge(int[] arr, int le, int mid, int ri){ 18 | int j = mid+1; 19 | int cn = 0; 20 | for(int i=le;i<=mid;i++){ 21 | while(j<=ri&&arr[i]>arr[j]){ 22 | j++; 23 | } 24 | cn+= j - (mid+1); 25 | } 26 | Arrays.sort(arr, le, ri+1); 27 | return cn; 28 | } 29 | } -------------------------------------------------------------------------------- /K closest elements/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector printKClosest(vector arr, int k, int x) { 4 | // Code here 5 | auto comp = [x](int a, int b) { 6 | int diffA = abs(a - x); 7 | int diffB = abs(b - x); 8 | if (diffA != diffB) 9 | return diffA < diffB; // max-heap based on distance 10 | return a > b; // if same distance, prefer smaller value later 11 | }; 12 | 13 | priority_queue, decltype(comp)> pq(comp); 14 | 15 | for (int i : arr) { 16 | if (i != x) { 17 | pq.push(i); 18 | } 19 | if (pq.size() > k) { 20 | pq.pop(); 21 | } 22 | } 23 | 24 | vector ans(k); 25 | for (int i = k - 1; i >= 0; --i) { 26 | ans[i] = pq.top(); 27 | pq.pop(); 28 | } 29 | 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Pair Sum in BST/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean findTarget(Node root, int target) { 3 | // Write your code here 4 | if(root == null){ 5 | return false; 6 | } 7 | return solve(root, root, target); 8 | } 9 | boolean solve(Node root, Node curr, int target){ 10 | if(curr == null){ 11 | return false; 12 | } 13 | if(findNode(root, target-curr.data, curr)){ 14 | return true; 15 | } 16 | return solve(root, curr.left, target) || solve(root, curr.right, target); 17 | } 18 | boolean findNode(Node root, int target, Node curr){ 19 | if(root==null){ 20 | return false; 21 | } 22 | if(root.data == target && root != curr) { 23 | return true; 24 | } 25 | if(root.data > target){ 26 | return findNode(root.left, target, curr); 27 | } 28 | return findNode(root.right, target, curr); 29 | } 30 | } -------------------------------------------------------------------------------- /Maximum sum of Non-adjacent nodes/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to return the maximum sum of non-adjacent nodes. 4 | int getMaxSum(Node* root) { 5 | unordered_map mp; 6 | return getMax(root, mp); 7 | } 8 | 9 | private: 10 | int getMax(Node* root, unordered_map& mp) { 11 | if (root == nullptr) { 12 | return 0; 13 | } 14 | if (mp.find(root) != mp.end()) { 15 | return mp[root]; 16 | } 17 | 18 | int sum = root->data; 19 | 20 | if (root->left != nullptr) { 21 | sum += getMax(root->left->left, mp) + getMax(root->left->right, mp); 22 | } 23 | if (root->right != nullptr) { 24 | sum += getMax(root->right->left, mp) + getMax(root->right->right, mp); 25 | } 26 | 27 | mp[root] = max(sum, getMax(root->left, mp) + getMax(root->right, mp)); 28 | return mp[root]; 29 | } 30 | }; -------------------------------------------------------------------------------- /Evaluation of Postfix Expression/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int evaluate(String[] arr) { 3 | // code here 4 | Stack stack = new Stack(); 5 | for(String ch: arr){ 6 | if(isOperator(ch)){ 7 | int b = stack.pop(); 8 | int a = stack.pop(); 9 | int res = apply(a, b, ch); 10 | stack.push(res); 11 | } 12 | else { 13 | stack.push(Integer.parseInt(ch)); 14 | } 15 | } 16 | return stack.pop(); 17 | } 18 | boolean isOperator(String s){ 19 | return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/"); 20 | } 21 | int apply(int a, int b, String operator){ 22 | switch(operator){ 23 | case "+": return a+b; 24 | case "-": return a-b; 25 | case "*": return a*b; 26 | case "/": return a/b; 27 | default: return a; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Merge two sorted linked lists/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node sortedMerge(Node head1, Node head2) { 3 | // code here 4 | Node newHead = null, tmp = null; 5 | while(head1!=null || head2!=null){ 6 | if(head1!=null && (head2 == null || head1.dataarr.length) 5 | return -1; 6 | int beg = 0, end = 0; 7 | 8 | for(int i: arr){ 9 | beg = Math.max(beg, i); 10 | end+=i; 11 | } 12 | int ans = beg; 13 | 14 | while(beg<=end){ 15 | int mid = (beg+end)/2; 16 | if(isPossible(arr, k, mid)){ 17 | ans=mid; 18 | end = mid-1; 19 | } 20 | else 21 | beg = mid+1; 22 | } 23 | return ans; 24 | } 25 | static boolean isPossible(int[] arr, int k, int maxPages){ 26 | int tot = 1, sum = 0; 27 | for(int i: arr){ 28 | sum+=i; 29 | if(sum > maxPages){ 30 | tot++; 31 | sum = i; 32 | } 33 | } 34 | return tot <= k; 35 | } 36 | } -------------------------------------------------------------------------------- /Number of occurrence/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int countFreq(int[] arr, int target) { 3 | // code here 4 | int lo = 0, hi = arr.length-1, st = -1, end = -1; 5 | while(lo<=hi){ 6 | int mid = (lo + hi)/2; 7 | if(arr[mid] >= target){ 8 | st = mid; 9 | hi=mid-1; 10 | } 11 | else { 12 | lo = mid+1; 13 | } 14 | } 15 | if(st == -1 || arr[st] != target) 16 | return 0; 17 | // System.out.println(st); 18 | lo = 0; 19 | hi = arr.length-1; 20 | while(lo<=hi){ 21 | int mid = (lo + hi)/2; 22 | if(arr[mid] <= target){ 23 | end = mid; 24 | lo=mid+1; 25 | } 26 | else { 27 | hi = mid-1; 28 | } 29 | } 30 | if(end == -1 || arr[st] != target) 31 | return 0; 32 | return end - st +1; 33 | } 34 | } -------------------------------------------------------------------------------- /Aggressive Cows/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int aggressiveCows(int[] stalls, int k) { 3 | // code here 4 | Arrays.sort(stalls); 5 | int n = stalls.length; 6 | int low = 0, high = stalls[n-1]-stalls[0], ans =0; 7 | while(low<=high){ 8 | int mid = (low+high)/2; 9 | if(isPossible(mid, k, stalls)){ 10 | ans = mid; 11 | low = mid+1; 12 | } 13 | else { 14 | high = mid-1; 15 | } 16 | } 17 | return ans; 18 | } 19 | static boolean isPossible(int mid, int k, int[] stalls){ 20 | int count = 1, lastCow = stalls[0]; 21 | for(int i=1;i< stalls.length;i++){ 22 | if(stalls[i]-lastCow>=mid){ 23 | count++; 24 | lastCow = stalls[i]; 25 | if(count >= k){ 26 | return true; 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /Pair Sum in BST/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool findTarget(Node* root, int target) { 4 | if (root == nullptr) { 5 | return false; 6 | } 7 | return solve(root, root, target); 8 | } 9 | 10 | private: 11 | bool solve(Node* root, Node* curr, int target) { 12 | if (curr == nullptr) { 13 | return false; 14 | } 15 | if (findNode(root, target - curr->data, curr)) { 16 | return true; 17 | } 18 | return solve(root, curr->left, target) || solve(root, curr->right, target); 19 | } 20 | 21 | bool findNode(Node* root, int target, Node* curr) { 22 | if (root == nullptr) { 23 | return false; 24 | } 25 | if (root->data == target && root != curr) { 26 | return true; 27 | } 28 | if (root->data > target) { 29 | return findNode(root->left, target, curr); 30 | } 31 | return findNode(root->right, target, curr); 32 | } 33 | }; -------------------------------------------------------------------------------- /Evaluation of Postfix Expression/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evaluate(vector& arr) { 4 | // code here 5 | stack st; 6 | 7 | for (string ch : arr) { 8 | if (isOperator(ch)) { 9 | int b = st.top(); st.pop(); 10 | int a = st.top(); st.pop(); 11 | int res = apply(a, b, ch); 12 | st.push(res); 13 | } else { 14 | st.push(stoi(ch)); // Convert string to integer 15 | } 16 | } 17 | 18 | return st.top(); 19 | } 20 | 21 | private: 22 | bool isOperator(const string& s) { 23 | return s == "+" || s == "-" || s == "*" || s == "/"; 24 | } 25 | 26 | int apply(int a, int b, const string& op) { 27 | if (op == "+") return a + b; 28 | if (op == "-") return a - b; 29 | if (op == "*") return a * b; 30 | if (op == "/") return a / b; // Integer division rounds toward zero 31 | return 0; 32 | } 33 | }; -------------------------------------------------------------------------------- /Product array puzzle/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& arr) { 4 | int n = arr.size(); 5 | vector res(n); 6 | 7 | int product = 1; 8 | int zeroCount = 0; 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (arr[i] == 0) { 12 | zeroCount++; 13 | } else { 14 | product *= arr[i]; 15 | } 16 | } 17 | 18 | if (zeroCount > 1) { 19 | return vector(n, 0); // All zeros 20 | } 21 | 22 | 23 | if (zeroCount == 1) { 24 | for (int i = 0; i < n; i++) { 25 | if (arr[i] == 0) { 26 | res[i] = product; 27 | } else { 28 | res[i] = 0; 29 | } 30 | } 31 | return res; 32 | } 33 | 34 | for (int i = 0; i < n; i++) { 35 | res[i] = product / arr[i]; 36 | } 37 | 38 | return res; 39 | } 40 | }; -------------------------------------------------------------------------------- /Clone List with Next and Random/no extra space/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node *cloneLinkedList(Node *head) { 4 | if (head == NULL) 5 | return head; 6 | 7 | Node *t = head; 8 | while (t != NULL) { 9 | Node *n = new Node(t->data); 10 | n->next = t->next; 11 | t->next = n; 12 | t = n->next; 13 | } 14 | 15 | t = head; 16 | Node *head2 = head->next; 17 | while (t != NULL) { 18 | if (t->random == NULL) 19 | t->next->random = NULL; 20 | else 21 | t->next->random = t->random->next; 22 | 23 | t = t->next->next; 24 | } 25 | 26 | t = head; 27 | Node *res = head->next; 28 | while (t != NULL) { 29 | Node *temp = t->next; 30 | t->next = temp->next; 31 | if (temp->next) 32 | temp->next = temp->next->next; 33 | t = t->next; 34 | } 35 | return head2; 36 | } 37 | }; -------------------------------------------------------------------------------- /Coin Piles/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumCoins(int[] arr, int k) { 3 | // code here 4 | Arrays.sort(arr); 5 | int n = arr.length; 6 | int[] prefix = new int[n+1]; 7 | for(int i=0;i> kClosest(vector>& points, int k){ 4 | auto compare = [](vector& a, vector& b) { 5 | return distance(a) < distance(b); // Max heap based on distance 6 | }; 7 | priority_queue, vector>, decltype(compare)> pq(compare); 8 | 9 | for (auto& pt : points) { 10 | pq.push(pt); 11 | if (pq.size() > k) { 12 | pq.pop(); // Remove the farthest point 13 | } 14 | } 15 | 16 | // Store the k closest points in a vector 17 | vector> ans; 18 | while (!pq.empty()) { 19 | ans.push_back(pq.top()); 20 | pq.pop(); 21 | } 22 | return ans; 23 | } 24 | 25 | private: 26 | static int distance(vector& point) { 27 | return point[0] * point[0] + point[1] * point[1]; // Squared Euclidean distance 28 | } 29 | }; -------------------------------------------------------------------------------- /Get Min from Stack/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int min; 3 | stack st; 4 | 5 | public: 6 | Solution() {} 7 | 8 | // Add an element to the top of the Stack 9 | void push(int x) { 10 | if (st.empty()) { 11 | min = x; 12 | } else if (x <= min) { 13 | st.push(min); 14 | min = x; 15 | } 16 | st.push(x); 17 | } 18 | 19 | // Remove the top element from the Stack 20 | void pop() { 21 | if (st.empty()) 22 | return; 23 | int tmp = st.top(); 24 | st.pop(); 25 | if (tmp == min && !st.empty()) { 26 | min = st.top(); 27 | st.pop(); 28 | } 29 | } 30 | 31 | // Returns top element of the Stack 32 | int peek() { 33 | if (st.empty()) 34 | return -1; 35 | return st.top(); 36 | } 37 | 38 | // Finds minimum element of the Stack 39 | int getMin() { 40 | if (st.empty()) 41 | return -1; 42 | return min; 43 | } 44 | }; -------------------------------------------------------------------------------- /Pair with given sum in a sorted array/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int countPairs(int arr[], int target) { 4 | // Complete the function 5 | int ans=0, st=0, end=arr.length-1; 6 | while(sttarget){ 9 | end--; 10 | } 11 | else if(currSum> insertInterval(vector> &intervals, 4 | vector &newInterval) { 5 | // code here 6 | vector> ans; 7 | int i = 0, len = intervals.size(); 8 | 9 | // Add all intervals before the new interval 10 | while (i < len && intervals[i][1] < newInterval[0]) { 11 | ans.push_back(intervals[i]); 12 | i++; 13 | } 14 | 15 | // Merge overlapping intervals with the new interval 16 | while (i < len && intervals[i][0] <= newInterval[1]) { 17 | newInterval[0] = min(newInterval[0], intervals[i][0]); 18 | newInterval[1] = max(newInterval[1], intervals[i][1]); 19 | i++; 20 | } 21 | ans.push_back(newInterval); 22 | 23 | // Add all intervals after the new interval 24 | while (i < len) { 25 | ans.push_back(intervals[i]); 26 | i++; 27 | } 28 | 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /Clone List with Next and Random/no extra space/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to clone a linked list with next and random pointer. 3 | Node cloneLinkedList(Node head) { 4 | // your code here 5 | if(head == null) 6 | return null; 7 | 8 | Node curr =head; 9 | while(curr!=null){ 10 | Node copy = new Node(curr.data); 11 | copy.next = curr.next; 12 | curr.next = copy; 13 | curr = copy.next; 14 | } 15 | curr = head; 16 | while(curr!=null){ 17 | if(curr.random!=null){ 18 | curr.next.random = curr.random.next; 19 | } 20 | curr = curr.next.next; 21 | } 22 | curr = head; 23 | Node copyH = head.next; 24 | while(curr!=null){ 25 | Node copy = curr.next; 26 | curr.next = copy.next; 27 | if(copy.next!=null){ 28 | copy.next = copy.next.next; 29 | } 30 | curr= curr.next; 31 | } 32 | return copyH; 33 | } -------------------------------------------------------------------------------- /Equalize the Towers/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getCost(vector& heights, vector& cost, int h) { 4 | int totalCost = 0; 5 | for (int i = 0; i < heights.size(); i++) { 6 | totalCost += abs(heights[i] - h) * cost[i]; 7 | } 8 | return totalCost; 9 | } 10 | 11 | int minCost(vector& heights, vector& cost) { 12 | int lo = *min_element(heights.begin(), heights.end()); 13 | int hi = *max_element(heights.begin(), heights.end()); 14 | int ans = INT_MAX; 15 | 16 | while (lo <= hi) { 17 | int mid1 = lo + (hi - lo) / 3; 18 | int mid2 = hi - (hi - lo) / 3; 19 | 20 | int cost1 = getCost(heights, cost, mid1); 21 | int cost2 = getCost(heights, cost, mid2); 22 | 23 | ans = min({ans, cost1, cost2}); 24 | 25 | if (cost1 < cost2) { 26 | hi = mid2 - 1; 27 | } else { 28 | lo = mid1 + 1; 29 | } 30 | } 31 | 32 | return ans; 33 | } 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /Remove loop in Linked List/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to remove a loop in the linked list. 4 | void removeLoop(Node* head) { 5 | // code here 6 | Node* slow = head; 7 | Node* fast = head; 8 | Node* prev = head; 9 | 10 | // Detect loop using Floyd's Cycle Detection algorithm 11 | while (fast != nullptr && fast->next != nullptr) { 12 | slow = slow->next; 13 | prev = fast; 14 | fast = fast->next->next; 15 | 16 | // If a loop is detected 17 | if (slow == fast) { 18 | slow = head; 19 | prev = prev->next; 20 | 21 | // Find the node before the start of the loop 22 | while (slow != fast) { 23 | slow = slow->next; 24 | fast = fast->next; 25 | prev = prev->next; 26 | } 27 | 28 | // Break the loop 29 | prev->next = nullptr; 30 | return; 31 | } 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /Find all possible palindromic partitions of a String/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> palinParts(string &s) { 4 | vector> ans; 5 | vector tmp; 6 | chec(s, 0, tmp, ans); 7 | return ans; 8 | } 9 | 10 | private: 11 | void chec(string &s, int ind, vector &tmp, vector> &ans) { 12 | if (ind >= s.length()) { 13 | ans.push_back(tmp); 14 | return; 15 | } 16 | for (int i = ind + 1; i <= s.length(); ++i) { 17 | string curr = s.substr(ind, i - ind); 18 | if (isPalin(curr)) { 19 | tmp.push_back(curr); 20 | chec(s, i, tmp, ans); 21 | tmp.pop_back(); 22 | } 23 | } 24 | } 25 | 26 | bool isPalin(const string &curr) { 27 | int i = 0, j = curr.length() - 1; 28 | while (i < j) { 29 | if (curr[i] != curr[j]) 30 | return false; 31 | i++; 32 | j--; 33 | } 34 | return true; 35 | } 36 | }; -------------------------------------------------------------------------------- /Merge two sorted linked lists/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* sortedMerge(Node* head1, Node* head2) { 4 | Node* newHead = nullptr; 5 | Node* tmp = nullptr; 6 | 7 | while (head1 != nullptr || head2 != nullptr) { 8 | if (head1 != nullptr && (head2 == nullptr || head1->data < head2->data)) { 9 | if (newHead == nullptr) { 10 | newHead = head1; 11 | tmp = head1; 12 | } else { 13 | tmp->next = head1; 14 | tmp = head1; 15 | } 16 | head1 = head1->next; 17 | } else { 18 | if (newHead == nullptr) { 19 | newHead = head2; 20 | tmp = head2; 21 | } else { 22 | tmp->next = head2; 23 | tmp = head2; 24 | } 25 | head2 = head2->next; 26 | } 27 | } 28 | 29 | if (tmp != nullptr) { 30 | tmp->next = nullptr; 31 | } 32 | 33 | return newHead; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Allocate Minimum Pages/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(vector& arr, int k, int maxPages) { 4 | int totalStudents = 1, currentSum = 0; 5 | 6 | for (int pages : arr) { 7 | currentSum += pages; 8 | if (currentSum > maxPages) { 9 | totalStudents++; 10 | currentSum = pages; // Start new allocation 11 | } 12 | } 13 | return totalStudents <= k; 14 | } 15 | 16 | int findPages(vector& arr, int k) { 17 | if (k > arr.size()) return -1; // If students are more than books 18 | 19 | int beg = 0, end = 0; 20 | for (int pages : arr) { 21 | beg = max(beg, pages); // Maximum single page count 22 | end += pages; // Sum of all pages 23 | } 24 | 25 | int ans = beg; 26 | while (beg <= end) { 27 | int mid = (beg + end) / 2; 28 | if (isPossible(arr, k, mid)) { 29 | ans = mid; 30 | end = mid - 1; // Reduce the search space 31 | } else { 32 | beg = mid + 1; // Increase the search space 33 | } 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /Coin Piles/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumCoins(vector& arr, int k) { 4 | sort(arr.begin(), arr.end()); 5 | int n = arr.size(); 6 | 7 | vector prefix(n + 1, 0); 8 | for (int i = 0; i < n; ++i) { 9 | prefix[i + 1] = prefix[i] + arr[i]; 10 | } 11 | 12 | int ans = INT_MAX; 13 | 14 | for (int i = 0; i < n; ++i) { 15 | int remLeft = prefix[i]; 16 | int upper = upperBound(arr, arr[i] + k); 17 | int remRight = prefix[n] - prefix[upper] - (n - upper) * (arr[i] + k); 18 | ans = min(ans, remLeft + remRight); 19 | } 20 | 21 | return ans; 22 | } 23 | 24 | private: 25 | int upperBound(vector& arr, int v) { 26 | int lo = 0, hi = arr.size() - 1, ans = arr.size(); 27 | while (lo <= hi) { 28 | int mid = (lo + hi) / 2; 29 | if (arr[mid] <= v) { 30 | lo = mid + 1; 31 | } else { 32 | ans = mid; 33 | hi = mid - 1; 34 | } 35 | } 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Construct Tree from Inorder & Preorder/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findIndex(vector &arr, int start, int target) { 4 | int i = 0; 5 | while (arr[start + i] != target) 6 | i++; 7 | return i; 8 | } 9 | 10 | = Node *buildUtil(vector &inorder, vector &preorder, int inStart, 11 | int preStart, int n) { 12 | if (n == 0) 13 | return NULL; 14 | 15 | Node *root = new Node(preorder[preStart]); 16 | 17 | int i = findIndex(inorder, inStart, preorder[preStart]); 18 | 19 | // Recursively construct the left and right subtrees 20 | root->left = buildUtil(inorder, preorder, inStart, preStart + 1, i); 21 | root->right = 22 | buildUtil(inorder, preorder, inStart + i + 1, preStart + i + 1, n - i - 1); 23 | 24 | return root; 25 | } 26 | 27 | // Function to build the tree from given inorder and preorder traversals 28 | Node *buildTree(vector &inorder, vector &preorder) { 29 | int n = inorder.size(); 30 | return buildUtil(inorder, preorder, 0, 0, n); 31 | } 32 | }; -------------------------------------------------------------------------------- /Find all possible palindromic partitions of a String/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList> palinParts(String s) { 3 | // code here 4 | ArrayList> ans = new ArrayList(); 5 | ArrayList tmp = new ArrayList(); 6 | chec(s, 0, tmp, ans); 7 | return ans; 8 | } 9 | static void chec(String s, int ind, ArrayList tmp, ArrayList> ans){ 10 | if(ind>=s.length()){ 11 | ans.add(new ArrayList(tmp)); 12 | return; 13 | } 14 | for(int i=ind+1;i<=s.length();i++){ 15 | String curr = s.substring(ind, i); 16 | if(isPalin(curr)){ 17 | tmp.add(curr); 18 | chec(s, i, tmp, ans); 19 | tmp.remove(tmp.size()-1); 20 | } 21 | } 22 | } 23 | static boolean isPalin(String curr){ 24 | int i=0,j=curr.length()-1; 25 | while(i &arr, int k) { 4 | int n = arr.size(); 5 | map freqMap; 6 | 7 | // Store the frequency of each value 8 | for (int val : arr) { 9 | freqMap[val]++; 10 | } 11 | 12 | // Starting from minimum value, try to form consecutive groups 13 | for (auto p : freqMap) { 14 | int val = p.first; 15 | int freq = p.second; 16 | 17 | // Skip if all cards of this value are already used 18 | if (freq == 0) 19 | continue; 20 | 21 | // Try to form a group of 'k' starting from 'val' 22 | for (int i = 1; i < k; i++) { 23 | int nextVal = val + i; 24 | 25 | // Check if there are enough cards for the next value 26 | if (freqMap[nextVal] < freq) { 27 | return false; 28 | } 29 | 30 | // Deduct the used cards 31 | freqMap[nextVal] -= freq; 32 | } 33 | } 34 | 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /Get Min from Stack/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int min; 3 | Stack st = new Stack(); 4 | public Solution() {} 5 | 6 | // Add an element to the top of Stack 7 | public void push(int x) { 8 | // code here 9 | if(st.isEmpty()){ 10 | min=x; 11 | } 12 | else if(x<=min){ 13 | st.push(min); 14 | min=x; 15 | } 16 | st.push(x); 17 | } 18 | 19 | // Remove the top element from the Stack 20 | public void pop() { 21 | // code here 22 | if(st.isEmpty()) 23 | return; 24 | int tmp = st.pop(); 25 | if(tmp == min){ 26 | if(!st.isEmpty()){ 27 | min=st.pop(); 28 | } 29 | } 30 | } 31 | 32 | // Returns top element of the Stack 33 | public int peek() { 34 | // code here 35 | if(st.isEmpty()) 36 | return -1; 37 | return st.peek(); 38 | } 39 | 40 | // Finds minimum element of Stack 41 | public int getMin() { 42 | // code here 43 | if(st.isEmpty()) 44 | return -1; 45 | return min; 46 | } 47 | } -------------------------------------------------------------------------------- /Merge K sorted linked lists/c++: -------------------------------------------------------------------------------- 1 | struct Compare { 2 | bool operator()(Node* a, Node* b) { 3 | return a->data > b->data; // Min-heap based on node value 4 | } 5 | }; 6 | 7 | class Solution { 8 | public: 9 | // Function to merge K sorted linked lists 10 | Node* mergeKLists(vector& arr) { 11 | priority_queue, Compare> pq; 12 | 13 | // Push the head of each linked list into the priority queue 14 | for (Node* node : arr) { 15 | if (node) { 16 | pq.push(node); 17 | } 18 | } 19 | 20 | Node* newHead = nullptr, *tail = nullptr; 21 | 22 | while (!pq.empty()) { 23 | Node* temp = pq.top(); 24 | pq.pop(); 25 | 26 | if (!newHead) { 27 | newHead = temp; 28 | tail = temp; 29 | } else { 30 | tail->next = temp; 31 | tail = temp; 32 | } 33 | 34 | if (temp->next) { 35 | pq.push(temp->next); 36 | } 37 | } 38 | return newHead; 39 | } 40 | }; -------------------------------------------------------------------------------- /Count Inversions/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to count inversions in the array. 4 | int inversionCount(vector& arr) { 5 | return mergeSort(arr, 0, arr.size() - 1); 6 | } 7 | 8 | private: 9 | int mergeSort(vector& arr, int le, int ri) { 10 | if (le >= ri) { 11 | return 0; 12 | } 13 | int mid = le + (ri - le) / 2; 14 | int leftInversion = mergeSort(arr, le, mid); 15 | int rightInversion = mergeSort(arr, mid + 1, ri); 16 | int mergedInversion = merge(arr, le, mid, ri); 17 | return leftInversion + rightInversion + mergedInversion; 18 | } 19 | 20 | int merge(vector& arr, int le, int mid, int ri) { 21 | int j = mid + 1; 22 | int cn = 0; 23 | 24 | // Count inversions 25 | for (int i = le; i <= mid; i++) { 26 | while (j <= ri && arr[i] > arr[j]) { 27 | j++; 28 | } 29 | cn += (j - (mid + 1)); 30 | } 31 | 32 | // Sort the array segment (le to ri) after counting inversions 33 | sort(arr.begin() + le, arr.begin() + ri + 1); 34 | return cn; 35 | } 36 | }; -------------------------------------------------------------------------------- /Longest Subarray with Sum K/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& arr, int k) { 4 | unordered_map 5 | prefixSumIndices; // Maps cumulative sum to its earliest index 6 | int currentSum = 0, longestLength = 0; 7 | 8 | // Traverse through the array 9 | for (int i = 0; i < arr.size(); i++) { 10 | currentSum += arr[i]; // Accumulate the current sum 11 | 12 | // Check if subarray starting from index 0 equals k 13 | if (currentSum == k) 14 | longestLength = i + 1; 15 | 16 | // If (currentSum - k) exists in the map, update longestLength 17 | if (prefixSumIndices.find(currentSum - k) != prefixSumIndices.end()) { 18 | longestLength = 19 | max(longestLength, i - prefixSumIndices[currentSum - k]); 20 | } 21 | 22 | // Store the current sum in the map if it hasn't been stored yet 23 | if (prefixSumIndices.find(currentSum) == prefixSumIndices.end()) 24 | prefixSumIndices[currentSum] = i; 25 | } 26 | 27 | return longestLength; // Return the length of the longest subarray 28 | } 29 | }; -------------------------------------------------------------------------------- /Set Matrix Zeroes/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // c++ and java code are pretty much same so I am not writing c++ code. Please ask if you have any doubt. 4 | 5 | public void setMatrixZeroes(int[][] mat) { 6 | int r = mat.length, c = mat[0].length; 7 | boolean isFirstColZero = false; 8 | 9 | for(int i=0;i=mat.length || j>= mat[0].length || visit[i][j] || mat[i][j] != word.charAt(ind)){ 20 | return false; 21 | } 22 | visit[i][j]=true; 23 | if(check(mat, i, j-1, ind+1, word, visit) || 24 | check(mat, i, j+1, ind+1, word, visit) || 25 | check(mat, i+1, j, ind+1, word, visit) || 26 | check(mat, i-1, j, ind+1, word, visit)) 27 | return true; 28 | 29 | visit[i][j]=false; 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /Decode the string/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static String decodeString(String s) { 3 | // code here 4 | Stack count = new Stack(); 5 | Stack result = new Stack(); 6 | char[] arr = s.toCharArray(); 7 | int i=0, num=0; 8 | String curr = ""; 9 | while(i cache; 4 | static int capacity; 5 | LRUCache(int cap) { 6 | // code here 7 | cache = new LinkedHashMap(); 8 | capacity = cap; 9 | } 10 | 11 | // Function to return value corresponding to the key. 12 | public static int get(int key) { 13 | // your code here 14 | if(!cache.containsKey(key)){ 15 | return -1; 16 | } 17 | int val = cache.get(key); 18 | cache.remove(key); 19 | cache.put(key, val); 20 | return val; 21 | } 22 | 23 | // Function for storing key-value pair. 24 | public static void put(int key, int value) { 25 | // your code here 26 | if(cache.containsKey(key)){ 27 | cache.remove(key); 28 | cache.put(key, value); 29 | return; 30 | } 31 | if(cache.size() == capacity){ 32 | int rem = -1; 33 | for(int i: cache.keySet()){ 34 | rem = i; 35 | break; 36 | } 37 | cache.remove(rem); 38 | } 39 | 40 | cache.put(key, value); 41 | } 42 | } -------------------------------------------------------------------------------- /N-Queen Problem/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList> nQueen(int n) { 3 | // code here 4 | boolean[] col = new boolean[n]; 5 | boolean[] ndiag = new boolean[2*n-1]; 6 | boolean[] rdiag = new boolean[2*n-1]; 7 | ArrayList> res = new ArrayList(); 8 | ArrayList tmp = new ArrayList(); 9 | solve(n, 0, col, ndiag, rdiag, res, tmp); 10 | return res; 11 | } 12 | static void solve(int n, int currR, boolean[] col, boolean[] ndiag, boolean[] rdiag, ArrayList> res, ArrayList tmp){ 13 | if(currR == n){ 14 | res.add(new ArrayList(tmp)); 15 | return; 16 | } 17 | for(int i=0;i countStack; 6 | stack resultStack; 7 | int i = 0, num = 0; 8 | string curr = ""; 9 | 10 | while (i < s.length()) { 11 | if (isdigit(s[i])) { 12 | num = 0; 13 | while (isdigit(s[i])) { 14 | num = num * 10 + (s[i] - '0'); 15 | i++; 16 | } 17 | countStack.push(num); 18 | } 19 | else if (s[i] == '[') { 20 | resultStack.push(curr); 21 | curr = ""; 22 | i++; 23 | } 24 | else if (s[i] == ']') { 25 | int n = countStack.top(); 26 | countStack.pop(); 27 | string temp = resultStack.top(); 28 | resultStack.pop(); 29 | for (int j = 0; j < n; j++) { 30 | temp += curr; 31 | } 32 | curr = temp; 33 | i++; 34 | } 35 | else { 36 | curr += s[i]; 37 | i++; 38 | } 39 | } 40 | return curr; 41 | } 42 | }; -------------------------------------------------------------------------------- /Fixing Two nodes of a BST/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node *first, *middle, *last, *prev; 4 | 5 | Solution() { 6 | first = middle = last = prev = nullptr; 7 | } 8 | 9 | void inorder(Node* root) { 10 | if (!root) return; 11 | 12 | // Left subtree 13 | inorder(root->left); 14 | 15 | // Detect misplaced nodes 16 | if (prev && prev->data > root->data) { 17 | if (!first) { 18 | first = prev; 19 | middle = root; // First violation 20 | } else { 21 | last = root; // Second violation 22 | } 23 | } 24 | prev = root; // Update prev node 25 | 26 | // Right subtree 27 | inorder(root->right); 28 | } 29 | 30 | void correctBST(Node* root) { 31 | first = middle = last = nullptr; 32 | prev = new Node(INT_MIN); // Initialize previous node with minimum value 33 | 34 | inorder(root); 35 | 36 | // If two nodes are not adjacent 37 | if (first && last) { 38 | swap(first->data, last->data); 39 | } 40 | // If two nodes are adjacent 41 | else if (first && middle) { 42 | swap(first->data, middle->data); 43 | } 44 | } 45 | }; -------------------------------------------------------------------------------- /N-Queen Problem/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> nQueen(int n) { 4 | vector col(n, false); 5 | vector ndiag(2 * n - 1, false); 6 | vector rdiag(2 * n - 1, false); 7 | vector> res; 8 | vector tmp; 9 | solve(n, 0, col, ndiag, rdiag, res, tmp); 10 | return res; 11 | } 12 | 13 | private: 14 | void solve(int n, int currR, vector& col, vector& ndiag, vector& rdiag, 15 | vector>& res, vector& tmp) { 16 | if (currR == n) { 17 | res.push_back(tmp); 18 | return; 19 | } 20 | for (int i = 0; i < n; i++) { 21 | if (!col[i] && !ndiag[currR + i] && !rdiag[currR - i + n - 1]) { 22 | tmp.push_back(i + 1); 23 | col[i] = true; 24 | ndiag[currR + i] = true; 25 | rdiag[currR - i + n - 1] = true; 26 | 27 | solve(n, currR + 1, col, ndiag, rdiag, res, tmp); 28 | 29 | tmp.pop_back(); 30 | col[i] = false; 31 | ndiag[currR + i] = false; 32 | rdiag[currR - i + n - 1] = false; 33 | } 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /Find All Triplets with Zero Sum/java: -------------------------------------------------------------------------------- 1 | // Please follow me on github and let me know if you have any doubt. 2 | 3 | class Solution { 4 | public List> findTriplets(int[] arr) { 5 | // Your code here 6 | Set> ansSet = new HashSet(); 7 | Map> mp =new HashMap(); 8 | 9 | for(int i=0;i()); 15 | } 16 | mp.get(sum).add(new int[]{i,j}); 17 | } 18 | } 19 | 20 | for(int i=0;i pairs = mp.get(tar); 24 | for(int[] pair: pairs){ 25 | if(pair[0]!=i && pair[1]!=i){ 26 | List curr = Arrays.asList(i, pair[0], pair[1]); 27 | Collections.sort(curr); 28 | ansSet.add(curr); 29 | } 30 | } 31 | } 32 | } 33 | return new ArrayList<>(ansSet); 34 | } 35 | } -------------------------------------------------------------------------------- /Find median in a stream/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ArrayList getMedian(int[] arr) { 3 | // code here 4 | ArrayList res = new ArrayList(); 5 | PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 6 | PriorityQueue minHeap = new PriorityQueue<>(); 7 | for(int num: arr){ 8 | addNum(num, maxHeap, minHeap); 9 | res.add(findMedian(maxHeap, minHeap)); 10 | } 11 | return res; 12 | } 13 | void addNum(int num,PriorityQueue maxHeap, PriorityQueue minHeap ){ 14 | if(maxHeap.isEmpty() || num<=maxHeap.peek()){ 15 | maxHeap.add(num); 16 | } 17 | else { 18 | minHeap.add(num); 19 | } 20 | if(maxHeap.size() > minHeap.size()+1){ 21 | minHeap.add(maxHeap.poll()); 22 | } 23 | else if(minHeap.size() > maxHeap.size()){ 24 | maxHeap.add(minHeap.poll()); 25 | } 26 | } 27 | double findMedian(PriorityQueue maxHeap, PriorityQueue minHeap){ 28 | if(maxHeap.size()>minHeap.size()){ 29 | return maxHeap.peek(); 30 | } 31 | else { 32 | return (maxHeap.peek() + minHeap.peek())/2.0; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Parenthesis Checker/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isBalanced(string& s) { 4 | 5 | // Declare a stack to store the opening brackets 6 | stack st; 7 | for (int i = 0; i < s.length(); i++) { 8 | 9 | // Check if the character is an opening bracket 10 | if (s[i] == '(' || s[i] == '{' || s[i] == '[') { 11 | st.push(s[i]); 12 | } 13 | 14 | else { 15 | 16 | // If it's a closing bracket, check if the stack is non-empty 17 | // and if the top of the stack is a matching opening bracket 18 | if (!st.empty() && ((st.top() == '(' && s[i] == ')') || 19 | (st.top() == '{' && s[i] == '}') || 20 | (st.top() == '[' && s[i] == ']'))) { 21 | 22 | // Pop the matching opening bracket 23 | st.pop(); 24 | } else { 25 | 26 | // Unmatched closing bracket 27 | return false; 28 | } 29 | } 30 | } 31 | 32 | // If stack is empty, return true (balanced), otherwise false 33 | return st.empty(); 34 | } 35 | }; -------------------------------------------------------------------------------- /Count all triplets with given sum in sorted array/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // code is mostly same for both java and c++ so I am providing only java code 3 | public int countTriplets(int[] arr, int target) { 4 | // Code Here 5 | int ans=0,size = arr.length; 6 | for(int i=0;itarget){ 14 | k--; 15 | } 16 | else { 17 | int e1=arr[j], e2=arr[k], c1=0, c2=0; 18 | while(j<=k && arr[j]==e1){ 19 | c1++; 20 | j++; 21 | } 22 | 23 | while(j<=k && arr[k]==e2){ 24 | c2++; 25 | k--; 26 | } 27 | if(e1==e2){ 28 | ans+=(c1*(c1-1))/2; 29 | } 30 | else { 31 | ans+=c1*c2; 32 | } 33 | } 34 | } 35 | } 36 | return ans; 37 | } 38 | } -------------------------------------------------------------------------------- /Find All Triplets with Zero Sum/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findTriplets(vector &arr) { 4 | // Set to handle duplicates 5 | set> ansSet; 6 | int n = arr.size(); 7 | unordered_map>> mp; 8 | 9 | // Store sum of all the pairs with their indices 10 | for (int i = 0; i < n; i++) { 11 | for (int j = i + 1; j < n; j++) 12 | mp[arr[i] + arr[j]].push_back({i, j}); 13 | } 14 | 15 | for (int i = 0; i < n; i++) { 16 | 17 | // Find remaining value to get zero sum 18 | int rem = -arr[i]; 19 | if (mp.find(rem) != mp.end()) { 20 | vector> pairs = mp[rem]; 21 | for (auto p : pairs) { 22 | 23 | // Ensure no two indices are same in triplet 24 | if (p.first != i && p.second != i) { 25 | vector curr = {i, p.first, p.second}; 26 | sort(curr.begin(), curr.end()); 27 | ansSet.insert(curr); 28 | } 29 | } 30 | } 31 | } 32 | 33 | vector> res(ansSet.begin(), ansSet.end()); 34 | return res; 35 | } 36 | }; -------------------------------------------------------------------------------- /Fixing Two nodes of a BST/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Node first, middle, last, prev; 3 | private void inorder(Node root) { 4 | if (root == null) return; 5 | 6 | // Left subtree 7 | inorder(root.left); 8 | 9 | // Detect misplaced nodes 10 | if (prev != null && prev.data > root.data) { 11 | if (first == null) { 12 | first = prev; 13 | middle = root; // First violation 14 | } else { 15 | last = root; // Second violation 16 | } 17 | } 18 | prev = root; // Update prev node 19 | 20 | // Right subtree 21 | inorder(root.right); 22 | } 23 | void correctBST(Node root) { 24 | // code here. 25 | first = middle = last = null; 26 | inorder(root); 27 | 28 | // If two nodes are not adjacent 29 | if (first != null && last != null) { 30 | int temp = first.data; 31 | first.data = last.data; 32 | last.data = temp; 33 | } 34 | // If two nodes are adjacent in in-order traversal 35 | else if (first != null && middle != null) { 36 | int temp = first.data; 37 | first.data = middle.data; 38 | middle.data = temp; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Longest Bounded-Difference Subarray/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public ArrayList longestSubarray(int[] arr, int x) { 4 | // code here 5 | Deque maxDq = new LinkedList<>(); 6 | Deque minDq = new LinkedList<>(); 7 | int str = 0, maxLen = 0, ansStr = 0; 8 | for(int end = 0; end= arr[end]){ 14 | minDq.pollLast(); 15 | } 16 | minDq.addLast(end); 17 | 18 | while(arr[maxDq.peekFirst()]-arr[minDq.peekFirst()] > x){ 19 | str++; 20 | if(maxDq.peekFirst() maxLen){ 25 | maxLen = end-str + 1; 26 | ansStr = str; 27 | } 28 | } 29 | 30 | ArrayList ans = new ArrayList(); 31 | for(int i=ansStr;i longestSubarray(vector& arr, int x) { 4 | // code here 5 | int n = arr.size(); 6 | deque maxDeque, minDeque; 7 | int start = 0, maxLen = 0, bestStart = 0; 8 | 9 | for (int end = 0; end < n; end++) { 10 | // Maintain maxDeque (Monotonic Decreasing) 11 | while (!maxDeque.empty() && arr[maxDeque.back()] <= arr[end]) 12 | maxDeque.pop_back(); 13 | maxDeque.push_back(end); 14 | 15 | // Maintain minDeque (Monotonic Increasing) 16 | while (!minDeque.empty() && arr[minDeque.back()] >= arr[end]) 17 | minDeque.pop_back(); 18 | minDeque.push_back(end); 19 | 20 | // Shrink window if max - min > x 21 | while (arr[maxDeque.front()] - arr[minDeque.front()] > x) { 22 | start++; 23 | if (maxDeque.front() < start) maxDeque.pop_front(); 24 | if (minDeque.front() < start) minDeque.pop_front(); 25 | } 26 | 27 | // Update max length and best start index 28 | if (end - start + 1 > maxLen) { 29 | maxLen = end - start + 1; 30 | bestStart = start; 31 | } 32 | } 33 | 34 | return vector(arr.begin() + bestStart, arr.begin() + bestStart + maxLen); 35 | } 36 | }; -------------------------------------------------------------------------------- /Linked List Group Reverse/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static Node reverseKGroup(Node head, int k) { 3 | // code here 4 | int len = getLength(head); 5 | Node origH = null; 6 | Node origT = null, tmpH = null, tmpT=null; 7 | Node curr=head; 8 | while(len > 0){ 9 | int j=k; 10 | j = Math.min(j, len); 11 | while(j>0){ 12 | Node nex = curr.next; 13 | if(tmpH == null){ 14 | tmpH = curr; 15 | tmpT = curr; 16 | } 17 | else { 18 | curr.next = tmpH; 19 | tmpH = curr; 20 | } 21 | curr=nex; 22 | j--; 23 | len--; 24 | } 25 | if(origH == null){ 26 | origH = tmpH; 27 | origT = tmpT; 28 | } 29 | else { 30 | origT.next = tmpH; 31 | origT = tmpT; 32 | } 33 | tmpH = null; 34 | tmpT=null; 35 | } 36 | origT.next = null; 37 | return origH; 38 | } 39 | public static int getLength(Node head){ 40 | int len =0; 41 | while(head!=null){ 42 | len++; 43 | head=head.next; 44 | } 45 | return len; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Add Number Linked Lists/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static Node addTwoLists(Node num1, Node num2) { 3 | // code here 4 | Node l1 = reverseList(num1); 5 | Node l2 = reverseList(num2); 6 | Node curr = null; 7 | int carry = 0; 8 | while(l1!=null || l2!=null || carry >0){ 9 | int v1 = l1!=null ? l1.data : 0; 10 | int v2 = l2!=null ? l2.data : 0; 11 | int sum = v1+v2+carry; 12 | carry = sum/10; 13 | Node tmp = new Node(sum%10); 14 | tmp.next = curr; 15 | curr = tmp; 16 | if(l1!=null){ 17 | l1=l1.next; 18 | } 19 | if(l2!=null){ 20 | l2=l2.next; 21 | } 22 | } 23 | while(curr!=null && curr.data == 0){ 24 | curr=curr.next; 25 | } 26 | return curr; 27 | 28 | } 29 | static Node reverseList(Node head) { 30 | // code here 31 | Node tmpHead = null; 32 | while(head!=null){ 33 | Node nex = head.next; 34 | if(tmpHead == null) { 35 | tmpHead = head; 36 | tmpHead.next = null; 37 | } 38 | else { 39 | head.next = tmpHead; 40 | tmpHead = head; 41 | } 42 | head = nex; 43 | } 44 | return tmpHead; 45 | } 46 | } -------------------------------------------------------------------------------- /Word Search/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isWordExist(vector>& mat, string& word) { 4 | // Code here 5 | for (int i = 0; i < mat.size(); i++) { 6 | for (int j = 0; j < mat[0].size(); j++) { 7 | if (mat[i][j] == word[0]) { 8 | vector> visit(mat.size(), vector(mat[0].size(), false)); 9 | if (check(mat, i, j, 0, word, visit)) 10 | return true; 11 | } 12 | } 13 | } 14 | return false; 15 | } 16 | 17 | private: 18 | static bool check(vector>& mat, int i, int j, int ind, string& word, vector>& visit) { 19 | if (ind == word.length()) { 20 | return true; 21 | } 22 | if (i < 0 || j < 0 || i >= mat.size() || j >= mat[0].size() || visit[i][j] || mat[i][j] != word[ind]) { 23 | return false; 24 | } 25 | visit[i][j] = true; 26 | if (check(mat, i, j - 1, ind + 1, word, visit) || 27 | check(mat, i, j + 1, ind + 1, word, visit) || 28 | check(mat, i + 1, j, ind + 1, word, visit) || 29 | check(mat, i - 1, j, ind + 1, word, visit)) { 30 | return true; 31 | } 32 | visit[i][j] = false; 33 | return false; 34 | } 35 | }; -------------------------------------------------------------------------------- /Clone List with Next and Random/with extra space/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to clone a linked list with next and random pointer. 3 | Node cloneLinkedList(Node head) { 4 | // your code her 5 | // your code here 6 | Map nodeMapping = new HashMap<>(); 7 | 8 | // Dummy node to start building the cloned list 9 | Node dummyNode = new Node(0); 10 | Node currentOriginalNode = head; 11 | Node currentClonedNode = dummyNode; 12 | 13 | // Step 1: Create a clone of the linked list with only next pointers 14 | while (head != null) { 15 | Node clonedNode = new Node(head.data); 16 | currentClonedNode.next = clonedNode; 17 | nodeMapping.put(head, clonedNode); 18 | currentClonedNode = clonedNode; 19 | head = head.next; 20 | } 21 | 22 | // Step 2: Update the random pointers in the cloned list 23 | Node clonedHead = dummyNode.next; // Head of the cloned list 24 | while (currentOriginalNode != null) { 25 | if (currentOriginalNode.random != null) { 26 | clonedHead.random = nodeMapping.get(currentOriginalNode.random); 27 | } 28 | clonedHead = clonedHead.next; 29 | currentOriginalNode = currentOriginalNode.next; 30 | } 31 | 32 | return dummyNode.next; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Find median in a stream/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getMedian(vector& arr) { 4 | vector res; 5 | priority_queue maxHeap; // Max heap for the smaller half 6 | priority_queue, greater> minHeap; // Min heap for the larger half 7 | 8 | for (int num : arr) { 9 | addNum(num, maxHeap, minHeap); 10 | res.push_back(findMedian(maxHeap, minHeap)); 11 | } 12 | return res; 13 | } 14 | 15 | private: 16 | void addNum(int num, priority_queue& maxHeap, priority_queue, greater>& minHeap) { 17 | if (maxHeap.empty() || num <= maxHeap.top()) { 18 | maxHeap.push(num); 19 | } else { 20 | minHeap.push(num); 21 | } 22 | 23 | // Balance the heaps 24 | if (maxHeap.size() > minHeap.size() + 1) { 25 | minHeap.push(maxHeap.top()); 26 | maxHeap.pop(); 27 | } else if (minHeap.size() > maxHeap.size()) { 28 | maxHeap.push(minHeap.top()); 29 | minHeap.pop(); 30 | } 31 | } 32 | 33 | double findMedian(priority_queue& maxHeap, priority_queue, greater>& minHeap) { 34 | if (maxHeap.size() > minHeap.size()) { 35 | return maxHeap.top(); 36 | } else { 37 | return (maxHeap.top() + minHeap.top()) / 2.0; 38 | } 39 | } 40 | }; -------------------------------------------------------------------------------- /Search Pattern (KMP-Algorithm)/Java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | ArrayList search(String pat, String txt) { 4 | // your code here 5 | ArrayList res=new ArrayList(); 6 | int[] lps = new int[pat.length()]; 7 | calculateLPS(pat, lps); 8 | int j=0, f=0, i=0; 9 | int N = txt.length(); 10 | while(i>& mat) { 5 | solve(mat, 0, 0); 6 | } 7 | 8 | private: 9 | static bool solve(vector>& mat, int i, int j) { 10 | if (i == 9) { 11 | return true; 12 | } 13 | int nextI = (j == 8) ? i + 1 : i; 14 | int nextJ = (j == 8) ? 0 : j + 1; 15 | 16 | if (mat[i][j] != 0) { 17 | return solve(mat, nextI, nextJ); 18 | } 19 | for (int val = 1; val <= 9; val++) { 20 | if (isValid(mat, i, j, val)) { 21 | mat[i][j] = val; 22 | if (solve(mat, nextI, nextJ)) { 23 | return true; 24 | } 25 | mat[i][j] = 0; 26 | } 27 | } 28 | return false; 29 | } 30 | 31 | static bool isValid(vector>& mat, int r, int c, int val) { 32 | for (int i = 0; i < 9; i++) { 33 | if (mat[i][c] == val || mat[r][i] == val) 34 | return false; 35 | } 36 | 37 | int strR = (r / 3) * 3; 38 | int strC = (c / 3) * 3; 39 | for (int i = strR; i < strR + 3; i++) { 40 | for (int j = strC; j < strC + 3; j++) { 41 | if (mat[i][j] == val) { 42 | return false; 43 | } 44 | } 45 | } 46 | return true; 47 | } 48 | }; -------------------------------------------------------------------------------- /Clone List with Next and Random/with extra space/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node *cloneLinkedList(Node *head) { 4 | // Write your code here 5 | if (head == nullptr) return nullptr; 6 | 7 | // Map to store the mapping of original nodes to their corresponding cloned nodes 8 | unordered_map nodeMapping; 9 | 10 | // Dummy node to start building the cloned list 11 | Node* dummyNode = new Node(0); 12 | Node* currentOriginalNode = head; 13 | Node* currentClonedNode = dummyNode; 14 | 15 | // Step 1: Create a clone of the linked list with only next pointers 16 | while (head != nullptr) { 17 | Node* clonedNode = new Node(head->data); 18 | currentClonedNode->next = clonedNode; 19 | nodeMapping[head] = clonedNode; 20 | currentClonedNode = clonedNode; 21 | head = head->next; 22 | } 23 | 24 | // Step 2: Update the random pointers in the cloned list 25 | Node* clonedHead = dummyNode->next; // Head of the cloned list 26 | while (currentOriginalNode != nullptr) { 27 | if (currentOriginalNode->random != nullptr) { 28 | clonedHead->random = nodeMapping[currentOriginalNode->random]; 29 | } 30 | clonedHead = clonedHead->next; 31 | currentOriginalNode = currentOriginalNode->next; 32 | } 33 | 34 | return dummyNode->next; 35 | } 36 | }; -------------------------------------------------------------------------------- /Tree Boundary Traversal/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList boundaryTraversal(Node node) { 3 | // code here 4 | ArrayList ans = new ArrayList(); 5 | if(node.left!=null || node.right!=null){ 6 | ans.add(node.data); 7 | } 8 | leftNodes(node.left, ans); 9 | addLeaves(node, ans); 10 | rightRevNodes(node.right, ans); 11 | return ans; 12 | } 13 | void leftNodes(Node node, ArrayList ans){ 14 | if(node == null) 15 | return; 16 | if(node.left!=null){ 17 | ans.add(node.data); 18 | leftNodes(node.left, ans); 19 | } else if(node.right!=null){ 20 | ans.add(node.data); 21 | leftNodes(node.right, ans); 22 | } 23 | } 24 | void addLeaves(Node node, ArrayList ans){ 25 | if(node == null) 26 | return; 27 | addLeaves(node.left, ans); 28 | if(node.left==null && node.right == null){ 29 | ans.add(node.data); 30 | } 31 | addLeaves(node.right, ans); 32 | } 33 | void rightRevNodes(Node node, ArrayList ans){ 34 | if(node == null) 35 | return; 36 | if(node.right!=null){ 37 | 38 | rightRevNodes(node.right, ans); 39 | ans.add(node.data); 40 | } else if(node.left!=null){ 41 | rightRevNodes(node.left, ans); 42 | ans.add(node.data); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Linked List Group Reverse/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node *reverseKGroup(Node *head, int k) { 4 | // code here 5 | int len = getLength(head); 6 | Node* origH = nullptr; 7 | Node* origT = nullptr; 8 | Node* tmpH = nullptr; 9 | Node* tmpT = nullptr; 10 | Node* curr = head; 11 | 12 | while (len > 0) { 13 | int j = k; 14 | j = std::min(j, len); 15 | while (j > 0) { 16 | Node* nex = curr->next; 17 | if (tmpH == nullptr) { 18 | tmpH = curr; 19 | tmpT = curr; 20 | } else { 21 | curr->next = tmpH; 22 | tmpH = curr; 23 | } 24 | curr = nex; 25 | j--; 26 | len--; 27 | } 28 | 29 | if (origH == nullptr) { 30 | origH = tmpH; 31 | origT = tmpT; 32 | } else { 33 | origT->next = tmpH; 34 | origT = tmpT; 35 | } 36 | 37 | tmpH = nullptr; 38 | tmpT = nullptr; 39 | } 40 | 41 | if (origT != nullptr) { 42 | origT->next = nullptr; 43 | } 44 | 45 | return origH; 46 | } 47 | 48 | int getLength(Node* head) { 49 | int len = 0; 50 | while (head != nullptr) { 51 | len++; 52 | head = head->next; 53 | } 54 | return len; 55 | } 56 | }; -------------------------------------------------------------------------------- /LRU Cache/c++: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | private: 3 | int capacity; 4 | std::list> cacheList; // Stores key-value pairs in order of use 5 | std::unordered_map>::iterator> cacheMap; // Maps keys to iterators in the list 6 | 7 | public: 8 | LRUCache(int cap) : capacity(cap) {} 9 | 10 | int get(int key) { 11 | auto it = cacheMap.find(key); 12 | if (it == cacheMap.end()) { 13 | return -1; // Key not found 14 | } 15 | 16 | // Move the accessed key-value pair to the front of the list 17 | cacheList.splice(cacheList.begin(), cacheList, it->second); 18 | 19 | return it->second->second; // Return the value 20 | } 21 | 22 | void put(int key, int value) { 23 | auto it = cacheMap.find(key); 24 | if (it != cacheMap.end()) { 25 | // Key already exists, update its value and move it to the front 26 | cacheList.splice(cacheList.begin(), cacheList, it->second); 27 | it->second->second = value; 28 | return; 29 | } 30 | 31 | // If cache is full, remove the least recently used item 32 | if (cacheMap.size() == capacity) { 33 | int lruKey = cacheList.back().first; 34 | cacheMap.erase(lruKey); 35 | cacheList.pop_back(); 36 | } 37 | 38 | // Add the new key-value pair to the front of the list and update the map 39 | cacheList.emplace_front(key, value); 40 | cacheMap[key] = cacheList.begin(); 41 | } 42 | }; -------------------------------------------------------------------------------- /Tree Boundary Traversal/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector boundaryTraversal(Node* node) { 4 | vector ans; 5 | if (node->left != nullptr || node->right != nullptr) { 6 | ans.push_back(node->data); 7 | } 8 | leftNodes(node->left, ans); 9 | addLeaves(node, ans); 10 | rightRevNodes(node->right, ans); 11 | return ans; 12 | } 13 | 14 | private: 15 | void leftNodes(Node* node, vector& ans) { 16 | if (node == nullptr) 17 | return; 18 | if (node->left != nullptr) { 19 | ans.push_back(node->data); 20 | leftNodes(node->left, ans); 21 | } else if (node->right != nullptr) { 22 | ans.push_back(node->data); 23 | leftNodes(node->right, ans); 24 | } 25 | } 26 | 27 | void addLeaves(Node* node, vector& ans) { 28 | if (node == nullptr) 29 | return; 30 | addLeaves(node->left, ans); 31 | if (node->left == nullptr && node->right == nullptr) { 32 | ans.push_back(node->data); 33 | } 34 | addLeaves(node->right, ans); 35 | } 36 | 37 | void rightRevNodes(Node* node, vector& ans) { 38 | if (node == nullptr) 39 | return; 40 | if (node->right != nullptr) { 41 | rightRevNodes(node->right, ans); 42 | ans.push_back(node->data); 43 | } else if (node->left != nullptr) { 44 | rightRevNodes(node->left, ans); 45 | ans.push_back(node->data); 46 | } 47 | } 48 | }; -------------------------------------------------------------------------------- /Solve the Sudoku/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find a solved Sudoku. 3 | static void solveSudoku(int[][] mat) { 4 | // code here 5 | solve(mat, 0, 0); 6 | } 7 | static boolean solve(int[][] mat, int i, int j){ 8 | if(i==9){ 9 | return true; 10 | } 11 | int nextI=0, nextJ=0; 12 | if(j==8){ 13 | nextI=i+1; 14 | nextJ=0; 15 | } 16 | else { 17 | nextI=i; 18 | nextJ=j+1; 19 | } 20 | if(mat[i][j]!=0){ 21 | return solve(mat, nextI, nextJ); 22 | } 23 | else { 24 | for(int val=1;val<=9;val++){ 25 | if(isValid(mat, i, j, val)){ 26 | mat[i][j]=val; 27 | if(solve(mat, nextI, nextJ)){ 28 | return true; 29 | } 30 | else 31 | mat[i][j]=0; 32 | } 33 | } 34 | return false; 35 | } 36 | } 37 | static boolean isValid(int[][] mat, int r, int c, int val){ 38 | for(int i=0;i<9;i++){ 39 | if(mat[i][c]==val || mat[r][i]==val) 40 | return false; 41 | } 42 | 43 | int strR = (r/3)*3; 44 | 45 | int strC = (c/3)*3; 46 | for(int i=strR;i& lps) { 4 | int len = 0; 5 | int i; 6 | 7 | lps[0] = 0; 8 | i = 1; 9 | 10 | while (i < M) { 11 | if (pat[i] == pat[len]) { 12 | len++; 13 | lps[i] = len; 14 | i++; 15 | } 16 | 17 | else { 18 | if (len != 0) { 19 | len = lps[len - 1]; 20 | 21 | } else { 22 | lps[i] = 0; 23 | i++; 24 | } 25 | } 26 | } 27 | } 28 | 29 | vector search(string& pat, string& txt) { 30 | vector res; 31 | int M = pat.size(); 32 | int N = txt.size(); 33 | 34 | vector lps(M + 1, 0); 35 | int j = 0; 36 | computeLPSArray(pat, M, lps); 37 | int f = 0; 38 | int i = 0; // index for txt[] 39 | while (i < N) { 40 | if (pat[j] == txt[i]) { 41 | j++; 42 | i++; 43 | } 44 | 45 | if (j == M) { 46 | f++; 47 | res.push_back(i - j); 48 | j = lps[j - 1]; 49 | } 50 | 51 | // mismatch after j matches 52 | else if (i < N && pat[j] != txt[i]) { 53 | if (j != 0) 54 | j = lps[j - 1]; 55 | else 56 | i = i + 1; 57 | } 58 | } 59 | 60 | return res; 61 | } 62 | }; -------------------------------------------------------------------------------- /Add Number Linked Lists/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* addTwoLists(Node* num1, Node* num2) { 4 | // Reverse both lists 5 | Node* l1 = reverseList(num1); 6 | Node* l2 = reverseList(num2); 7 | Node* curr = nullptr; 8 | int carry = 0; 9 | 10 | // Add numbers represented by the two linked lists 11 | while (l1 != nullptr || l2 != nullptr || carry > 0) { 12 | int v1 = (l1 != nullptr) ? l1->data : 0; 13 | int v2 = (l2 != nullptr) ? l2->data : 0; 14 | int sum = v1 + v2 + carry; 15 | carry = sum / 10; 16 | Node* tmp = new Node(sum % 10); 17 | tmp->next = curr; 18 | curr = tmp; 19 | 20 | if (l1 != nullptr) { 21 | l1 = l1->next; 22 | } 23 | if (l2 != nullptr) { 24 | l2 = l2->next; 25 | } 26 | } 27 | 28 | // Remove leading zeros if any 29 | while (curr != nullptr && curr->data == 0) { 30 | curr = curr->next; 31 | } 32 | 33 | return curr; 34 | } 35 | 36 | private: 37 | Node* reverseList(Node* head) { 38 | Node* tmpHead = nullptr; 39 | 40 | while (head != nullptr) { 41 | Node* nex = head->next; 42 | if (tmpHead == nullptr) { 43 | tmpHead = head; 44 | tmpHead->next = nullptr; 45 | } else { 46 | head->next = tmpHead; 47 | tmpHead = head; 48 | } 49 | head = nex; 50 | } 51 | 52 | return tmpHead; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Spirally traversing a matrix/java and c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to return a list of integers denoting spiral traversal of matrix. 3 | 4 | // code is basically same for java and C++. just the syntax is different. So, I am not repeating the code for C++. Hope you understand. 5 | 6 | public ArrayList spirallyTraverse(int mat[][]) { 7 | // code here 8 | int r = mat.length, c = mat[0].length; 9 | int top = 0, down = r-1, left = 0, right = c-1, d=0; 10 | ArrayList res = new ArrayList(); 11 | while(top<=down && left<=right){ 12 | switch(d){ 13 | case 0: 14 | for(int i=left;i<=right;i++){ 15 | res.add(mat[top][i]); 16 | } 17 | top++; 18 | break; 19 | case 1: 20 | for(int i=top;i<=down;i++){ 21 | res.add(mat[i][right]); 22 | } 23 | right--; 24 | break; 25 | case 2: 26 | for(int i=right;i>=left;i--){ 27 | res.add(mat[down][i]); 28 | } 29 | down--; 30 | break; 31 | case 3: 32 | for(int i=down;i>=top;i--){ 33 | res.add(mat[i][left]); 34 | } 35 | left++; 36 | break; 37 | } 38 | if(d==3) 39 | d=0; 40 | else 41 | d++; 42 | } 43 | return res; 44 | } 45 | } -------------------------------------------------------------------------------- /Sum-string/java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private String addStrings(String num1, String num2) { 3 | // code here 4 | StringBuilder ans=new StringBuilder(); 5 | int i=num1.length()-1,j=num2.length()-1; 6 | int carry=0; 7 | while(i>=0||j>=0||carry==1) 8 | { 9 | int v1=i>=0?num1.charAt(i)-'0':0; 10 | int v2=j>=0?num2.charAt(j)-'0':0; 11 | int sum=v1+v2+carry; 12 | carry=sum/10; 13 | ans.insert(0,sum%10); 14 | i--;j--; 15 | } 16 | return ans.toString(); 17 | } 18 | private boolean checkSeq(String s, int str, int len1, int len2){ 19 | String s1 = s.substring(str, str+len1); 20 | String s2 = s.substring(str+len1, str+len1+len2); 21 | String sum = addStrings(s1, s2); 22 | int sumLen = sum.length(); 23 | 24 | if(str+len1+len2+sumLen > s.length()){ 25 | return false; 26 | } 27 | if(sum.equals(s.substring(str+len1+len2, str+len1+len2+sumLen))){ 28 | if(str+len1+len2+sumLen == s.length()){ 29 | return true; 30 | } 31 | return checkSeq(s, str+len1, len2, sumLen); 32 | } 33 | return false; 34 | 35 | } 36 | public boolean isSumString(String s) { 37 | // code here 38 | int n = s.length(); 39 | for(int len1 = 1; len1< n; len1++){ 40 | for(int len2 = 1; len1 + len2 < n ; len2++){ 41 | if(checkSeq(s, 0, len1, len2)){ 42 | return true; 43 | } 44 | } 45 | } 46 | return false; 47 | } 48 | } -------------------------------------------------------------------------------- /Min Chars to Add for Palindrome/C++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector computeLPSArray(string str) { 4 | int M = str.length(); 5 | vector lps(M); 6 | 7 | int len = 0; 8 | lps[0] = 0; // lps[0] is always 0 9 | 10 | // the loop calculates lps[i] for i = 1 to M-1 11 | int i = 1; 12 | while (i < M) { 13 | if (str[i] == str[len]) { 14 | len++; 15 | lps[i] = len; 16 | i++; 17 | } else // (str[i] != str[len]) 18 | { 19 | // This is tricky. Consider the example. 20 | // AAACAAAA and i = 7. The idea is similar 21 | // to search step. 22 | if (len != 0) { 23 | len = lps[len - 1]; 24 | 25 | // Also, note that we do not increment 26 | // i here 27 | } else // if (len == 0) 28 | { 29 | lps[i] = 0; 30 | i++; 31 | } 32 | } 33 | } 34 | return lps; 35 | } 36 | 37 | int minChar(string& str) { 38 | // Write your code here 39 | string revStr = str; 40 | reverse(revStr.begin(), revStr.end()); 41 | 42 | // Get concatenation of string, special character 43 | // and reverse string 44 | string concat = str + "$" + revStr; 45 | 46 | // Get LPS array of this concatenated string 47 | vector lps = computeLPSArray(concat); 48 | 49 | // By subtracting last entry of lps vector from 50 | // string length, we will get our result 51 | return (str.length() - lps.back()); 52 | } 53 | }; -------------------------------------------------------------------------------- /Sum-string/c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | // Adds two numeric strings and returns 5 | // the sum as string 6 | string addStrings(string num1, string num2) { 7 | 8 | if (num1.length() < num2.length()) { 9 | swap(num1, num2); 10 | } 11 | 12 | int len1 = num1.length(); 13 | int len2 = num2.length(); 14 | string sum = ""; 15 | int carry = 0; 16 | 17 | // Add from least significant digits 18 | for (int i = 0; i < len2; i++) { 19 | int d1 = num1[len1 - 1 - i] - '0'; 20 | int d2 = num2[len2 - 1 - i] - '0'; 21 | int digit = (d1 + d2 + carry) % 10; 22 | carry = (d1 + d2 + carry) / 10; 23 | sum = char(digit + '0') + sum; 24 | } 25 | 26 | // Add remaining digits of num1 27 | for (int i = len2; i < len1; i++) { 28 | int d = num1[len1 - 1 - i] - '0'; 29 | int digit = (d + carry) % 10; 30 | carry = (d + carry) / 10; 31 | sum = char(digit + '0') + sum; 32 | } 33 | 34 | // Add remaining carry 35 | if (carry) { 36 | sum = char(carry + '0') + sum; 37 | } 38 | 39 | return sum; 40 | } 41 | 42 | // Recursively checks if the string from index 43 | // start is a valid sum-sequence 44 | bool checkSequence(string s, int start, int len1, int len2) { 45 | 46 | string part1 = s.substr(start, len1); 47 | string part2 = s.substr(start + len1, len2); 48 | string expectedSum = addStrings(part1, part2); 49 | 50 | int sumLen = expectedSum.length(); 51 | 52 | // If sum length exceeds remaining string, 53 | // return false 54 | if (start + len1 + len2 + sumLen > s.length()) { 55 | return false; 56 | } 57 | 58 | // If the sum matches the next part in string 59 | if (expectedSum == s.substr(start + len1 + len2, sumLen)) { 60 | 61 | // If end is reached, return true 62 | if (start + len1 + len2 + sumLen == s.length()) { 63 | return true; 64 | } 65 | 66 | // Recur for next pair: part2 and expectedSum 67 | return checkSequence(s, start + len1, len2, sumLen); 68 | } 69 | 70 | // Sum does not match the next segment 71 | return false; 72 | } 73 | 74 | // Function to check if a string is a sum-string 75 | bool isSumString(string s) { 76 | int n = s.length(); 77 | 78 | // Try all combinations of first two parts 79 | for (int len1 = 1; len1 < n; len1++) { 80 | for (int len2 = 1; len1 + len2 < n; len2++) { 81 | if (checkSequence(s, 0, len1, len2)) { 82 | return true; 83 | } 84 | } 85 | } 86 | 87 | return false; 88 | } 89 | }; --------------------------------------------------------------------------------