├── 139. Word Break ├── 198. House Robber ├── 300. Longest Increasing Subsequence ├── 322. Coin Change ├── Activity Selection ├── All numbers with specific difference ├── Amount of Water ├── Anonymous Functions - Python ├── Array Subset of another array ├── Array ├── All Unique Permutations of an array ├── Container With Most Water ├── Find Missing And Repeating ├── Find triplets with zero sum ├── K closest point to origin ├── K-th missing element ├── Longest Palindrome in a String ├── Majority Element ├── Matrix │ └── Is Sudoku Valid ├── Maximum Index ├── Maximum Product Subarray ├── Merge Sort │ ├── Count Smaller elements │ └── Surpasser Count ├── Missing Intervals ├── Next Permutation ├── Overlapping Intervals ├── Quick Sort │ └── Kth Smallest ├── Reverse an Array ├── Roof Top ├── Rotate a Matrix ├── Sliding Window │ ├── Count distinct elements in every window │ ├── Longest substring with distinct characters │ ├── Smallest subarray with sum greater than x │ └── Smallest window in a string containing all the characters of another string ├── Smallest Positive missing number ├── Stock Buy and Sell – Max one Transaction Allowed ├── Two Pointer │ ├── 3 Sum Closest │ └── Largest Pair Sum └── Union of Two Sorted Arrays ├── Average_Min_Max - Python ├── BinarySearch ├── Allocate Minimum Pages ├── Bike Racing ├── Binary Search ├── Find All Four Sum Numbers ├── Left most and right most index ├── Median of 2 Sorted Arrays of Different Sizes ├── Median of 2 Sorted Arrays of Same Size ├── Search in Rotated Sorted Array ├── Split Array Largest Sum ├── Square root └── The Painter's Partition Problem-II ├── Bit Difference ├── Bit MAgic └── Sum of XOR of all possible subsets ├── Bitwise Operators - Python ├── Black and White ├── C++ Data Types ├── Check if it is possible to survive on Island ├── Check the status - Python ├── Classes and Objects - Python ├── Closest Three Sum ├── Coins and Game ├── Combination Sum ├── Comment in Python ├── Comments in C ├── Comparison Operators - Python ├── Convert Ternary Expression to Binary Tree ├── Count Even Odd - Python ├── Count distinct elements in every window ├── Count total set bits ├── Counting elements in two arrays ├── Dictionary in Python - II ├── Dictionary in Python - III ├── Divide And Conquer ├── Allocate minimum number of pages ├── Merge Sort └── The Nth Fibonnaci ├── Dynamic Programming ├── 0 - 1 Knapsack Problem ├── Bits Counting ├── Boolean Parenthesization ├── Check for subsequence ├── Coin Change (Max no. of ways) ├── Count all possible paths from top left to bottom right ├── Count number of hops ├── Count of subsets with given sum ├── Cutting Binary String ├── Diameter of Binary Tree ├── Distinct occurrences ├── Edit Distance ├── Egg Dropping Puzzle ├── Form a palindrome ├── Form a palindrome (Minimum number of insertions in a string to make it a palindrome) ├── Interleaved Strings ├── Knapsack with Duplicate Items (Unbounded knapsack) ├── Largest Divisible Subset ├── Largest square formed in a matrix ├── Longest Arithmetic Subsequence ├── Longest Common Subsequence ├── Longest Common Substring ├── Longest Palindromic Subsequence ├── Longest Prefix Suffix ├── Longest Repeating Subsequence ├── Longest consecutive subsequence ├── Matrix Chain Multiplication ├── Max length chain ├── Max rectangle ├── Maximum path sum from any node ├── Min cut Square ├── Minimum Deletions (to make a string palindromic) ├── Minimum Operations ├── Minimum number of deletions and insertions. ├── Minimum sum partition ( Minimum subset sum difference)) ├── Nth Fibonacci Number ├── Number of Coins (Min no. of coins) ├── Paint N House ├── Palindromic Partitioning ├── Palindromic patitioning ├── Partition Equal Subset Sum ├── Perfect Sum Problem (count of subset sum) ├── Pots of Gold Game ├── Print Longest Common Subsequence ├── Print Shortest common Supersequence ├── Print first n Fibonacci Numbers ├── Reach the Nth point ├── Rod Cutting ├── Scramble String ├── Shortest Common Supersequence ├── Shortest XY distance in Grid ├── Special Keyboard ├── Stickler Thief ├── Subset Sum Problem ├── Wildcard Pattern Matching ├── Word Break └── target sum - Leetcode ├── Element that appears once where every element occurs twice ├── Equilibrium point ├── Examination Papers ├── Fact Digit Sum ├── Find Immediate Smaller Than X ├── Find Pair Given Difference ├── Find Smallest Missing in Sorted ├── Find first set bit ├── Find the Highest number ├── Find the closest number ├── Find the element that appears once in sorted array ├── Find the median ├── Finding Position ├── Finding Profession ├── First Repeating Element ├── First and last occurrences of X ├── For Loop 2- Python ├── For loop - Python ├── Format specifier - C ├── Fractional Knapsack ├── Functions - Python ├── Functions in Lists - Python ├── G.F Series ├── Game of Death in a circle ├── Generate IP Addresses ├── Graph ├── Alien Dictionary ├── Articulation Point ├── BFS ├── Bellman Ford ├── Bipartite Graph ├── Bridge Edge in a graph ├── Clone an Undirected Graph ├── Course Schedule ├── DFS ├── Detect cycle in a directed graph ├── Detect cycle in an undirected graph ├── Dijkstra Algorithm ├── Find number of closed islands ├── Find the number of islands ├── Find whether path exist ├── Flood fill Algorithm ├── Knight Walk ├── Kosaraju's Algo: Strongly Connected Components ├── Minimum Cost Path ├── Minimum Spanning Tree - PRIM'S ALGORITHM ├── Number Of Enclaves ├── Number of Provinces ├── Open the gates ├── Prerequisite Tasks ├── Replace O's with X's ├── Rotten Oranges ├── Snake and Ladder Problem ├── Topological Sort ├── Unit Area of largest region of 1's ├── Word Boggle ├── Word Ladder I ├── Word Ladder II └── X Total Shapes ├── Greedy ├── Jump Game ├── Minimum Platforms ├── Minimum number of jumps └── Stock buy and sell ├── Help the Old Man!!! ├── Hungry Pizza Lovers ├── Immediate Smaller Element ├── Increment and Decrement - Python ├── Increment and decrement - C ├── Input\Output - C ├── Intro to Dictionary - Python ├── Intro to Lists - Python ├── Inversion of array ├── Is Binary Number Multiple of 3 ├── Is and In Operator ├── Ishaan Loves Chocolates ├── Iterating through Lists - Python ├── Job Sequencing Problem ├── Josephus problem ├── K-th element of two sorted Arrays ├── Kadane's Algorithm ├── Kadane's Algorithm New ├── Largest Permutation ├── Largest number in K swaps ├── Largest number possible ├── Largest number with given sum ├── Last non-zero digit in factorial ├── Leaders in an array ├── Linked List ├── Add two numbers represented by linked lists ├── Check If Circular Linked List ├── Check if Linked List is Palindrome ├── Circular Linked List Traversal ├── Count nodes of linked list ├── Delete Alternate Nodes ├── Delete a Node in Single Linked List ├── Delete node in Doubly Linked List ├── Delete without head pointer ├── Detect Loop in linked list ├── Doubly linked list Insertion at given position ├── Find n upon k th node in Linked list ├── Find the Sum of Last N nodes of the Linked List ├── Finding middle element in a linked list ├── Identical Linked Lists ├── Implement Stack using Linked List ├── Insert in Middle of Linked List ├── Intersection Point in Y Shapped Linked Lists ├── LRU Cache ├── Linked List Insertion ├── Linked List Length Even or Odd? ├── Linked List Matrix ├── Merge two sorted linked lists ├── Modular Node ├── Node at a given index in linked list ├── Nth node from end of linked list ├── Print Linked List elements ├── Remove duplicate element from sorted Linked List ├── Remove loop in Linked List ├── Repetitive Addition Of Digits ├── Reverse a Linked List in groups of given size ├── Reverse a linked list ├── Rotate a Linked List └── Subtract 1 from number represented as Linked list ├── Logical Operators - Python ├── Logical operator in C ├── Longest Span with same Sum in two Binary arrays ├── Longest subarray with sum divisible by K ├── Love For The Twins ├── Map ├── Check if two strings are k-anagrams or not ├── Count pairs with given sum ├── Frequency Game ├── Key Pair ├── Max distance between same elements └── Unique Number of Occurrences ├── Mark Even and Odd - Python ├── Math ├── Bit Difference ├── Construct list using given q XOR queries ├── Modular Exponentiation for large numbers ├── Nth Natural Number ├── Number following a pattern ├── Plus One ├── Single Element Among Triplets ├── String's Count └── Sum of bit differences ├── Matrix Chain Multiplication ├── Max Sum Subarray of size K ├── Maximize Toys ├── Maximum sum of increasing order elements from n arrays ├── Maximum sum of subarray less than or equal to x ├── Merge Without Extra Space ├── Merge and Sort ├── Message Spreading ├── Minimum Number in a sorted rotated array ├── Missing number in array ├── Modules ├── N meetings in one room ├── N-Queen Problem ├── Next Happy Number ├── Non Repeating Character ├── Non-Repeating Element ├── Number of Unique Paths ├── Number of paths ├── Operators in C ├── Operators in Python ├── Page Faults in LRU ├── Palindrome numbers ├── Palindromic patitioning ├── Parenthesis Checker ├── Pattern_Printing └── Print the pattern | Set-1 ├── Peak element ├── Permutations of a given string ├── Power of 2 ├── Prime number of set bits ├── Print Pattern ├── Print this pattern! ├── Queue ├── C++ STL | Set 5 (queue) ├── Card Rotation ├── Chinky and diamonds ├── Circular tour ├── Count the Reversals ├── Find median in a stream ├── First negative integer in every window of size k ├── Generate Binary Numbers ├── Implement Queue using Linked List ├── Implement Queue using array ├── Min Heap implementation ├── Min sum formed by digits ├── Minimum Cost of ropes ├── Nearly sorted ├── Queue Push & Pop ├── Queue Reversal ├── Queue using two Stacks ├── Reverse First K elements of Queue └── Stack using two queues ├── Quick Sort ├── Raju and coins ├── Rat Maze With Multiple Jumps ├── Rat in a Maze Problem - I ├── Rearrange an array with O(1) extra space ├── Recaman’s sequence ├── Regex - Python ├── Regular Expressions 2 - Python ├── Remove all duplicates from a given string ├── Repeat the Strings - Python ├── Repetitive Printing - Python ├── Replace a word ├── Reverse an Array ├── Reverse array in groups ├── Reverse words in a given string ├── Root to leaf paths sum ├── Rotate Array ├── Search in a Rotated Array ├── Search in a matrix ├── Set in Python - I ├── Set in Python - II ├── Shop in Candy Store ├── Shuffle integers ├── Slicing in String - Python ├── Smallest Positive missing number ├── Smallest number ├── Smallest number with sum of digits as N and divisible by 10^N ├── Solve the Sudoku ├── Sorting in Lists - Python ├── Space Seperated - Python ├── Split the input - Python ├── Stack ├── Decode the string ├── Delete array elements which are smaller than next or become smaller ├── Delete middle element of a stack ├── Easy string ├── Evaluation of Postfix Expression ├── Get min at pop ├── Get minimum element from stack ├── Histogram Max Rectangular Area ├── Implement stack using array ├── Implement two stacks in an array ├── Infix to Postfix ├── Longest valid Parentheses ├── Max sum in sub-arrays ├── Maximum Difference ├── Maximum Rectangular Area in a Histogram ├── Maximum of minimum for every window size ├── Next larger element ├── Pairwise Consecutive Elements ├── Parenthesis Checker ├── Print Bracket Number ├── Remove repeated digits in a given number ├── Reverse a string using Stack ├── Save Gotham! ├── Smallest number on left ├── Sort a stack ├── Special Stack ├── Stack designer ├── Stock span problem ├── String Manipulation ├── The Celebrity Problem └── Valid Substring ├── Start Coding - Python ├── Start coding - C ├── String Functions - II - Python ├── String Functions I - Python ├── String ├── Find and Replace in String ├── Find largest word in dictionary ├── Generate Parentheses ├── Generate binary string ├── Group Shifted String ├── Implement Atoi ├── Isomorphic Strings ├── KMP │ ├── Minimum repeat to make substring │ ├── Minimum times A has to be repeated such that B is a substring of it │ └── Repeated String Match ├── Length of the longest substring ├── License Key Formatting ├── Longest K unique characters substring ├── Meta Strings ├── Minimum sum ├── Multiply two strings ├── Remove b and ac from a given string ├── String rp or pr └── Validate an IP Address ├── Subarray with 0 sum ├── Subarray with given sum ├── Subarray with given sum new ├── Subset Sums ├── Subsets ├── Swap and Maximize ├── Taking input - Python ├── Taking input and typecasting - Python ├── The new line - C ├── Tower of Hanoi ├── Trapping Rain Water ├── Tree ├── Ancestors in Binary Tree ├── BST │ ├── Add all greater values to every node in a BST │ ├── Array to BST │ ├── Check for BST │ ├── Construct BST from Postorder │ ├── Count BST nodes that lie in a given range │ ├── Delete a node from BST │ ├── Expression Tree │ ├── Find a pair with given target in BST │ ├── Find the Closest Element in BST │ ├── Inorder Successor in BST │ ├── Insert a node in a BST │ ├── Kth largest element in BST │ ├── Largest BST │ ├── Lowest Common Ancestor in a BST │ ├── Minimum element in BST │ ├── Print BST elements in given range │ ├── Search a node in BST │ ├── Serialize and Deserialize a Binary Tree │ └── k-th smallest element in BST ├── Binary Tree to CDLL ├── Binary Tree to DLL ├── Bottom View of Binary Tree ├── Boundary Traversal of binary tree ├── Check for Balanced Tree ├── Check if subtree ├── Check if two Nodes are Cousins ├── Connect Nodes at Same Level ├── Connect Nodes at Same Level Of Tree ├── Construct Binary Tree from Parent Array ├── Construct Tree from Inorder & Preorder ├── Count Leaves in Binary Tree ├── Count Non-Leaf Nodes in Tree ├── Count Number of SubTrees having given Sum ├── Determine if Two Trees are Identical ├── Diagonal Traversal of Binary Tree ├── Diameter of Binary Tree ├── Does array represent Heap ├── Duplicate Subtree ├── Full Binary Tree from Preorder and Postorder - Lalit Sir ├── Height of Binary Tree ├── Height of Heap ├── Inorder Traversal ├── Inorder Traversal (Iterative) ├── K distance from root ├── Kth Ancestor in a Tree ├── Left View of Binary Tree ├── Level order traversal ├── Level order traversal Line by Line ├── Level order traversal in spiral form ├── Lowest Common Ancestor in a Binary Tree ├── Make Binary Tree From Linked List ├── Maximum Path Sum between 2 Leaf Nodes ├── Maximum Width of Tree ├── Maximum difference between node and its ancestor ├── Maximum sum leaf to root path ├── Maximum sum of Non-adjacent nodes ├── Min distance between two given nodes of a Binary Tree ├── Minimum Depth of a Binary Tree ├── Mirror Tree ├── Populate Inorder Successor for all nodes ├── Postorder Traversal ├── Postorder Traversal (Iterative) ├── Preorder Traversal ├── Preorder traversal (Iterative) ├── Print all nodes that don't have sibling ├── Remove Half Nodes ├── Reverse Level Order Traversal ├── Right View of Binary Tree ├── Root to Leaf Paths ├── Root to leaf path sum ├── Size of Binary Tree ├── Sum Tree ├── Sum of Binary Tree ├── Symmetric Tree ├── Top View of Binary Tree ├── Transform to Sum Tree ├── Tree from Postorder and Inorder ├── Vertical Traversal of Binary Tree └── ZigZag Tree Traversal ├── Two Mirror Trees ├── Variable Arguments - Python ├── Welcome aboard - Python ├── Winner of an election ├── Zero Converter - python ├── getchar and putchar - C ├── module 1 contest ├── module 2 contest ├── module 3 - contest ├── module 4 - contest ├── module 5 - contest └── sep and end in Print() /139. Word Break: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, vector& wordDict) { 4 | int n = s.size(); 5 | vector dp(n+1,false); 6 | dp[0]=true; 7 | unordered_set words(wordDict.begin(),wordDict.end()); 8 | for(int i=1;i<=n;i++){ 9 | for(int j=0;j<=i;j++){ 10 | if(dp[j] && words.count(s.substr(j,i-j))){ 11 | dp[i]=true; 12 | break; 13 | } 14 | } 15 | } 16 | 17 | return dp[n]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /198. House Robber: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n=nums.size(); 5 | if(n==1) return nums[0]; 6 | int prev2=0,prev = nums[0]; 7 | for(int i=1;i1) pick+=prev2; 10 | int notPick = prev; 11 | int curr = max(pick,notPick); 12 | prev2=prev; 13 | prev=curr; 14 | } 15 | return prev; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /300. Longest Increasing Subsequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | if(nums.size()<=1) return nums.size(); 5 | vector dp(nums.size(),0); 6 | dp[0]=1,dp[1]=1; 7 | for(int i=1; inums[j]){ 11 | dp[i] =max(dp[i] , 1+dp[j]); 12 | } 13 | } 14 | } 15 | return *max_element(dp.begin(),dp.end()); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /322. Coin Change: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | vector dp(amount+1,INT_MAX); 5 | dp[0]=0; 6 | sort(coins.begin(),coins.end()); 7 | for(int i=1;i<=amount;i++){ 8 | for(int c: coins){ 9 | if(i-c<0) break; 10 | if(dp[i-c] != INT_MAX) dp[i] = min(dp[i],1+dp[i-c]); 11 | } 12 | } 13 | return (dp[amount]==INT_MAX) ? -1 : dp[amount]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Activity Selection: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct activity{ 4 | int start , finish; 5 | }; 6 | bool comp(activity s1 , activity s2){ 7 | return (s1.finish < s2.finish); 8 | } 9 | int main() 10 | { 11 | int t; 12 | scanf("%d",&t); 13 | while(t--){ 14 | int n; 15 | cin >> n; 16 | activity arr[n]; 17 | for(int i =0;i> arr[i].start; 18 | for(int i =0;i> arr[i].finish; 19 | sort(arr,arr+n,comp); 20 | int count=1,j=0; 21 | for(int i=1;i= arr[j].finish){ 23 | j=i; 24 | count++; 25 | } 26 | } 27 | cout << count << endl; 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /All numbers with specific difference: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | scanf("%d", &t); 7 | while (t--) { 8 | int n, d, i, count = 0; 9 | cin >> n >> d; 10 | int l = 0, r = n - 1, mid; 11 | while (l <= r) { 12 | mid = l + (r - l) / 2; 13 | int temp = mid, sum = 0; 14 | while (temp > 0) { 15 | sum += temp % 10; 16 | temp /= 10; 17 | } 18 | if ((mid - sum) < d) { 19 | l = mid + 1; 20 | } 21 | else { 22 | count = n - mid + 1; 23 | r = mid - 1; 24 | } 25 | } 26 | cout << count << endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Anonymous Functions - Python: -------------------------------------------------------------------------------- 1 | power = lambda a,b: a**b##write the lambda expression in one line here 2 | -------------------------------------------------------------------------------- /Array/All Unique Permutations of an array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void recurPerm(int idx, vector &arr, int n, set> &ans){ 4 | if(idx==n){ 5 | ans.insert(arr); 6 | return; 7 | } 8 | for(int i = idx;i> uniquePerms(vector &arr ,int n) { 16 | set> ans; 17 | sort(arr.begin(),arr.end()); 18 | recurPerm(0,arr,n,ans); 19 | vector> res; 20 | for(auto it: ans){ 21 | res.push_back(it); 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Array/Container With Most Water: -------------------------------------------------------------------------------- 1 | long long maxArea(long long A[], int len) 2 | { 3 | int l=0, r = len-1; 4 | long long ans=0; 5 | while(lsum) hi--; 14 | else lo++; 15 | } 16 | } 17 | return false; 18 | } 19 | -------------------------------------------------------------------------------- /Array/K closest point to origin: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool static cmp (vector &x, vector &y){ 4 | int dis1 = x[0]*x[0] + x[1]*x[1]; 5 | int dis2 = y[0]*y[0] + y[1]*y[1]; 6 | if(dis1!=dis2) return dis1> kClosest(vector>& arr, int K) { 11 | sort(arr.begin(), arr.end(), cmp); 12 | vector> ans(arr.begin(), arr.begin() + K); 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/K-th missing element: -------------------------------------------------------------------------------- 1 | int num = -1; 2 | for(int i=0; k>0&&i1){ 5 | num = arr[i]; 6 | while(k>0&&diff>1){ 7 | num ++; 8 | k--; 9 | diff--; 10 | 11 | } 12 | } 13 | 14 | } 15 | if(k!=0){ 16 | return -1; 17 | } 18 | return num; 19 | -------------------------------------------------------------------------------- /Array/Majority Element: -------------------------------------------------------------------------------- 1 | int majorityElement(int a[], int n) 2 | { 3 | int ans=a[0],c=1; 4 | for(int i=0;in/2)?ans:-1; 17 | } 18 | -------------------------------------------------------------------------------- /Array/Maximum Index: -------------------------------------------------------------------------------- 1 | int maxIndexDiff(int arr[], int n) { 2 | vector v_min(n),v_max(n); 3 | v_min[0]=arr[0]; 4 | v_max[n-1]=arr[n-1]; 5 | for(int i=1;i arr, int n) { 6 | long long maxProduct = arr[0]; 7 | long long minProduct = arr[0]; 8 | long long ans = arr[0]; 9 | for(int i =1;i> missingIntervals(vector &arr, int l, int r) { 2 | vector> ans; 3 | int n=arr.size(); 4 | if (l < arr[0]) { 5 | ans.push_back({l, arr[0] - 1}); 6 | } 7 | for(int i=1;i arr[i - 1] + 1) { 9 | ans.push_back({arr[i - 1] + 1, arr[i] - 1}); 10 | } 11 | } 12 | if(r>arr[n-1]){ 13 | ans.push_back({arr[n-1]+1,r}); 14 | } 15 | if(ans.empty()) ans.push_back({-1,-1}); 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Array/Next Permutation: -------------------------------------------------------------------------------- 1 | vector nextPermutation(vector arr) { 2 | int n = arr.size(),i,j; 3 | for(i = n-2;i>=0;i--){ 4 | if(arr[i]i;j--){ 13 | if(arr[j]>arr[i]){ 14 | break; 15 | } 16 | } 17 | swap(arr[i],arr[j]); 18 | reverse(arr.begin()+i+1,arr.end()); 19 | } 20 | r 21 | -------------------------------------------------------------------------------- /Array/Overlapping Intervals: -------------------------------------------------------------------------------- 1 | vector> overlappedInterval(vector>& intervals) { 2 | sort(intervals.begin(),intervals.end()); 3 | vector> ans; 4 | ans.push_back(intervals[0]); 5 | for(int i=1;i &arr) { 2 | int left = 0, right = arr.size() - 1; 3 | while (left < right) { 4 | swap(arr[left], arr[right]); 5 | left++; 6 | right--; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Array/Roof Top: -------------------------------------------------------------------------------- 1 | int maxStep(vector& arr) { 2 | int cnt=0,maxCnt=INT_MIN, n=arr.size(); 3 | for(int i=1;iarr[i-1] ) { 5 | cnt++; 6 | } 7 | else{ 8 | maxCnt = max(maxCnt,cnt); 9 | cnt=0; 10 | } 11 | } 12 | return max(maxCnt,cnt) ; 13 | } 14 | -------------------------------------------------------------------------------- /Array/Rotate a Matrix: -------------------------------------------------------------------------------- 1 | void rotateMatrix(vector>& arr, int n) { 2 | for(int i=0;i countDistinct(vector &arr, int k) { 2 | int n = arr.size(); 3 | unordered_map mp; 4 | vector res; 5 | int l=0,r=0; 6 | for(r=0;r=k-1){ 9 | res.push_back(mp.size()); 10 | mp[arr[l]]--; 11 | if(mp[arr[l]]==0) 12 | mp.erase(arr[l]); 13 | l++; 14 | } 15 | } 16 | return res; 17 | } 18 | -------------------------------------------------------------------------------- /Array/Sliding Window/Longest substring with distinct characters: -------------------------------------------------------------------------------- 1 | int longestUniqueSubstr(string &s) { 2 | int ans=0; 3 | int n = s.size(); 4 | int l=-1,i; 5 | unordered_map mp; 6 | for(i=0;i& arr) { 2 | int l=0,r=0; 3 | int n=arr.size(), sum=0, minLen=INT_MAX; 4 | while(rx){ 7 | minLen=min(minLen,r-l+1); 8 | sum-=arr[l]; 9 | l++; 10 | } 11 | r++; 12 | } 13 | return (minLen == INT_MAX)? 0:minLen; 14 | } 15 | -------------------------------------------------------------------------------- /Array/Smallest Positive missing number: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find the smallest positive number missing from the array. 5 | int missingNumber(int arr[], int n) 6 | { 7 | sort(arr,arr+n); 8 | int t=0; 9 | for(int i=0;i &prices) { 2 | int maxi = 0; 3 | int minLeft = prices[0]; 4 | for(int i=1;i &arr) { 2 | int l=0,r=arr.size()-1,sum=0; 3 | while(l=L){ 12 | fast+=H[i]+A[i]*mid; 13 | } 14 | } 15 | if(fast>=M){ 16 | ans=mid; 17 | high=mid-1; 18 | }else{ 19 | low=mid+1; 20 | // fast=0; 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /BinarySearch/Binary Search: -------------------------------------------------------------------------------- 1 | int bin_search(int A[], int left, int right, int k) 2 | { 3 | if(left>right){ 4 | return -1; 5 | } 6 | int mid=left+(right-left)/2; 7 | if(A[mid]==k) return mid; 8 | if(k 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin >> t; 7 | while(t--){ 8 | int a,b; 9 | cin >> a>>b; 10 | int x=a^b; 11 | int count=0; 12 | while(x){ 13 | x=x&(x-1); 14 | count++; 15 | } 16 | cout << count< 2 | using namespace std; 3 | 4 | int main() { 5 | int a; 6 | char b; 7 | float c; 8 | cin>>a>>b>>c; 9 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int s,n,m; 9 | cin >> s >> n >> m; 10 | int req = s*m,day=s-(s/7); 11 | if(day*n < req || n0 and b<0): 13 | return True 14 | elif(b>0 and a<0): 15 | return True 16 | else: 17 | return False 18 | -------------------------------------------------------------------------------- /Coins and Game: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,k; 9 | cin >> n >>k; 10 | cout << n-((k-1)/2) << " "; 11 | for(int i=1;ib) ##do a>b 4 | print(a!=b) ##do a!=b 5 | print(a countDistinct (int arr[], int n, int k) 2 | { 3 | int i, count; 4 | unordered_map hash; 5 | vector c; 6 | for (int i = 0; i < n - k + 1; i++) { 7 | hash.clear(); 8 | count = 1; 9 | hash[arr[i]] = 1; 10 | for (int j = i; j < i + k; j++) { 11 | if (hash[arr[j]] != 1) { 12 | hash[arr[j]] = 1; 13 | count++; 14 | } 15 | } 16 | c.push_back(count); 17 | } 18 | return c; 19 | } 20 | -------------------------------------------------------------------------------- /Count total set bits: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin >>t; 7 | while(t--){ 8 | int n,bits=0; 9 | cin >>n; 10 | for(int i=0;i<=n;i++){ 11 | int temp = i; 12 | int count=0; 13 | while(temp){ 14 | temp=temp&(temp-1); 15 | count++; 16 | } 17 | bits+=count; 18 | } 19 | cout< countBits(int n) { 2 | 3 | vector ans(n + 1, 0); 4 | 5 | for (int i = 1; i <= n; i++) { 6 | ans[i] = ans[i>>1] + (i & 1); 7 | } 8 | 9 | return ans; 10 | } 11 | -------------------------------------------------------------------------------- /Dynamic Programming/Coin Change (Max no. of ways): -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | long long int count( int coin[], int n, int sum ) 5 | { 6 | long long t[n+1][sum+1]; 7 | for(int i=0;i<=n;i++){ 8 | for(int j=0;j<=sum;j++){ 9 | if(i==0) t[i][j]=0; 10 | if(j==0) t[i][j]=1; 11 | } 12 | } 13 | for(int i=1;i<=n;i++){ 14 | for(int j=1;j<=sum;j++){ 15 | if(coin[i-1]<=j){ 16 | t[i][j]=t[i-1][j]+t[i][j-coin[i-1]]; 17 | } 18 | else{ 19 | t[i][j]=t[i-1][j]; 20 | } 21 | } 22 | } 23 | return t[n][sum]; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/Count number of hops: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to count the number of ways in which frog can reach the top. 5 | long long countWays(int n) 6 | { 7 | long long int prev=1, prev1=1, prev2=0; 8 | for(int i=2;i<=n;i++){ 9 | long long int cur = (prev+prev1+prev2) % 1000000007; 10 | prev2=prev1; 11 | prev1=prev; 12 | prev=cur; 13 | } 14 | return prev%1000000007; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/Count of subsets with given sum: -------------------------------------------------------------------------------- 1 | Class Solution{ 2 | public: 3 | int perfectSum(int arr[], int n, int sum) 4 | { 5 | int t[n+1][sum+1]; 6 | for(int i=0;i<=n;i++){ 7 | for(int j=0;j<=sum;j++){ 8 | if(i==0) t[i][j]=0; 9 | if(j==0) t[i][j]=1; 10 | } 11 | } 12 | for(int i=1;i<=n;i++){ 13 | for(int j=1;j<=sum;j++){ 14 | if(arr[i-1]<=j){ 15 | t[i][j]=(t[i-1][j]+t[i-1][j-arr[i-1]]); 16 | } 17 | else t[i][j]=t[i-1][j]; 18 | } 19 | } 20 | return t[n][sum]; 21 | } 22 | 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/Diameter of Binary Tree: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to return the diameter of a Binary Tree. 5 | int solve(Node* root,int &res){ 6 | if(!root) return 0; 7 | int l=solve(root->left,res); 8 | int r=solve(root->right,res); 9 | int temp=1+max(l,r); 10 | int ans=max(temp,1+l+r); 11 | res = max(res,ans); 12 | return temp; 13 | } 14 | int diameter(Node* root) 15 | { 16 | int res=INT_MIN; 17 | solve(root,res); 18 | return res; 19 | } 20 | 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Distinct occurrences: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | const int mod = 1000000007; 5 | int subsequenceCount(string s, string t) 6 | { 7 | int n = s.length(); 8 | int m = t.length(); 9 | vector> dp(n+1,vector (m+1,0)); 10 | for(int i=0;i<=n;i++) dp[i][0] = 1; 11 | for(int i=1;i<=n;i++){ 12 | for(int j=1;j<=m;j++){ 13 | if(s[i-1] == t[j-1]){ 14 | dp[i][j] = dp[i-1][j-1] % mod ; 15 | } 16 | 17 | dp[i][j] += dp[i-1][j]%mod; 18 | } 19 | } 20 | return dp[n][m]%mod; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Dynamic Programming/Edit Distance: -------------------------------------------------------------------------------- 1 | int editDistance(string str1, string str2) { 2 | 3 | int n = str1.size(); 4 | int m = str2.size(); 5 | vector> dp(n+1,vector(m+1,0)); 6 | 7 | for(int i=0;i<=n;i++) dp[i][0] = i; 8 | for(int j=0;j<=m;j++) dp[0][j] = j; 9 | 10 | for(int i=1;i<=n;i++){ 11 | for(int j=1;j<=m;j++){ 12 | if(str1[i-1] == str2[j-1]){ 13 | dp[i][j] = dp[i-1][j-1]; 14 | } 15 | else{ 16 | dp[i][j] = 1 + min ( dp[i-1][j], min( dp[i][j-1], dp[i-1][j-1])); 17 | } 18 | } 19 | } 20 | 21 | return dp[n][m]; 22 | } 23 | -------------------------------------------------------------------------------- /Dynamic Programming/Egg Dropping Puzzle: -------------------------------------------------------------------------------- 1 | int solve (int n, int k,vector> &dp ){ 2 | if(n==0) 3 | return 0; 4 | if(n==1 || k==0 || k==1) 5 | return k; 6 | if(dp[n][k] != -1) 7 | return dp[n][k]; 8 | int ans = INT_MAX; 9 | for(int i=1;i<=k;i++){ 10 | int step = 1+ max(solve(n-1,i-1,dp), solve(n,k-i,dp)); 11 | ans = min(ans,step); 12 | } 13 | return dp[n][k] = ans; 14 | 15 | } 16 | int eggDrop(int n, int k) 17 | { 18 | vector> dp(n+1,vector(k+1,-1)); 19 | return solve(n,k,dp); 20 | } 21 | -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack with Duplicate Items (Unbounded knapsack): -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int knapSack(int N, int W, int val[], int wt[]) 4 | { 5 | int t[N+1][W+1]; 6 | for(int i=0;i<=N;i++){ 7 | for(int j=0;j<=W;j++){ 8 | if(i==0 || j==0) t[i][j]=0; 9 | } 10 | } 11 | for(int i=1;i<=N;i++){ 12 | for(int j=1;j<=W;j++){ 13 | if(wt[i-1]<=j){ 14 | t[i][j]=max(t[i-1][j],val[i-1]+t[i][j-wt[i-1]]); 15 | } 16 | else t[i][j]=t[i-1][j]; 17 | } 18 | } 19 | return t[N][W]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Largest square formed in a matrix: -------------------------------------------------------------------------------- 1 | int maxSquare(int n, int m, vector> mat) { 2 | vector> dp(n,vector(m,0)); 3 | int maxSquare=0; 4 | for(int i=0;i& arr) { 2 | int n = arr.size(); 3 | int maxi = 1; 4 | vector> dp(n,vector(arr[n-1]-arr[0]+1, 1)); 5 | for(int i=0;i=0;j--){ 7 | int diff = arr[i]-arr[j]; 8 | dp[i][diff] = dp[j][diff] +1; 9 | maxi = max(maxi, dp[i][diff]); 10 | } 11 | } 12 | return maxi; 13 | } 14 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Common Substring: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | int longestCommonSubstr (string S1, string S2, int n, int m) 5 | { 6 | int t[n+1][m+1]; 7 | int ans=0; 8 | for(int i=0;i<=n;i++){ 9 | for(int j=0;j<=m;j++){ 10 | if(i==0 || j==0) t[i][j]=0; 11 | } 12 | } 13 | for(int i=1;i<=n;i++){ 14 | for(int j=1;j<=m;j++){ 15 | if(S1[i-1]==S2[j-1]){ 16 | t[i][j]=1+t[i-1][j-1]; 17 | ans=max(ans,t[i][j]); 18 | } 19 | else 20 | t[i][j]=0; 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Palindromic Subsequence: -------------------------------------------------------------------------------- 1 | int longestPalinSubseq (string S) 2 | { 3 | string a=S; 4 | reverse(S.begin(),S.end()); 5 | string b=S; 6 | int n=S.length(); 7 | int t[n+1][n+1]; 8 | for(int i=0;i<=n;i++){ 9 | for(int j=0;j<=n;j++){ 10 | if(i==0 || j==0) 11 | t[i][j] = 0; 12 | else if(a[i-1]==b[j-1]) 13 | t[i][j] = 1+t[i-1][j-1]; 14 | else 15 | t[i][j] = max(t[i-1][j],t[i][j-1]); 16 | } 17 | } 18 | return t[n][n]; 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Repeating Subsequence: -------------------------------------------------------------------------------- 1 | int LongestRepeatingSubsequence(string &str) { 2 | string p=str; 3 | int n=str.size(); 4 | vector>dp(n+1,vector(n+1,0)); 5 | for(int i=1;i<=n;i++){ 6 | for(int j=1;j<=n;j++){ 7 | if(str[i-1]==p[j-1] and i!=j)dp[i][j]=1+dp[i-1][j-1]; 8 | else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 9 | } 10 | } 11 | return dp[n][n]; 12 | } 13 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest consecutive subsequence: -------------------------------------------------------------------------------- 1 | int dp[100005]; 2 | 3 | //Function to return length of longest subsequence of consecutive integers. 4 | int findLongestConseqSubseq(int arr[], int N) 5 | { 6 | int ans=0; 7 | sort(arr,arr+N); 8 | for(int i=0;i<100005;i++) dp[i]=0; 9 | for(int i=0;ix.second); 3 | } 4 | int maxChainLen(struct val p[],int n) 5 | { 6 | sort(p,p+n,cmp); 7 | int dp[n]; 8 | for(int i=0;ip[j].second){ 12 | if(dp[i]s) s=dp[i]; 19 | } 20 | return s; 21 | } 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Maximum path sum from any node: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //Function to return maximum path sum from any node in a tree. 4 | int solve(Node* root,int &res){ 5 | if(!root) return 0; 6 | int l=solve(root->left,res); 7 | int r=solve(root->right,res); 8 | int temp=max(max(l,r)+root->data,root->data); 9 | int ans=max(temp,l+r+root->data); 10 | res=max(res,ans); 11 | return temp; 12 | } 13 | int findMaxSum(Node* root) 14 | { 15 | int res=INT_MIN; 16 | solve(root,res); 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Min cut Square: -------------------------------------------------------------------------------- 1 | int getSquaresCount(int r, int c,vector> &dp){ 2 | if(r==c) return dp[r][c] = 1; 3 | if(r<0 || c<0) return 1e9; 4 | if(dp[r][c] != -1) return dp[r][c]; 5 | int t1 = INT_MAX, t2=INT_MAX; 6 | for(int i=1;i> dp (M+1, vector (N+1,-1)); 19 | getSquaresCount(M,N,dp); 20 | return dp[M][N]; 21 | } 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Minimum Deletions (to make a string palindromic): -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int minimumNumberOfDeletions(string S) { 4 | string a=S; 5 | reverse(S.begin(),S.end()); 6 | string b=S; 7 | int n=S.length(); 8 | int t[n+1][n+1]; 9 | for(int i=0;i<=n;i++){ 10 | for(int j=0;j<=n;j++){ 11 | if(i==0 || j==0) 12 | t[i][j] = 0; 13 | else if(a[i-1]==b[j-1]) 14 | t[i][j] = 1+t[i-1][j-1]; 15 | else 16 | t[i][j] = max(t[i-1][j],t[i][j-1]); 17 | } 18 | } 19 | return n-t[n][n]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Minimum Operations: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minOperation(int n) 5 | { 6 | int cnt=0,i=n; 7 | while(i){ 8 | if(i%2==0){ 9 | i/=2; 10 | cnt++; 11 | } 12 | else{ 13 | i-=1; 14 | cnt++; 15 | } 16 | } 17 | return cnt; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Minimum number of deletions and insertions.: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | public: 5 | int minOperations(string str1, string str2) 6 | { 7 | int x=str1.length(); 8 | int y=str2.length(); 9 | int t[x+1][y+1]; 10 | for(int i=0;i<=x;i++){ 11 | for(int j=0;j<=y;j++){ 12 | if(i==0 || j==0) t[i][j] = 0; 13 | } 14 | } 15 | for(int i=1;i<=x;i++){ 16 | for(int j=1;j<=y;j++){ 17 | if(str1[i-1]==str2[j-1]) t[i][j]=1+t[i-1][j-1]; 18 | else t[i][j]=max(t[i-1][j],t[i][j-1]); 19 | } 20 | } 21 | return (x-t[x][y])+(y-t[x][y]); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/Nth Fibonacci Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long int nthFibonacci(long long int n){ 4 | long long int t[n+1]; 5 | t[0]=0; 6 | t[1]=1; 7 | for(int i=2;i<=n;i++){ 8 | t[i]=(t[i-1]+t[i-2])%1000000007; 9 | } 10 | return t[n]%1000000007; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic Programming/Paint N House: -------------------------------------------------------------------------------- 1 | long long int distinctColoring(int N, int r[], int g[], int b[]){ 2 | 3 | vector> dp(N,vector(3,0)); 4 | dp[0][0]=r[0]; 5 | dp[0][1]=g[0]; 6 | dp[0][2]=b[0]; 7 | 8 | for(int i=1;i dp(n+1,0); 16 | for(int i=n-1;i>=0;i--){ 17 | int minCost=INT_MAX; 18 | for(int j=i;j &arr,int l,int r, vector> &dp){ 2 | if(l>r) return 0; 3 | if(dp[l][r]!=-1) return dp[l][r]; 4 | int takeLeft = arr[l] + min(solve(arr,l+1,r-1,dp), solve(arr,l+2,r,dp)); 5 | int takeRight = arr[r] + min(solve(arr,l+1,r-1,dp), solve(arr,l,r-2,dp)); 6 | return dp[l][r] = max(takeLeft,takeRight); 7 | } 8 | int maxCoins(vector&A,int n) 9 | { 10 | vector> dp(n,vector(n,-1)); 11 | return solve(A,0,n-1,dp); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Dynamic Programming/Print first n Fibonacci Numbers: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to return list containing first n fibonacci numbers. 5 | vector printFibb(int n) 6 | { 7 | vector v(n); 8 | v[0]=v[1]=1; 9 | for(int i=2;i dp(N+1,0); 4 | for(int i=0;i<=6;i++){ 5 | dp[i] = i; 6 | } 7 | for(int i=7;i<=N;i++){ 8 | for(int j=i-3;j>=1;j--){ 9 | long long int cur = dp[j]*(i-j-1); 10 | dp[i] = max(cur,dp[i]); 11 | } 12 | 13 | } 14 | return dp[N]; 15 | } 16 | -------------------------------------------------------------------------------- /Dynamic Programming/Stickler Thief: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find the maximum money the thief can get. 5 | int FindMaxSum(int arr[], int n) 6 | { 7 | int curr, prev=arr[0],prev2=0; 8 | if(n==1) return prev; 9 | for(int i=1;i1) pick+=prev2; 12 | int notPick = prev; 13 | curr= max(pick,notPick); 14 | prev2 = prev; 15 | prev= curr; 16 | } 17 | return prev; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Subset Sum Problem: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool isSubsetSum(int N, int arr[], int sum){ 4 | bool d[N+1][sum+1]; 5 | for(int i=0;i<=N;i++){ 6 | for(int j=0;j<=sum;j++){ 7 | if(i==0) d[i][j]=false; 8 | if(j==0) d[i][j]=true; 9 | } 10 | } 11 | for(int i=1;i<=N;i++){ 12 | for(int j=1;j<=sum;j++){ 13 | if(arr[i-1] &dictionary) { 2 | unordered_set set(dictionary.begin(), dictionary.end()); 3 | int m =s.size(); 4 | vector dp(m+1,false); 5 | dp[0] = true; 6 | for(int i=1;i<=m;i++){ 7 | for(int j=i-1;j>=0;j--){ 8 | if(dp[j] && set.count(s.substr(j,i-j))){ 9 | dp[i]=true; 10 | break; 11 | } 12 | } 13 | } 14 | return (dp[m])?1:0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Element that appears once where every element occurs twice: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,x,res=0; 9 | cin >>n; 10 | for(int i=0;i> x; 12 | res=res^x; 13 | } 14 | cout< 2 | using namespace std; 3 | 4 | int eqb(int arr[], int n) 5 | { 6 | if (n == 1) 7 | return 1; 8 | else { 9 | int pre[n]; 10 | 11 | pre[0] = arr[0]; 12 | for (int i = 1; i < n; i++) 13 | pre[i] = pre[i - 1] + arr[i]; 14 | for (int i = 1; i < n - 1; i++) { 15 | if (pre[i - 1] == (pre[n - 1] - pre[i])) 16 | return i + 1; 17 | } 18 | return -1; 19 | } 20 | } 21 | 22 | 23 | int main() { 24 | int t; 25 | cin >> t; 26 | while (t--) { 27 | int n; 28 | cin >> n; 29 | int arr[n]; 30 | for (int i = 0; i < n; i++) { 31 | cin >> arr[i]; 32 | } 33 | cout << eqb(arr, n) << endl; 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Examination Papers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | scanf("%d",&t); 8 | while(t--){ 9 | int n,count=0; 10 | cin >> n; 11 | cout << (unsigned long long)pow(2,n)-1 << endl; 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Find Immediate Smaller Than X: -------------------------------------------------------------------------------- 1 | int immediateSmaller(int a[], int n, int x) 2 | { 3 | int min=10001,val; 4 | for(int i=0;i(x-a[i])){ 7 | min=x-a[i]; 8 | val=a[i]; 9 | } 10 | } 11 | } 12 | if(min==10001) 13 | return -1; 14 | else 15 | return val; 16 | } 17 | -------------------------------------------------------------------------------- /Find Pair Given Difference: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool binarysearch(int arr[], int n, int x) { 5 | int l = 0, r = n - 1, mid; 6 | while (l <= r) { 7 | mid = l + ((r - l) / 2); 8 | if (arr[mid] == x) { 9 | return true; 10 | } 11 | else if (arr[mid] < x) 12 | l = mid + 1; 13 | else 14 | r = mid - 1; 15 | } 16 | return false; 17 | } 18 | int main() { 19 | int t; 20 | scanf("%d", &t); 21 | while (t--) { 22 | int n, i, x; 23 | cin >> n >> x; 24 | int arr[n]; 25 | for (i = 0; i < n; i++) 26 | cin >> arr[i]; 27 | sort(arr, arr + n); 28 | for (i = 0; i < n; i++) { 29 | if (binarysearch(arr, n, abs(x - arr[i]))) 30 | break; 31 | } 32 | if (i == n) 33 | cout << -1 << endl; 34 | else 35 | cout << 1 << endl; 36 | 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Find first set bit: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | int t; 4 | cin >>t; 5 | while(t--){ 6 | int n; 7 | cin>>n; 8 | if(n==0) cout << 0 < 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | scanf("%d", &t); 7 | while (t--) { 8 | int n, i; 9 | cin >> n; 10 | int arr[n]; 11 | for (i = 0; i < n; i++) cin >> arr[i]; 12 | int l = 0, r = n - 1, mid, ans = arr[n-1] ; 13 | if(arr[0] > arr[1]) 14 | ans = arr[0]; 15 | else { 16 | while (l <= r) { 17 | mid = l + ((r - l) / 2); 18 | if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { 19 | ans = arr[mid]; 20 | break; 21 | } 22 | else if (arr[mid] < arr[mid + 1]) 23 | l = mid + 1 ; 24 | else 25 | r = mid - 1 ; 26 | } 27 | } 28 | cout << ans << endl; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Find the element that appears once in sorted array: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | int x=arr[0]; 13 | for(int i=1;i v) 6 | { 7 | sort(v.begin(),v.end()); 8 | int l=0,r=v.size(); 9 | int mid=l+(r-l)/2; 10 | if(r%2==1) return(v[mid]); 11 | else return((v[mid-1]+v[mid])/2); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Finding Position: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,a=1,i=0; 9 | cin >>n; 10 | cout << (1< 2 | using namespace std; 3 | 4 | bool prof(int l,int p){ 5 | if(l==1) return 1; 6 | if(prof(l-1,(p+1)/2)==0) return (p%2)? 0 : 1; 7 | return (p%2)? 1 : 0; 8 | } 9 | int main() 10 | { 11 | int t; 12 | scanf("%d",&t); 13 | while(t--){ 14 | int l,p; 15 | cin >> l >> p; 16 | if(prof(l,p)) cout << "Engineer" << endl; 17 | else cout <<"Doctor" < 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | scanf("%d", &t); 7 | while (t--) { 8 | int n, x, i; 9 | cin >> n >> x; 10 | int arr[n]; 11 | for (i = 0; i < n; i++) cin >> arr[i]; 12 | int l = 0, r = n - 1, mid, start = -1, end = -1; 13 | while (l <= r) { 14 | mid = l + ((r - l) / 2); 15 | if (arr[mid] == x) { 16 | start = mid; 17 | end = mid; 18 | int temp = mid; 19 | while (arr[--temp] == x) { 20 | start--; 21 | } 22 | while (arr[++mid] == x) { 23 | end++; 24 | } 25 | break; 26 | } 27 | else if (arr[mid] < x) 28 | l = mid + 1 ; 29 | else 30 | r = mid - 1 ; 31 | } 32 | if (l > r) 33 | cout << -1 << endl; 34 | else 35 | cout << start << " " << end << endl; 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /For Loop 2- Python: -------------------------------------------------------------------------------- 1 | function Template for python3 2 | 3 | 4 | def stringJumper(str): 5 | for i in range(0,len(str),2): ## from 0 to length of str and skip 2 6 | print(str[i], end="") ##printing character and separating characters by nothing 7 | -------------------------------------------------------------------------------- /For loop - Python: -------------------------------------------------------------------------------- 1 | def multiplicationTable(N):## in is a membership operator that is true if something is a member of sequence 2 | for i in range(1,11,1): ## i in range(x,y,z) means i goes from x to y-1 and increments z steps in each iteration 3 | print(i*N, end=" ") ## Separating by spaces using end =" " 4 | 5 | -------------------------------------------------------------------------------- /Format specifier - C: -------------------------------------------------------------------------------- 1 | void format(int a, float b, char ch, double d) 2 | { 3 | printf("%d %.1f %c %f", a, b, ch, d); 4 | } 5 | -------------------------------------------------------------------------------- /Functions - Python: -------------------------------------------------------------------------------- 1 | def isPrime(n): 2 | if n <= 1: 3 | return False 4 | 5 | max_div = math.floor(math.sqrt(n)) 6 | for i in range(2, 1 + max_div): 7 | if n % i == 0: 8 | return False 9 | return True 10 | -------------------------------------------------------------------------------- /Functions in Lists - Python: -------------------------------------------------------------------------------- 1 | # Function to sort the list 2 | def sort_arr(arr): 3 | arr.sort()# Your code here 4 | 5 | # Function to join list elements 6 | # with string as delimiter 7 | def join_list(arr, string): 8 | 9 | # Complete the return statement to join list 10 | return string.join(arr) 11 | 12 | # Function to reverse array elements 13 | def rev_arr(arr): 14 | arr.reverse()# Your code here 15 | 16 | # Function to insert element at index 17 | def insert_arr(arr, index, element): 18 | arr.insert(index,element)# Your code here 19 | 20 | # Function to pop element from array at index 21 | def pop_arr(arr, index): 22 | arr.pop(index)# Your code here 23 | -------------------------------------------------------------------------------- /G.F Series: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long gf(int n){ 5 | if(n==0) return 0; 6 | if(n==1) return 1; 7 | return ((gf(n-2)*gf(n-2))-gf(n-1)); 8 | } 9 | 10 | int main() 11 | { 12 | int t; 13 | scanf("%d",&t); 14 | while(t--){ 15 | int n; 16 | cin >> n; 17 | for(int i=0;i 2 | using namespace std; 3 | int ans(int n,int k){ 4 | if(n==1) return 1; 5 | else return(ans(n-1,k)+k-1)%n+1; 6 | } 7 | int main() 8 | { 9 | int t; 10 | scanf("%d",&t); 11 | while(t--){ 12 | int n,k; 13 | cin >> n >> k; 14 | cout <<(n,k) << endl;; 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Graph/BFS: -------------------------------------------------------------------------------- 1 | vector bfsOfGraph(int V, vector adj[]) { 2 | vector ans; 3 | queue>> q; 4 | vector vis(V,false); 5 | 6 | q.push({0,adj[0]}); 7 | vis[0] = true; 8 | ans.push_back(0); 9 | while(!q.empty()){ 10 | int n = q.size(); 11 | 12 | for(int i=0;i> p = q.front(); 14 | q.pop(); 15 | for(int x: p.second){ 16 | if(!vis[x]){ 17 | ans.push_back(x); 18 | vis[x]=1; 19 | q.push({x,adj[x]}); 20 | } 21 | } 22 | } 23 | } 24 | 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /Graph/Clone an Undirected Graph: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map cloneMap; 4 | Node* cloneGraph(Node* node) { 5 | if(!node) return node; 6 | if(cloneMap.find(node) != cloneMap.end()) return cloneMap[node]; 7 | Node* root = new Node(node->val); 8 | cloneMap[node] = root; 9 | for(Node* neighbor : node->neighbors){ 10 | root->neighbors.push_back(cloneGraph(neighbor)); 11 | } 12 | return root; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Graph/DFS: -------------------------------------------------------------------------------- 1 | void dfs(int node,vector adj[],vector &ans,vector &vis){ 2 | ans.push_back(node); 3 | vis[node]=1; 4 | for(auto itr:adj[node]){ 5 | if(!vis[itr]) dfs(itr,adj,ans,vis); 6 | } 7 | } 8 | vector dfsOfGraph(int V, vector adj[]) { 9 | vector ans; 10 | vector vis(V,0); 11 | for(int i=0;i>& grid,int i,int j){ 6 | if(i<0 || j<0 || i==grid.size() || j==grid[0].size() || grid[i][j]==0) return false; 7 | if(grid[i][j]==2) return true; 8 | 9 | grid[i][j]=0; 10 | return (solve(grid,i+1,j) || solve(grid,i-1,j) || solve(grid,i,j+1) || solve(grid,i,j-1) ); 11 | } 12 | bool is_Possible(vector>& grid) 13 | { 14 | int i,j; 15 | for(i=0;i >& prerequisites) { 2 | vector> adj(N); 3 | vector indegree(N,0); 4 | for(auto it : prerequisites){ 5 | adj[it.second].push_back(it.first); 6 | indegree[it.first]++; 7 | } 8 | int count=0; 9 | queue q; 10 | for(int i=0;imaxIdx){ 5 | return 0; 6 | } 7 | maxIdx = max(maxIdx, A[i]+i); 8 | } 9 | return 1; 10 | } 11 | -------------------------------------------------------------------------------- /Greedy/Minimum Platforms: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | //Function to find the minimum number of platforms required at the 4 | //railway station such that no train waits. 5 | int findPlatform(int arr[], int dep[], int n) 6 | { 7 | sort(arr, arr + n); 8 | sort(dep, dep + n); 9 | int plat_needed = 1, result = 1; 10 | int i = 1, j = 0; 11 | while (i < n && j < n) { 12 | if (arr[i] <= dep[j]) { 13 | plat_needed++; 14 | i++; 15 | } 16 | else if (arr[i] > dep[j]) { 17 | plat_needed--; 18 | j++; 19 | } 20 | if (plat_needed > result) 21 | result = plat_needed; 22 | } 23 | return result; 24 | } 25 | }; 26 | 27 | 28 | -------------------------------------------------------------------------------- /Greedy/Minimum number of jumps: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int minJumps(int arr[], int n){ 4 | int farthest=0,jumps=0,current=0; 5 | for(int i=0;i > stockBuySell(vector A, int n){ 5 | vector> profit; 6 | 7 | for(int i=1;iA[i-1]){ 9 | profit.push_back({i-1,i}); 10 | } 11 | } 12 | return profit; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Help the Old Man!!!: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int count; 4 | 5 | void toh(int n,char a,char c,char b,int k){ 6 | if(n==1){ 7 | ::count++; 8 | if(::count==k) cout << a << " " << c; 9 | return; 10 | } 11 | toh(n-1,a,b,c,k); 12 | ::count++; 13 | if(::count==k) cout << a << " " << c; 14 | toh(n-1,b,c,a,k); 15 | } 16 | int main() 17 | { 18 | int t; 19 | scanf("%d",&t); 20 | while(t--){ 21 | int n,k; 22 | ::count=0; 23 | cin>>n>>k; 24 | toh(n,'1','3','2',k); 25 | cout << endl; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Hungry Pizza Lovers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct order{ 5 | int x,y,o,f; 6 | }; 7 | bool cmp(order a,order b){ 8 | if(a.f != b.f) return(a.f < b.f); 9 | else return(a.o < b.o); 10 | } 11 | int main() 12 | { 13 | int t; 14 | scanf("%d",&t); 15 | while(t--){ 16 | int n; 17 | cin >> n; 18 | order arr[n]; 19 | for(int i=0;i> arr[i].x >> arr[i].y ; 21 | arr[i].o = i+1; 22 | arr[i].f = arr[i].x+arr[i].y; 23 | } 24 | sort(arr,arr+n,cmp); 25 | for(int i =0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | scanf("%d", &t); 8 | while (t--) { 9 | string s; 10 | cin >> s; 11 | char state = '0'; 12 | for (int i = 0; i < s.length(); i++) { 13 | char digit = s[i]; 14 | if (state == '0') { 15 | if (digit == '1') state = '1'; 16 | } 17 | else if (state == '1') { 18 | if (digit == '1') state = '0'; 19 | else state = '2'; 20 | } 21 | else{ 22 | if (digit == '0') state = '1'; 23 | } 24 | } 25 | if (state == '0') cout << 1 << endl; 26 | else cout << 0 << endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Is and In Operator: -------------------------------------------------------------------------------- 1 | #Function to find if number is present in the list or not 2 | def number_present(num, query): 3 | #num is a 'list', query is a 'int' 4 | for i in range(len(num)): #write this here - i in range(len(num)) 5 | # see the use of 'in' in for loop 6 | if (num[i] is query) : #write this here - num[i] is query 7 | # see the use of 'is' as equal to 8 | return True 9 | return False 10 | 11 | -------------------------------------------------------------------------------- /Ishaan Loves Chocolates: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | cout << *min_element(arr,arr+n) << endl; 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /Iterating through Lists - Python: -------------------------------------------------------------------------------- 1 | # Function to print list 2 | # print elements in required fashion 3 | def print_elements(n, arr): 4 | for i in range(0,n//2): 5 | print(arr[i],end=' ') 6 | for i in range(n//2,n,3): 7 | print(arr[i],end=' ') 8 | # Your code here 9 | # use '//' to divide to get int for index 10 | -------------------------------------------------------------------------------- /Josephus problem: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int josephus(int n, int k) 5 | { 6 | if (n == 1) 7 | return 1; 8 | else 9 | /* The position returned by josephus(n - 1, k) 10 | is adjusted because the recursive call 11 | josephus(n - 1, k) considers the 12 | original position k % n + 1 as position 1 */ 13 | return (josephus(n - 1, k) + k-1) % n + 1; 14 | } 15 | 16 | // Driver Program to test above function 17 | int main() 18 | { 19 | int n = 14; 20 | int k = 2; 21 | cout << "The chosen place is " << josephus(n, k); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Kadane's Algorithm: -------------------------------------------------------------------------------- 1 | int maxSubarraySum(int arr[], int n){ 2 | int max_so_far = INT_MIN, max_ending_here = 0; 3 | 4 | for (int i = 0; i < n; i++) 5 | { 6 | max_ending_here = max_ending_here + arr[i]; 7 | if (max_so_far < max_ending_here) 8 | max_so_far = max_ending_here; 9 | 10 | if (max_ending_here < 0) 11 | max_ending_here = 0; 12 | } 13 | return max_so_far; 14 | } 15 | 16 | 17 | long long maxSubarraySum(int arr[], int n){ 18 | long long s=0,ans=arr[0]; 19 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | for(int i=0;i>arr[i]; 12 | int sum=0,mx=arr[0]; 13 | for(int i=0;i 2 | using namespace std; 3 | void lswap( string s,int k,string &ans,int curr){ 4 | if(k==0) return; 5 | char cmax=s[curr]; 6 | for(int i=curr+1;i> k; 27 | cin >> s; 28 | string ans=s; 29 | lswap(s,k,ans,0); 30 | cout<< ans << endl; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Largest number possible: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,s; 9 | cin >> n >> s; 10 | if(s>n*9 || (s==0 && n>1)){ 11 | cout << -1 << endl; 12 | continue; 13 | } 14 | for(int i=0;i=9) { 16 | cout << 9; 17 | s-=9; 18 | } 19 | else{ 20 | cout << s; 21 | s=0; 22 | } 23 | } 24 | cout << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Largest number with given sum: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,s; 9 | cin >> n >> s; 10 | if(s>(9*n)) { 11 | cout << -1 << endl; 12 | continue; 13 | } 14 | for(int i=0;i=9){ 16 | cout << 9; 17 | s-=9; 18 | } 19 | else{ 20 | cout << s; 21 | s=0; 22 | } 23 | } 24 | cout << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Last non-zero digit in factorial: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int d[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; 4 | int digit(int n){ 5 | if(n<10) return d[n]; 6 | if(((n/10)%10)%2==0) return (6*digit(n/5)*d[n%10])%10; 7 | else return (4*digit(n/5)*d[n%10])%10; 8 | } 9 | int main() 10 | { 11 | int t; 12 | scanf("%d",&t); 13 | while(t--){ 14 | int n; 15 | cin >> n; 16 | cout << digit(n) <next != NULL && temp->next != head){ 21 | temp = temp->next; 22 | } 23 | if(temp->next == NULL) return false; 24 | return true; 25 | } 26 | -------------------------------------------------------------------------------- /Linked List/Circular Linked List Traversal: -------------------------------------------------------------------------------- 1 | /* structure for a node 2 | struct Node 3 | { 4 | int data; 5 | struct Node *next; 6 | }; */ 7 | 8 | /* Function to print nodes in a given Circular linked list */ 9 | void printList(struct Node *head) 10 | { 11 | struct Node *t=head; 12 | while(t->next!=head){ 13 | printf("%d ",t->data); 14 | t=t->next; 15 | } 16 | printf("%d ",t->data); 17 | return; 18 | } 19 | -------------------------------------------------------------------------------- /Linked List/Count nodes of linked list: -------------------------------------------------------------------------------- 1 | int getCount(struct Node* head){ 2 | 3 | int count = 0; 4 | struct Node *temp =head; 5 | while(temp != NULL){ 6 | temp=temp->next; 7 | count++; 8 | } 9 | return count; 10 | } 11 | -------------------------------------------------------------------------------- /Linked List/Delete Alternate Nodes: -------------------------------------------------------------------------------- 1 | /* 2 | Structure of the node of the binary tree 3 | struct Node 4 | { 5 | int data; 6 | struct Node *next; 7 | 8 | Node(int x){ 9 | int data = x; 10 | next = NULL; 11 | } 12 | }; 13 | */ 14 | // Complete this function 15 | void deleteAlt(struct Node *head){ 16 | struct Node *a = head,*b; 17 | while(a!=NULL && a->next!=NULL){ 18 | b=a->next; 19 | a->next=b->next; 20 | free(b); 21 | a=a->next; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/Delete a Node in Single Linked List: -------------------------------------------------------------------------------- 1 | Node* deleteNode(Node *head,int x) 2 | { 3 | Node* curr=head,*prev=NULL,*after=curr->next; 4 | if(x==1){ 5 | head=head->next; 6 | delete(curr); 7 | return head; 8 | } 9 | for(int i=1;inext; 13 | } 14 | prev->next=after; 15 | delete(curr); 16 | return head; 17 | } 18 | -------------------------------------------------------------------------------- /Linked List/Delete without head pointer: -------------------------------------------------------------------------------- 1 | void deleteNode(Node *node) 2 | { 3 | Node * temp=node->next; 4 | *node=*(node->next); 5 | delete(temp); 6 | } 7 | -------------------------------------------------------------------------------- /Linked List/Detect Loop in linked list: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | struct Node 4 | { 5 | int data; 6 | struct Node *next; 7 | Node(int x) { 8 | data = x; 9 | next = NULL; 10 | } 11 | 12 | */ 13 | 14 | bool detectLoop(Node* head) 15 | { 16 | Node *s=head,*f=head; 17 | while(s!=NULL && f!=NULL && f->next!=NULL){ 18 | s=s->next; 19 | f=f->next->next; 20 | if(s==f) return true; 21 | } 22 | return false; 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/Doubly linked list Insertion at given position: -------------------------------------------------------------------------------- 1 | /* a Node of the doubly linked list 2 | struct Node 3 | { 4 | int data; 5 | struct Node *next; 6 | struct Node *prev; 7 | Node(int x) { data = x; next = prev = NULL; } 8 | }; */ 9 | 10 | /* Function to insert into a Doubly Linked List */ 11 | void addNode(Node *head, int pos, int data) 12 | { 13 | struct Node *t= new Node(data); 14 | if(head==NULL){ 15 | head=t; 16 | return; 17 | } 18 | struct Node *p=head; 19 | for(int i=0;inext; 20 | if(p->next == NULL){ 21 | p->next=t; 22 | t->prev=p; 23 | } 24 | else{ 25 | p->next->prev=t; 26 | t->next=p->next; 27 | t->prev=p; 28 | p->next=t; 29 | } 30 | return; 31 | } 32 | -------------------------------------------------------------------------------- /Linked List/Find n upon k th node in Linked list: -------------------------------------------------------------------------------- 1 | /*The structure of the node is 2 | struct Node 3 | { 4 | int data; 5 | struct Node *next; 6 | 7 | Node(int x){ 8 | data = x; 9 | next = NULL; 10 | } 11 | 12 | }; 13 | */ 14 | int fractional_node(struct Node *head, int k) 15 | { 16 | int count=0; 17 | Node *temp=head; 18 | while(temp->next!=NULL){ 19 | temp=temp->next; 20 | count++; 21 | } 22 | int pos=ceil(count/k); 23 | temp=head; 24 | while(pos--){ 25 | temp=temp->next; 26 | } 27 | return temp->data; 28 | } 29 | -------------------------------------------------------------------------------- /Linked List/Find the Sum of Last N nodes of the Linked List: -------------------------------------------------------------------------------- 1 | /*Structure of the node of the linled list is as 2 | 3 | struct Node { 4 | int data; 5 | struct Node* next; 6 | 7 | Node(int x){ 8 | data = x; 9 | next = NULL; 10 | } 11 | }; 12 | */ 13 | // your task is to complete this function 14 | // function should return sum of last n nodes 15 | int sumOfLastN_Nodes(struct Node* head, int n) 16 | { 17 | int c=0; 18 | Node *t=head; 19 | while(t->next!=NULL){ 20 | c++; 21 | t=t->next; 22 | } 23 | t=head; 24 | int sum=0; 25 | for(int i=0;i<=c-n;i++)t=t->next; 26 | while(t!=NULL){ 27 | sum+=t->data; 28 | t=t->next; 29 | } 30 | return sum; 31 | } 32 | -------------------------------------------------------------------------------- /Linked List/Finding middle element in a linked list: -------------------------------------------------------------------------------- 1 | int getMiddle(Node *head) 2 | { 3 | 4 | if(head==NULL) return -1; 5 | else{ 6 | Node *s=head; 7 | Node *f=head; 8 | while((f != NULL && f->next != NULL)){ 9 | f=f->next->next; 10 | s=s->next; 11 | } 12 | return s->data; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Linked List/Identical Linked Lists: -------------------------------------------------------------------------------- 1 | bool areIdentical(struct Node *head1, struct Node *head2) 2 | { 3 | struct Node *temp1=head1; 4 | struct Node *temp2=head2; 5 | while(temp1!=NULL || temp2!=NULL){ 6 | if(temp1->data != temp2->data) return false; 7 | temp1=temp1->next; 8 | temp2=temp2->next; 9 | } 10 | return true; 11 | } 12 | -------------------------------------------------------------------------------- /Linked List/Insert in Middle of Linked List: -------------------------------------------------------------------------------- 1 | /* 2 | struct Node { 3 | int data; 4 | struct Node *next; 5 | Node(int x) { 6 | data = x; 7 | next = NULL; 8 | } 9 | }; 10 | */ 11 | 12 | // function should insert node at the middle 13 | // of the linked list 14 | Node* insertInMiddle(Node* head, int x) 15 | { 16 | struct Node *n=new Node(x); 17 | struct Node *s=head; 18 | struct Node *f=head; 19 | if(head==NULL){ 20 | head=n; 21 | return head; 22 | } 23 | else{ 24 | while(f->next != NULL && f->next->next != NULL){ 25 | f=f->next->next; 26 | s=s->next; 27 | } 28 | } 29 | n->next=s->next; 30 | s->next=n; 31 | return head; 32 | } 33 | -------------------------------------------------------------------------------- /Linked List/Linked List Length Even or Odd?: -------------------------------------------------------------------------------- 1 | /*structure of a node of the linked list is as 2 | struct Node 3 | { 4 | int data; 5 | struct Node* next; 6 | 7 | Node(int x){ 8 | data = x; 9 | next = NULL; 10 | } 11 | 12 | }; 13 | */ 14 | // Function should return 0 is length is even else return 1 15 | int isLengthEvenOrOdd(struct Node* head) 16 | { 17 | int count=0; 18 | struct Node *temp=head; 19 | while(temp!=NULL){ 20 | count++; 21 | temp=temp->next; 22 | } 23 | if(count%2==0) return 0; 24 | return 1; 25 | } 26 | -------------------------------------------------------------------------------- /Linked List/Linked List Matrix: -------------------------------------------------------------------------------- 1 | vectorprev(mat[0].size()); 2 | for(int i=mat.size()-1; i>=0; i--){ 3 | for(int j=mat[0].size()-1; j>=0; j--){ 4 | Node* temp=new Node(mat[i][j]); 5 | if(i!=mat.size()-1) temp->down=prev[j]; 6 | if(j!=mat[0].size()-1) temp->right=prev[j+1]; 7 | prev[j]=temp; 8 | } 9 | } 10 | return prev[0]; 11 | -------------------------------------------------------------------------------- /Linked List/Merge two sorted linked lists: -------------------------------------------------------------------------------- 1 | Node* sortedMerge(Node* head1, Node* head2) 2 | { 3 | if(head1==NULL) return head2; 4 | if(head2==NULL) return head1; 5 | if(head1->data > head2->data ){ 6 | Node *temp=head1; 7 | head1=head2; 8 | head2=temp; 9 | } 10 | Node *res=head1; 11 | while( head1 && head2){ 12 | Node* temp=NULL; 13 | while(head1!=NULL && head1->data <=head2->data){ 14 | temp=head1; 15 | head1=head1->next; 16 | } 17 | temp->next=head2; 18 | Node *t=head1; 19 | head1=head2; 20 | head2=t; 21 | } 22 | return res; 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/Modular Node: -------------------------------------------------------------------------------- 1 | /*Struture of the node of the linked list is as: 2 | 3 | struct Node { 4 | int data; 5 | struct Node* next; 6 | 7 | Node(int x){ 8 | data = x; 9 | next = NULL; 10 | } 11 | 12 | }; 13 | */ 14 | // Your task is to complete the function 15 | // function should return the modular Node 16 | // if no such node is present then return -1 17 | int modularNode(Node* head, int k) 18 | { 19 | Node *t=head; 20 | int ans,flag=0,i=1; 21 | while(t!=NULL){ 22 | if(i%k==0){ 23 | ans=t->data; 24 | flag=1; 25 | } 26 | i++; 27 | t=t->next; 28 | } 29 | if(flag==0) return -1; 30 | return ans; 31 | } 32 | -------------------------------------------------------------------------------- /Linked List/Node at a given index in linked list: -------------------------------------------------------------------------------- 1 | int GetNth(struct node* head, int index){ 2 | node * temp=head; 3 | while(--index){ 4 | temp=temp->next; 5 | } 6 | return temp->data; 7 | } 8 | -------------------------------------------------------------------------------- /Linked List/Print Linked List elements: -------------------------------------------------------------------------------- 1 | void display(Node *head) 2 | { 3 | struct Node *temp = head; 4 | while(temp!=NULL){ 5 | cout << temp->data << " "; 6 | temp=temp->next; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Linked List/Remove duplicate element from sorted Linked List: -------------------------------------------------------------------------------- 1 | /* 2 | struct Node { 3 | int data; 4 | struct Node *next; 5 | Node(int x) { 6 | data = x; 7 | next = NULL; 8 | } 9 | };*/ 10 | 11 | // root: head node 12 | Node *removeDuplicates(Node *root){ 13 | Node *t=root; 14 | while(t!=NULL && t->next!=NULL){ 15 | if(t->data==t->next->data){ 16 | t->next=t->next->next; 17 | } 18 | else{ 19 | t=t->next; 20 | } 21 | } 22 | return root; 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/Remove loop in Linked List: -------------------------------------------------------------------------------- 1 | void removeLoop(Node* head) 2 | { 3 | // code here 4 | // just remove the loop without losing any nodes 5 | Node *slow=head,*fast=head; 6 | while(slow && fast && fast->next){ 7 | slow=slow->next; 8 | fast=fast->next->next; 9 | if(slow==fast) break; 10 | } 11 | if(slow==fast){ 12 | slow=head; 13 | if(slow==fast){ 14 | while(fast->next!=slow){ 15 | fast=fast->next; 16 | } 17 | } 18 | else{ 19 | while(slow->next!=fast->next){ 20 | slow=slow->next; 21 | fast=fast->next; 22 | } 23 | } 24 | fast->next=NULL; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Linked List/Repetitive Addition Of Digits: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleDigit(long long N) 5 | { 6 | long long sum=0; 7 | while(N){ 8 | sum+=N%10; 9 | N/=10; 10 | } 11 | if(sum/10==0) return sum; 12 | return singleDigit(sum); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Linked List/Reverse a Linked List in groups of given size: -------------------------------------------------------------------------------- 1 | struct node *reverse (struct node *head, int k) 2 | { 3 | node* prev=NULL,*curr=head,*t; 4 | int flag=k; 5 | while(flag-- && curr!=NULL){ 6 | t=curr->next; 7 | curr->next=prev; 8 | prev=curr; 9 | curr=t; 10 | } 11 | if(head!=NULL) head->next=reverse(t,k); 12 | return prev; 13 | } 14 | -------------------------------------------------------------------------------- /Linked List/Reverse a linked list: -------------------------------------------------------------------------------- 1 | /* Linked List Node structure: 2 | 3 | struct Node 4 | { 5 | int data; 6 | struct Node *next; 7 | } 8 | 9 | */ 10 | 11 | // Should reverse list and return new head. 12 | struct Node* reverseList(struct Node *head) 13 | { 14 | Node *prev=NULL,*curr=head,*after=curr->next; 15 | while(curr!=NULL){ 16 | after=curr->next; 17 | curr->next=prev; 18 | prev=curr; 19 | curr=after; 20 | } 21 | head=prev; 22 | return head; 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/Rotate a Linked List: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | struct Node { 4 | int data; 5 | struct Node *next; 6 | Node(int x) { 7 | data = x; 8 | next = NULL; 9 | } 10 | }; 11 | 12 | */ 13 | 14 | // This function should rotate list counter-clockwise 15 | // by k and return new head (if changed) 16 | 17 | Node* rotate(Node* head, int k) 18 | { 19 | Node *t=head; 20 | int c=1; 21 | while(c!=k){ 22 | t=t->next; 23 | c++; 24 | } 25 | if(t->next==NULL) return head; 26 | Node *temp=t; 27 | Node *temp_head=t->next; 28 | while(t!=NULL && t->next!=NULL){ 29 | t=t->next; 30 | } 31 | temp->next=NULL; 32 | t->next=head; 33 | return temp_head; 34 | } 35 | -------------------------------------------------------------------------------- /Logical Operators - Python: -------------------------------------------------------------------------------- 1 | def logical(a,b): 2 | print(a and b) ## do a and b 3 | print(a or b) ## do a or b 4 | print(not a) ## do not a 5 | -------------------------------------------------------------------------------- /Logical operator in C: -------------------------------------------------------------------------------- 1 | void logical(int x, int y) 2 | { 3 | printf("%d %d %d",x&&y,x||y,!x); 4 | } 5 | -------------------------------------------------------------------------------- /Longest subarray with sum divisible by K: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n, k; 9 | cin >> n >> k; 10 | int arr[n]; 11 | for (int i = 0; i < n; i++) { 12 | cin >> arr[i]; 13 | } 14 | unordered_map um; 15 | int mod_arr[n], max = 0; 16 | int curr_sum = 0; 17 | for (int i = 0; i < n; i++) 18 | { 19 | curr_sum += arr[i]; 20 | mod_arr[i] = ((curr_sum%k)+k)%k;; 21 | } 22 | 23 | for (int i = 0; i < n; i++) 24 | { 25 | if (mod_arr[i] == 0) 26 | max = i + 1; 27 | 28 | else if (um.find(mod_arr[i]) == um.end()) 29 | um[mod_arr[i]] = i; 30 | 31 | else 32 | 33 | if (max < (i - um[mod_arr[i]])) 34 | max = i - um[mod_arr[i]]; 35 | } 36 | cout << max << endl; 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Map/Check if two strings are k-anagrams or not: -------------------------------------------------------------------------------- 1 | bool areKAnagrams(string str1, string str2, int k) { 2 | 3 | if(str1.size() != str2.size()) return false; 4 | 5 | int count=0; 6 | vector freq(26,0); 7 | 8 | for(int i=0;i mp; 3 | int c=0; 4 | for(int i=0;imp; 3 | for(int i=0;ires) 17 | { 18 | res=i.first; 19 | } 20 | } 21 | return res; 22 | } 23 | -------------------------------------------------------------------------------- /Map/Key Pair: -------------------------------------------------------------------------------- 1 | bool hasArrayTwoCandidates(vector& arr, int x) { 2 | int n = arr.size(); 3 | unordered_set s; 4 | s.insert(arr[0]); 5 | for(int i=1;i &arr) { 2 | unordered_map mp; 3 | int maxDist=0; 4 | for(int i=0;i mp; 4 | for(int i=0;i freq(n+1,false); 8 | for(auto it:mp){ 9 | if(freq[it.second]) return false; 10 | freq[it.second] = true; 11 | } 12 | 13 | return true; 14 | } 15 | -------------------------------------------------------------------------------- /Mark Even and Odd - Python: -------------------------------------------------------------------------------- 1 | def checkOddEven(x): 2 | if(x % 2 is 0): 3 | # Complete the statement below 4 | return True 5 | else: 6 | # Complete the statement below 7 | return False 8 | -------------------------------------------------------------------------------- /Math/Bit Difference: -------------------------------------------------------------------------------- 1 | int countBits(int N, long long int A[]) 2 | { 3 | long long int ans=0; 4 | for(int i=0;i<32;i++){ 5 | long long int setCount =0, unsetCount=0; 6 | for(int j=0;j &res, int x){ 2 | for(int i=0;i constructList(int q, vector> &queries) { 7 | vector res = {0}; 8 | int cumulative_xor =0; 9 | for(int i=0;i0){ 5 | if(n&1){ 6 | ans = (ans*x)%M; 7 | } 8 | x = (x*x) %M; 9 | n>>=1; 10 | } 11 | return ans; 12 | } 13 | 14 | 15 | ######################################################################################## 16 | 17 | long long int PowMod(long long int x,long long int n,long long int M) 18 | { 19 | if(n==0) return 1; 20 | long long smallPower=PowMod(x,n/2,M); 21 | smallPower=((smallPower%M)*(smallPower%M))%M; 22 | if(n%2==0) 23 | return smallPower%M; 24 | else 25 | return ((smallPower%M)*(x%M))%M; 26 | } 27 | -------------------------------------------------------------------------------- /Math/Number following a pattern: -------------------------------------------------------------------------------- 1 | string printMinNumberForPattern(string S){ 2 | int n = S.size(); 3 | string res; 4 | stack st; 5 | 6 | for(int i=0;i<=n;i++){ 7 | st.push(i+1); 8 | if(i==n || S[i] == 'I'){ 9 | while(!st.empty()){ 10 | res += to_string(st.top()); 11 | st.pop(); 12 | } 13 | } 14 | } 15 | return res; 16 | } 17 | -------------------------------------------------------------------------------- /Math/Plus One: -------------------------------------------------------------------------------- 1 | vector increment(vector arr ,int N) { 2 | vector ans; 3 | int carry=1, i =N-1; 4 | while(i>=0 || carry){ 5 | int sum = carry; 6 | sum+=arr[i--]; 7 | carry = sum/10; 8 | ans.push_back(sum%10); 9 | } 10 | reverse(ans.begin(),ans.end()); 11 | return ans; 12 | } 13 | -------------------------------------------------------------------------------- /Math/Single Element Among Triplets: -------------------------------------------------------------------------------- 1 | int singleElement(int arr[] ,int N) { 2 | int result = 0; 3 | for (int i = 0; i < 32; i++) { 4 | int sum = 0; 5 | for (int j = 0; j < N; j++) { 6 | // getting set bit count 7 | sum += (arr[j] >> i) & 1; 8 | } 9 | // getting set bit % 3 value and if it is 1 10 | // then setting that bit as 1 for result 11 | result |= (sum % 3) << i; 12 | } 13 | return result; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Math/String's Count: -------------------------------------------------------------------------------- 1 | long long int countStr(long long int n){ 2 | const long long res = 1 + 2 * n + (3 * (n - 1) * n) / 2 + (n * (n - 1) * (n - 2)) / 2; 3 | return res; 4 | } 5 | 6 | ############################################################################################################################################################ 7 | 8 | 9 | void check(string s, long long int n, int nb, int nc, long long int &count){ 10 | if(s.size() == n){ 11 | count ++; 12 | return; 13 | } 14 | check(s+"a", n,nb,nc,count); 15 | if(nb>0) check(s+"b", n, nb-1,nc,count); 16 | if(nc>0) check(s+"c",n,nb,nc-1,count); 17 | return; 18 | } 19 | long long int countStr(long long int n){ 20 | long long int count=0; 21 | string s =""; 22 | check(s,n,1,2,count); 23 | return count; 24 | } 25 | -------------------------------------------------------------------------------- /Math/Sum of bit differences: -------------------------------------------------------------------------------- 1 | long long sumBitDifferences(int arr[], int n) { 2 | long long ans=0; 3 | int maxi = *max_element(arr,arr+n); 4 | //to get the binary digits max length 5 | int idx = (int)(log2(maxi+1))+1; 6 | //Worst Case time complexity => O(32*N) 7 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n, k; 9 | cin >> n >> k; 10 | int pre[n], arr[n]; 11 | for (int i = 0; i < n; i++) { 12 | cin >> arr[i]; 13 | } 14 | pre[0] = arr[0]; 15 | for (int i = 1; i < n; i++) { 16 | pre[i] = pre[i - 1] + arr[i]; 17 | } 18 | int max = pre[k - 1]; 19 | for (int i = 1; i < n - k + 1; i++) { 20 | if (max < (pre[i + k - 1] - pre[i - 1])) 21 | max = (pre[i + k - 1] - pre[i - 1]); 22 | } 23 | cout << max << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Maximize Toys: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,c; 9 | cin >> n >> c; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | sort(arr,arr+n); 13 | int i=0,count=0; 14 | while(arr[i]<=c){ 15 | count++; 16 | c-=arr[i]; 17 | i++; 18 | } 19 | cout << count << endl; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Maximum sum of subarray less than or equal to x: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n, k, i, j, sum = 0, diff, ans, first = 0; 9 | cin >> n; 10 | int arr[n]; 11 | for (i = 0; i < n; i++) { 12 | cin >> arr[i]; 13 | } 14 | cin >> k; 15 | diff = k; 16 | for (i = 0; i < n; i++) { 17 | sum += arr[i]; 18 | while (sum > k ) { 19 | sum -= arr[first]; 20 | first++; 21 | } 22 | if ((k - sum) < diff) { 23 | ans = sum; 24 | diff = k - sum; 25 | if (diff == 0) { 26 | cout << k << endl; 27 | break; 28 | } 29 | } 30 | } 31 | 32 | if (i == n){ 33 | if(diff==k) 34 | cout << 0 << endl; 35 | else 36 | cout << ans << endl; 37 | } 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Merge Without Extra Space: -------------------------------------------------------------------------------- 1 | void merge(int ar1[], int ar2[], int n, int m) 2 | { 3 | for (int i=m-1; i>=0; i--){ 4 | int j, last = ar1[n-1]; 5 | for (j=n-2; j >= 0 && ar1[j] > ar2[i]; j--){ 6 | ar1[j+1] = ar1[j]; 7 | } 8 | 9 | if(j != n-2 || last > ar2[i]){ 10 | ar1[j+1] = ar2[i]; 11 | ar2[i] = last; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Merge and Sort: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int k; 9 | cin >> k; 10 | set s; 11 | while(k--){ 12 | int temp,n; 13 | cin >> n; 14 | for(int i=0;i> temp; 16 | s.insert(temp); 17 | } 18 | } 19 | for (auto it : s) 20 | cout << it << " "; 21 | cout << endl; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Message Spreading: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | long long n; 9 | cin >> n; 10 | long long ans = (2*n)-2; 11 | cout << ans << endl; 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Missing number in array: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin >> t; 7 | while(t--){ 8 | int n,a=1,b; 9 | cin >> n; 10 | for(int i=2;i<=n;i++){ 11 | a=a^i; 12 | } 13 | int arr[n-1]; 14 | for(int i=0;i> arr[i]; 16 | } 17 | b=arr[0]; 18 | for(int i=1;i val; 23 | cin >> n; 24 | n++; 25 | while(true){ 26 | val.clear(); 27 | val.push_back(n); 28 | if(check(n,val)){ 29 | cout << n< m; 5 | for(i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | unordered_map m; 9 | long long i,n; 10 | cin >> n; 11 | long long arr[n]; 12 | for(i=0;i> arr[i]; 14 | m[arr[i]]++; 15 | } 16 | for(i=0;i 2 | using namespace std; 3 | 4 | int path(int n,int m){ 5 | if(n==1 || m==1) return 1; 6 | return(path(n-1,m)+path(n,m-1)); 7 | } 8 | int main() 9 | { 10 | int t; 11 | scanf("%d",&t); 12 | while(t--){ 13 | int n , m; 14 | cin >> n >> m; 15 | cout << path(n,m)<0;i--){ 3 | for(int j=n;j>0;j--){ 4 | for(int k=0;k=arr[mid-1]) && (arr[mid]>=arr[mid+1] || mid==n-1)) return mid; 7 | if(arr[mid-1]>arr[mid] && mid > 0)r=mid-1; 8 | else l=mid+1; 9 | } 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /Permutations of a given string: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector ans; 4 | void rec(string s,int l,int r){ 5 | if(l==r) ans.push_back(s); 6 | for(int i=l;i> s; 20 | sort(s.begin(),s.end()); 21 | rec(s,0,s.length()); 22 | sort(ans.begin(),ans.end()); 23 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin >> t; 7 | while(t--){ 8 | long long n; 9 | cin >> n; 10 | if(n && !(n&(n-1))) cout << "YES" << endl; 11 | else cout << "NO" << endl; 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Print Pattern: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void ppattern(int n, int temp) { 4 | cout << temp << " "; 5 | temp += 5; 6 | if (temp == n) { 7 | cout << temp; 8 | return; 9 | } 10 | else { 11 | ppattern(n, temp); 12 | } 13 | } 14 | 15 | void pattern(int n, int temp) { 16 | cout << temp << " "; 17 | temp -= 5; 18 | if (temp <= 0) { 19 | ppattern(n, temp); 20 | return; 21 | } 22 | else { 23 | pattern(n, temp); 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | int t; 30 | cin >> t; 31 | while (t--) { 32 | int n; 33 | cin >> n; 34 | int temp = n; 35 | pattern(n, temp); 36 | cout << endl; 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Print this pattern!: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void printPattern(int N) 5 | { 6 | int i,j,n=N*2-1; 7 | int k=0; 8 | int l=n-1; 9 | int x=N; 10 | int a[n][n]; 11 | while(x){ 12 | for(i=k;i<=l;i++){ 13 | for(j=k;j<=l;j++){ 14 | if(i==k||i==l||j==k||j==l) a[i][j]=x; 15 | } 16 | } 17 | k++; 18 | l--; 19 | x--; 20 | } 21 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | memset(arr,0,n); 12 | queue q; 13 | for(int i=1;i<=n;i++) q.push(i); 14 | int k=1,count=1; 15 | while(!q.empty()){ 16 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,k,t; 9 | cin >> n >> k; 10 | priority_queue pq; 11 | while(n--) { 12 | cin >> t; 13 | pq.push(t); 14 | } 15 | long long sum=0; 16 | while(k--){ 17 | sum+=pq.top(); 18 | t=pq.top(); 19 | pq.pop(); 20 | pq.push(t/2); 21 | } 22 | cout << sum << endl; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Queue/Circular tour: -------------------------------------------------------------------------------- 1 | /* 2 | The structure of petrolPump is 3 | struct petrolPump 4 | { 5 | int petrol; 6 | int distance; 7 | };*/ 8 | 9 | /*You are required to complete this method*/ 10 | int tour(petrolPump p[],int n) 11 | { 12 | int start=0,remaining=0,capacity=0; 13 | for(int i=0;i=0)?start:-1; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Queue/Count the Reversals: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | string str; 9 | cin>>str; 10 | if(str.size() % 2 != 0){ 11 | cout<<"-1\n"; 12 | continue; 13 | } 14 | stack s; 15 | int count=0; 16 | for(int i=0;i 2 | using namespace std; 3 | 4 | void solve(int arr[],int n,int k){ 5 | queue q; 6 | int i; 7 | for(i=0;i> n; 22 | int arr[n]; 23 | for(int i=0;i> arr[i]; 24 | cin >> k; 25 | solve(arr,n,k); 26 | cout << endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Queue/Generate Binary Numbers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printBinary(int n){ 5 | queue q; 6 | q.push("1"); 7 | for(int i=1;i<=n;i++){ 8 | string s1=q.front(); 9 | q.pop(); 10 | cout<> n; 22 | printBinary(n); 23 | cout << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Queue/Implement Queue using Linked List: -------------------------------------------------------------------------------- 1 | void MyQueue:: push(int x) 2 | { 3 | QueueNode *temp=new QueueNode(x); 4 | if(front==NULL){ 5 | front=rear=temp; 6 | return; 7 | } 8 | rear->next=temp; 9 | rear=temp; 10 | } 11 | 12 | /*The method pop which return the element 13 | poped out of the queue*/ 14 | int MyQueue :: pop() 15 | { 16 | if(front==NULL) return -1; 17 | int x=front->data; 18 | front=front->next; 19 | return x; 20 | } 21 | -------------------------------------------------------------------------------- /Queue/Implement Queue using array: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The structure of the class is 4 | class MyQueue { 5 | private: 6 | int arr[10001]; 7 | int front; 8 | int rear; 9 | 10 | public : 11 | MyQueue(){front=0;rear=0;} 12 | void push(int); 13 | int pop(); 14 | }; 15 | */ 16 | 17 | /* The method push to push element into the queue */ 18 | void MyQueue :: push(int x) 19 | { 20 | arr[front]=x; 21 | front++; 22 | } 23 | 24 | /*The method pop which return the element 25 | poped out of the queue*/ 26 | int MyQueue :: pop() 27 | { 28 | int t=arr[rear]; 29 | rear++; 30 | return t; 31 | } 32 | -------------------------------------------------------------------------------- /Queue/Min sum formed by digits: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int k; 6 | scanf("%d",&k); 7 | while(k--){ 8 | priority_queue,greater>q; 9 | int n,a,t,x=0,y=0; 10 | cin>>n; 11 | for(int i=0;i>a; 13 | q.push(a); 14 | } 15 | while(!q.empty()){ 16 | t=q.top(); 17 | q.pop(); 18 | x=x*10+t; 19 | if(!q.empty()){ 20 | t=q.top(); 21 | q.pop(); 22 | y=y*10+t; 23 | } 24 | } 25 | cout << x+y << endl; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Queue/Minimum Cost of ropes: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | long long n,cost=0; 9 | cin >> n; 10 | priority_queue,greater> pq; 11 | for(long long i=0;i> te; 14 | pq.push(te); 15 | } 16 | while(pq.size()!=1){ 17 | long long a,b; 18 | a=pq.top(); 19 | pq.pop(); 20 | b=pq.top(); 21 | pq.pop(); 22 | //cout << a << " " << b << endl; 23 | cost+=(a+b); 24 | pq.push(a+b); 25 | } 26 | cout << cost << endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Queue/Nearly sorted: -------------------------------------------------------------------------------- 1 | void nearlySorted(vector& arr, int k) { 2 | priority_queue,greater> min_heap; 3 | int n=arr.size(); 4 | int idx=0; 5 | for(int i=0;ik){ 8 | arr[idx++] = min_heap.top(); 9 | min_heap.pop(); 10 | } 11 | } 12 | while(!min_heap.empty()){ 13 | arr[idx++]=min_heap.top(); 14 | min_heap.pop(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Queue/Queue Push & Pop: -------------------------------------------------------------------------------- 1 | queue_push(int arr[],int n) 2 | { 3 | queue q; 4 | for(int i=0;is) 9 | { 10 | while(!s.empty()){ 11 | cout << s.front() << " "; 12 | s.pop(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Queue/Queue Reversal: -------------------------------------------------------------------------------- 1 | queue rev(queue q) 2 | { 3 | stack s; 4 | while(!q.empty()){ 5 | s.push(q.front()); 6 | q.pop(); 7 | } 8 | while(!s.empty()){ 9 | q.push(s.top()); 10 | s.pop(); 11 | } 12 | return q; 13 | } 14 | -------------------------------------------------------------------------------- /Queue/Queue using two Stacks: -------------------------------------------------------------------------------- 1 | /* The structure of the class is 2 | class StackQueue{ 3 | private: 4 | // These are STL stacks ( http://goo.gl/LxlRZQ ) 5 | stack s1; 6 | stack s2; 7 | public: 8 | void push(int); 9 | int pop(); 10 | }; */ 11 | 12 | /* The method push to push element into the queue */ 13 | void StackQueue :: push(int x) 14 | { 15 | s1.push(x); 16 | } 17 | 18 | /*The method pop which return the element poped out of the queue*/ 19 | int StackQueue :: pop() 20 | { 21 | if(s1.empty()) return -1; 22 | while(!s1.empty()){ 23 | s2.push(s1.top()); 24 | s1.pop(); 25 | } 26 | int ans =s2.top(); 27 | s2.pop(); 28 | while(!s2.empty()){ 29 | s1.push(s2.top()); 30 | s2.pop(); 31 | } 32 | return ans; 33 | } 34 | -------------------------------------------------------------------------------- /Queue/Reverse First K elements of Queue: -------------------------------------------------------------------------------- 1 | queue modifyQueue(queue q, int k) 2 | { 3 | stack s; 4 | queue ans; 5 | while(k--){ 6 | s.push(q.front()); 7 | q.pop(); 8 | } 9 | while(!s.empty()){ 10 | ans.push(s.top()); 11 | s.pop(); 12 | } 13 | while(!q.empty()){ 14 | ans.push(q.front()); 15 | q.pop(); 16 | } 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /Queue/Stack using two queues: -------------------------------------------------------------------------------- 1 | /* The structure of the class is 2 | class QueueStack{ 3 | private: 4 | queue q1; 5 | queue q2; 6 | public: 7 | void push(int); 8 | int pop(); 9 | }; 10 | */ 11 | 12 | /* The method push to push element into the stack */ 13 | void QueueStack :: push(int x) 14 | { 15 | q1.push(x); 16 | } 17 | 18 | /*The method pop which return the element poped out of the stack*/ 19 | int QueueStack :: pop() 20 | { 21 | if(q1.empty()) return -1; 22 | q1.push(0); 23 | int ans; 24 | while(1){ 25 | int x=q1.front(); 26 | q1.pop(); 27 | if(q1.front()==0){ 28 | ans=x; 29 | break; 30 | } 31 | else q1.push(x); 32 | } 33 | q1.pop(); 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /Raju and coins: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,k; 9 | cin >> n >> k; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | sort(arr,arr+n); 13 | int i=1,count=0,j=0; 14 | while(k>0&&k>=i){ 15 | if(arr[j]==i) j++; 16 | else { 17 | k-=i; 18 | count++; 19 | } 20 | i++; 21 | } 22 | cout << count << endl; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Rearrange an array with O(1) extra space: -------------------------------------------------------------------------------- 1 | // Function to rarrange the elements in O(1) extra space 2 | // arr: input array 3 | // n: size of array 4 | void arrange(long long arr[], int n) { 5 | int i; 6 | for(i=0;i 2 | using namespace std; 3 | void recaman(int n){ 4 | vector v; 5 | int prev=0; 6 | v.push_back(prev); 7 | for(int i=1;i> n; 27 | recaman(n); 28 | cout << endl; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Regex - Python: -------------------------------------------------------------------------------- 1 | def numberMatcher(str): 2 | pat=re.compile('\d+')##write the pattern here 3 | match=re.findall(pat,str) ##find all finds all the matched texts and returns a list 4 | if(match): 5 | for i in match: 6 | print(i,end=" ") 7 | else: 8 | print(-1,end="") 9 | -------------------------------------------------------------------------------- /Regular Expressions 2 - Python: -------------------------------------------------------------------------------- 1 | def validate(str): 2 | pat= re.compile('[a-z]\W+\d+')##your pattern here 3 | match=re.search(pat,str) 4 | if(match): 5 | return True 6 | else: 7 | return False 8 | -------------------------------------------------------------------------------- /Remove all duplicates from a given string: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | string removeDuplicates(string str) { 4 | string t=""; 5 | unordered_map m; 6 | for(int i=0;ilen(b)): 4 | short=b 5 | longer=a 6 | else: 7 | longer=b 8 | short=a 9 | 10 | return short+longer+short 11 | -------------------------------------------------------------------------------- /Repetitive Printing - Python: -------------------------------------------------------------------------------- 1 | # Function to print given string 'x' times 2 | def print_fun(string, x): 3 | # Your code here 4 | print(string*x) 5 | -------------------------------------------------------------------------------- /Replace a word: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int k; 6 | scanf("%d",&k); 7 | cin.ignore(); 8 | while(k--){ 9 | string s,o,n,t; 10 | getline(cin,s); 11 | getline(cin,o); 12 | getline(cin,n); 13 | //cout << s <<" "<< o<<" " << n<< endl; 14 | int l=o.length(); 15 | for(int i=0;i 2 | void rev(int arr[], int start, int end) 3 | { 4 | while (start < end) 5 | { 6 | int temp = arr[start]; 7 | arr[start] = arr[end]; 8 | arr[end] = temp; 9 | start++; 10 | end--; 11 | } 12 | } 13 | int main() { 14 | int i,j,t,n; 15 | scanf("%d",&t); 16 | for(j=0;j 2 | void rev(int arr[], int start, int end) 3 | { 4 | while (start < end) 5 | { 6 | int temp = arr[start]; 7 | arr[start] = arr[end]; 8 | arr[end] = temp; 9 | start++; 10 | end--; 11 | } 12 | } 13 | int main() { 14 | int i,j,t,n,k; 15 | scanf("%d",&t); 16 | for(j=0;j=k;i+=k){ 23 | rev(a,i,i+k-1); 24 | } 25 | rev(a,i,n-1); 26 | for(i=0;i v; 5 | for(int i=0;i0;i--){ 16 | x+=v[i]; 17 | x+='.'; 18 | } 19 | x+=v[0]; 20 | return x; 21 | } 22 | -------------------------------------------------------------------------------- /Root to leaf paths sum: -------------------------------------------------------------------------------- 1 | void fun(Node *root,long long &res,long long curr){ 2 | if(!root)return; 3 | if(!root->left && !root->right){ 4 | curr=curr*10+(root->data); 5 | res+=curr; 6 | return; 7 | } 8 | fun(root->left,res,(curr*10)+root->data); 9 | fun(root->right,res,(curr*10)+root->data); 10 | } 11 | long long treePathsSum(Node *root){ 12 | long long res=0,curr=0; 13 | fun(root,res,curr); 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /Rotate Array: -------------------------------------------------------------------------------- 1 | #include 2 | void rev(int arr[], int start, int end) 3 | { 4 | while (start < end) 5 | { 6 | int temp = arr[start]; 7 | arr[start] = arr[end]; 8 | arr[end] = temp; 9 | start++; 10 | end--; 11 | } 12 | } 13 | int main() { 14 | int n,i,j,d,t; 15 | scanf("%d",&t); 16 | for(j=0;j> &mat, int N, int M, int X) 4 | { 5 | int i=0,j=M-1; 6 | while(i=0){ 7 | if(mat[i][j]==X) return 1; 8 | else if(mat[i][j] 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n,k,count=0; 9 | cin >> n >> k; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | sort(arr,arr+n); 13 | while(((k+1)*count)n-1-count;i--) max+=arr[i]; 17 | cout << min << " " << max << endl; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Shuffle integers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void shuffle(int arr[],int l,int r){ 5 | if(r-l<=1) return; 6 | shuffle(arr,l+1,r-1); 7 | //cout << l << r << endl; 8 | for(int i=l+2;i<=r-1;i+=2){ 9 | //for(int i=l;i<=r;i++) cout << arr[i] << " "; 10 | //cout << endl; 11 | swap(arr[i-1],arr[i]); 12 | //for(int i=l;i<=r;i++) cout << arr[i] << " "; 13 | //cout << endl; 14 | } 15 | //cout << endl; 16 | } 17 | int main() 18 | { 19 | int t; 20 | scanf("%d",&t); 21 | while(t--){ 22 | int n; 23 | cin >> n; 24 | int arr[n]; 25 | for(int i=0;i> arr[i]; 26 | shuffle(arr,0,n-1); 27 | for(int i=0;i0){ 9 | if(arr[i]==k){ 10 | k++; 11 | } 12 | else if(arr[i]>k){ 13 | return k; 14 | } 15 | } 16 | } 17 | return k; 18 | } 19 | -------------------------------------------------------------------------------- /Sorting in Lists - Python: -------------------------------------------------------------------------------- 1 | # Function to sort using comparator 2 | def customSort(arr): 3 | 4 | return sorted(arr) 5 | # Your code here 6 | # Hint : Should be a return statement 7 | -------------------------------------------------------------------------------- /Space Seperated - Python: -------------------------------------------------------------------------------- 1 | # Function to print words with spaces 2 | def print_fun(): 3 | print("Geeks","For","Geeks") 4 | # Your code here 5 | # Do not use space in the string 6 | # try to use seperator 7 | -------------------------------------------------------------------------------- /Split the input - Python: -------------------------------------------------------------------------------- 1 | def inPutS(): 2 | a=input() ## input in a single line() 3 | s,i,f = a.split()## split the a into three parts: string, integer, and f. 4 | print(s+" "+str(int(i)+float(f))) ##type cast i to int, f to float. Add i with f. Typecast the result to string 5 | 6 | -------------------------------------------------------------------------------- /Stack/Delete middle element of a stack: -------------------------------------------------------------------------------- 1 | stack deleteMid(stacks,int sizeOfStack,int current) 2 | { 3 | if(current==(sizeOfStack/2)){ 4 | s.pop(); 5 | return s; 6 | } 7 | int temp=s.top(); 8 | s.pop(); 9 | s = deleteMid(s,sizeOfStack,current+1); 10 | s.push(temp); 11 | return s; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Stack/Easy string: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | string s; 9 | stack a; 10 | cin >> s; 11 | transform(s.begin(), s.end(), s.begin(), ::tolower); 12 | a.push(s[0]); 13 | int count=1; 14 | for(int i=1;i _push(int arr[],int n) 5 | { 6 | stack s; 7 | s.push(arr[0]); 8 | for(int i=1;is) 20 | { 21 | while(!s.empty()){ 22 | int t=s.top(); 23 | s.pop(); 24 | cout << t << " "; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Stack/Get minimum element from stack: -------------------------------------------------------------------------------- 1 | int _stack :: getMin() 2 | { 3 | if (s.empty()) return -1; 4 | return minEle; 5 | } 6 | int _stack ::pop() 7 | { 8 | int p; 9 | if (s.empty()) return -1; 10 | int t = s.top(); 11 | s.pop(); 12 | if (t < minEle) 13 | { 14 | p=minEle; 15 | minEle = 2*minEle - t; 16 | } 17 | else p=t; 18 | return p; 19 | } 20 | void _stack::push(int x) 21 | { 22 | if (s.empty()) 23 | { 24 | minEle = x; 25 | s.push(x); 26 | return; 27 | } 28 | if (x < minEle) 29 | { 30 | s.push(2*x - minEle); 31 | minEle = x; 32 | } 33 | else 34 | s.push(x); 35 | } 36 | -------------------------------------------------------------------------------- /Stack/Histogram Max Rectangular Area: -------------------------------------------------------------------------------- 1 | long long getMaxArea(vector arr) { 2 | long long maxArea=0; 3 | stack st; 4 | //int n=sizeof(arr)/sizeof(*arr); 5 | int n = arr.size(); 6 | for(int i=0;i<=n;i++){ 7 | while(!st.empty() && (arr[i] 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | string s; 9 | cin >> s; 10 | stack stk; 11 | int m=0; 12 | stk.push(-1); 13 | for(int i=0;i 2 | using namespace std; 3 | int main(){ 4 | int t; 5 | cin>>t; 6 | while(t--){ 7 | unsigned long long int n,p,sum=0; 8 | cin>>n; 9 | stack s; 10 | 11 | for(int i=0;i>p; 14 | sum=sum+p; 15 | s.push(p); 16 | } 17 | else{ 18 | cin>>p; 19 | if(s.top()+p>sum) 20 | sum=s.top()+p; 21 | s.push(p); 22 | } 23 | } 24 | cout< s; 4 | int ls[n], rs[n]; 5 | for(int i=0;i=A[i]) s.pop(); 7 | ls[i]=s.empty()?0:s.top(); 8 | s.push(A[i]); 9 | } 10 | while(!s.empty()) s.pop(); 11 | for(int i=n-1;i>=0;i--){ 12 | while(!s.empty() && s.top()>=A[i]) s.pop(); 13 | rs[i]=s.empty()?0:s.top(); 14 | s.push(A[i]); 15 | } 16 | int diff=0; 17 | for(int i=0;i 2 | using namespace std; 3 | #define ll long long 4 | 5 | void nge(ll arr[],ll n){ 6 | stack s; 7 | vector ans(n); 8 | for(int i = n-1; i >= 0; i--) { 9 | while(!s.empty() && arr[i] >= s.top()) s.pop(); 10 | ans[i] = s.empty() ? -1 : s.top(); 11 | s.push(arr[i]); 12 | } 13 | for(int i = 0; i < n; i++) cout << ans[i] << " "; 14 | } 15 | int main() 16 | { 17 | int t; 18 | scanf("%d",&t); 19 | while(t--){ 20 | ll n,i; 21 | cin >> n; 22 | ll arr[n]; 23 | for(i=0;i> arr[i]; 24 | nge(arr,n); 25 | cout< s) 2 | { 3 | if(s.size()==1) return true; 4 | while(s.size()!=1){ 5 | int r = s.top(); 6 | s.pop(); 7 | if((r-1)!=s.top() && (r+1)!=s.top()) return 0; 8 | } 9 | return 1; 10 | } 11 | -------------------------------------------------------------------------------- /Stack/Print Bracket Number: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | vector barcketNumbers(string S) 5 | { 6 | vector v; 7 | stack stk; 8 | int count=1; 9 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | long long n; 9 | cin >> n; 10 | stack s; 11 | s.push(n%10); 12 | n=n/10; 13 | while(n){ 14 | if((n%10)!=s.top()) s.push(n%10); 15 | n/=10; 16 | } 17 | while(!s.empty()){ 18 | cout< s; 3 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 12 | stack s; 13 | s.push(0); 14 | long long sum=0; 15 | for(int i=n-1;i>=0;i--){ 16 | while(s.top()<=arr[i] && s.size()>1) s.pop(); 17 | sum=(sum+s.top())%1000000001; 18 | s.push(arr[i]); 19 | } 20 | cout << sum << endl; 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Stack/Smallest number on left: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int temp; 11 | stack s; 12 | s.push(-1); 13 | cout << s.top() << " "; 14 | n--; 15 | cin >> temp; 16 | s.push(temp); 17 | while(n--){ 18 | cin >> temp; 19 | while(s.top()>=temp) s.pop(); 20 | cout << s.top() << " "; 21 | s.push(temp); 22 | } 23 | cout << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Stack/Sort a stack: -------------------------------------------------------------------------------- 1 | /*The structure of the class is 2 | class SortedStack{ 3 | public: 4 | stack s; 5 | void sort(); 6 | }; 7 | */ 8 | 9 | /* The below method sorts the stack s 10 | you are required to complete the below method */ 11 | 12 | void SortedStack :: sort(){ 13 | stack stk; 14 | while(!s.empty()){ 15 | int x = s.top(); 16 | s.pop(); 17 | while(!stk.empty() && stk.top()>x){ 18 | s.push(stk.top()); 19 | stk.pop(); 20 | } 21 | stk.push(x); 22 | } 23 | while(!stk.empty()){ 24 | cout< mine; 2 | void push(int a){ 3 | if(s.empty()){ 4 | s.push(a); 5 | mine.push(a); 6 | return; 7 | } 8 | if(a<=mine.top()) mine.push(a); 9 | s.push(a); 10 | return; 11 | } 12 | bool isFull(int n) 13 | { 14 | return (s.size()>=n); 15 | } 16 | bool isEmpty() 17 | { 18 | return s.empty(); 19 | } 20 | int pop() 21 | { 22 | if(s.top()==mine.top()) mine.pop(); 23 | int t=s.top(); 24 | s.pop(); 25 | return t; 26 | } 27 | 28 | int getMin() 29 | { 30 | return mine.top(); 31 | } 32 | -------------------------------------------------------------------------------- /Stack/Stack designer: -------------------------------------------------------------------------------- 1 | stack_push(int arr[],int n) 2 | { 3 | stack s; 4 | for(int i=0;is) 12 | { 13 | while(!s.empty()){ 14 | cout << s.top() << " "; 15 | s.pop(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Stack/String Manipulation: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | stack s; 9 | int n; 10 | string temp; 11 | cin >> n; 12 | for(int i=0;i> temp; 14 | if(s.empty()) s.push(temp); 15 | else if(s.top()==temp) s.pop(); 16 | else s.push(temp); 17 | } 18 | cout << s.size() << endl; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Stack/The Celebrity Problem: -------------------------------------------------------------------------------- 1 | int getId(int M[MAX][MAX], int n) 2 | { 3 | stack s; 4 | for(int i=0;i1){ 6 | int a=s.top(); 7 | s.pop(); 8 | int b=s.top(); 9 | s.pop(); 10 | if(M[a][b]==1) s.push(b); 11 | else s.push(a); 12 | } 13 | int x=s.top(); 14 | for(int i=0;i stk; 5 | int m=0; 6 | stk.push(-1); 7 | for(int i=0;i &res) 2 | { 3 | 4 | if (chk.size() == 2 * n) 5 | { 6 | res.push_back(chk); 7 | return; 8 | } 9 | 10 | if (open < n) 11 | { 12 | chk.push_back('('); 13 | solve(n, chk, open + 1, close,res); 14 | chk.pop_back(); 15 | } 16 | 17 | if (close < open) 18 | { 19 | chk.push_back(')'); 20 | solve(n, chk, open, close + 1,res); 21 | chk.pop_back(); 22 | } 23 | } 24 | vector AllParenthesis(int n) 25 | { 26 | vector res; 27 | string chk = ""; 28 | solve(n, chk, 0, 0,res); 29 | return res; 30 | } 31 | -------------------------------------------------------------------------------- /String/Generate binary string: -------------------------------------------------------------------------------- 1 | void fun(int i, string t, string s, vector &ans){ 2 | if(i==s.size()){ 3 | ans.push_back(t); 4 | return; 5 | } 6 | if(s[i] == '?'){ 7 | fun(i+1, t+'0', s,ans); 8 | fun(i+1, t+'1', s,ans); 9 | } 10 | else{ 11 | fun(i+1,t+s[i],s,ans); 12 | } 13 | return; 14 | } 15 | vector generate_binary_string(string s) 16 | { 17 | vector ans; 18 | fun(0,"",s,ans); 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /String/Group Shifted String: -------------------------------------------------------------------------------- 1 | vector> groupShiftedString(vector &arr) { 2 | unordered_map> groups; 3 | for (string s : arr) { 4 | string pattern = ""; 5 | for (int i = 1; i < s.size(); i++) { 6 | int diff = (s[i] - s[i-1] + 26) % 26; 7 | pattern += to_string(diff) + ","; 8 | } 9 | if (s.size() == 1) { 10 | pattern = "single"; 11 | } 12 | groups[pattern].push_back(s); 13 | } 14 | vector> result; 15 | for (auto &group : groups) { 16 | result.push_back(group.second); 17 | } 18 | return result; 19 | } 20 | -------------------------------------------------------------------------------- /String/Implement Atoi: -------------------------------------------------------------------------------- 1 | int atoi(string str) { 2 | int ans=0,flag=1,i=0; 3 | if(str[0]=='-'){ 4 | flag = -1; 5 | i+=1; 6 | } 7 | for(;i='0' && str[i]<='9'){ 9 | ans*=10; 10 | ans+=str[i]-'0'; 11 | } 12 | else return -1; 13 | } 14 | return flag*ans; 15 | } 16 | -------------------------------------------------------------------------------- /String/Isomorphic Strings: -------------------------------------------------------------------------------- 1 | bool check(string s1,string s2){ 2 | int n=s1.length(); 3 | unordered_map charMap; 4 | for(int i=0;i=0;i--) { 5 | if(S[i]== '-') continue; 6 | if(count==K) { 7 | ans += '-'; 8 | count=0; 9 | } 10 | ans += toupper(S[i]); 11 | count++; 12 | } 13 | reverse(ans.begin(),ans.end()); 14 | return ans; 15 | } 16 | -------------------------------------------------------------------------------- /String/Longest K unique characters substring: -------------------------------------------------------------------------------- 1 | int longestKSubstr(string s, int k) { 2 | unordered_map mp; 3 | int l=0,r=0,len=-1,n=s.size(); 4 | while(r k){ 13 | mp[s[l]]--; 14 | if(mp[s[l]] == 0) 15 | mp.erase(s[l]); 16 | l++; 17 | } 18 | if(mp.size()==k){ 19 | len = max (len,r-l+1); 20 | } 21 | r++; 22 | } 23 | return len; 24 | } 25 | -------------------------------------------------------------------------------- /String/Meta Strings: -------------------------------------------------------------------------------- 1 | bool metaStrings (string S1, string S2) 2 | { 3 | int n = S1.length(); 4 | int m = S2.length(); 5 | if(n!=m || S1==S2) return false; 6 | char c1 = '&'; 7 | char c2 = '&'; 8 | int notMatch = 0; 9 | for(int i=0;i 2) 13 | return false; 14 | else if(c1=='&' && c2=='&'){ 15 | c1=S1[i]; 16 | c2=S2[i]; 17 | } 18 | else if(c1 != S2[i] || c2 != S1[i]) 19 | return false; 20 | } 21 | } 22 | if(notMatch==2) 23 | return true; 24 | return false; 25 | } 26 | -------------------------------------------------------------------------------- /String/Minimum sum: -------------------------------------------------------------------------------- 1 | string solve(int arr[], int n) { 2 | sort(arr,arr+n); 3 | string ans; 4 | int i = n-1,j=n-2; 5 | int carry=0; 6 | while(i>=0 || j>=0 || carry !=0){ 7 | int sum = carry; 8 | if(i>=0) sum+=arr[i]; 9 | if(j>=0) sum+=arr[j]; 10 | carry = sum/10; 11 | if(sum) 12 | ans = char(sum%10+'0')+ans; 13 | i-=2; 14 | j-=2; 15 | } 16 | return (ans == "")? "0":ans; 17 | } 18 | -------------------------------------------------------------------------------- /String/Remove b and ac from a given string: -------------------------------------------------------------------------------- 1 | string stringFilter(string str) 2 | { 3 | string ans = ""; 4 | int i = 0; 5 | int n = str.length(); 6 | while(i < n){ 7 | if(str[i] == 'b'){ 8 | i++; 9 | continue; 10 | } 11 | else if(str[i] == 'a' && i+1 2 | using namespace std; 3 | bool subArrayExists(int arr[], int n) 4 | { 5 | unordered_map sum; 6 | int pre=0; 7 | for(int i=0;i> t; 22 | while (t--) { 23 | int n, i; 24 | cin >> n; 25 | int arr[n]; 26 | for (i = 0; i < n; i++) { 27 | cin >> arr[i]; 28 | } 29 | if(subArrayExists(arr,n)){ 30 | cout << "Yes" << endl; 31 | } 32 | else 33 | cout << "No" << endl; 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Subarray with given sum: -------------------------------------------------------------------------------- 1 | // Function to find the subarray with given sum k 2 | // arr: input array 3 | // n: size of array 4 | void subarraySum(int a[], int n, int s){ 5 | int sum=a[0],start=0,i; 6 | for(i=1;i<=n;i++){ 7 | while(sum>s && start < (i-1)){ 8 | sum-=a[start]; 9 | start++; 10 | } 11 | if(sum==s){ 12 | cout<n){ 20 | cout<<-1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Subarray with given sum new: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n, curr , i, start = 0, end = 0, sum; 9 | cin >> n >> sum; 10 | int arr[n]; 11 | for (i = 0; i < n; i++) 12 | cin >> arr[i]; 13 | curr = arr[0]; 14 | for (i = 1; i <= n; i++) { 15 | while (curr > sum and start < i - 1) { 16 | curr -= arr[start]; 17 | start++; 18 | } 19 | if (sum == curr) { 20 | cout << start + 1 << " " << end + 1<< endl; 21 | break; 22 | } 23 | if (i < n) { 24 | curr += arr[i]; 25 | end++; 26 | } 27 | } 28 | if (i == n + 1) { 29 | cout << -1 << endl; 30 | } 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Subset Sums: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector ans; 4 | 5 | void subsum(int arr[],int l,int r,int sum=0){ 6 | if(l>r){ 7 | ans.push_back(sum); 8 | return; 9 | } 10 | subsum(arr,l+1,r,sum+arr[l]); 11 | subsum(arr,l+1,r,sum); 12 | } 13 | 14 | int main() 15 | { 16 | int t; 17 | scanf("%d",&t); 18 | while(t--){ 19 | int n; 20 | ans.clear(); 21 | cin >> n; 22 | int arr[n]; 23 | //unordered_set arr; 24 | for(int i=0;i> arr[i]; 25 | subsum(arr,0,n-1); 26 | sort(ans.begin(),ans.end()); 27 | //int x = 1>>n; 28 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | for(int i=0;i> arr[i]; 13 | } 14 | int sum =0; 15 | sort(arr,arr+n); 16 | for(int i=0;i 2 | using namespace std; 3 | int count; 4 | void toh(int n,char from,char to,char aux){ 5 | if(n==1){ 6 | cout<<"move disk 1 from rod "<> n; 22 | ::count=0; 23 | toh(n,'1','3','2'); 24 | cout << ::count << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Tree/BST/Add all greater values to every node in a BST: -------------------------------------------------------------------------------- 1 | void fun(Node* root,int &sum){ 2 | if(!root) return; 3 | fun(root->right,sum); 4 | sum+=root->data; 5 | root->data=sum; 6 | fun(root->left,sum); 7 | } 8 | Node* modify(Node *root) 9 | { 10 | int sum=0; 11 | fun(root,sum); 12 | return root; 13 | } 14 | -------------------------------------------------------------------------------- /Tree/BST/Array to BST: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void BST(vector nums,int l,int r,vector &res){ 4 | if(l>r) return; 5 | int mid=l+(r-l)/2; 6 | res.push_back(nums[mid]); 7 | BST(nums,l,mid-1,res); 8 | BST(nums,mid+1,r,res); 9 | } 10 | vector sortedArrayToBST(vector& nums) { 11 | vector res; 12 | int n=nums.size(); 13 | BST(nums,0,n-1,res); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Tree/BST/Check for BST: -------------------------------------------------------------------------------- 1 | bool fun(Node* root,Node* &prev){ 2 | if(root){ 3 | if(!fun(root->left,prev)) return false; 4 | if(prev!=NULL && root->data<= prev->data) return false; 5 | prev=root; 6 | return fun(root->right,prev); 7 | } 8 | return true; 9 | } 10 | bool isBST(Node* root) { 11 | Node* prev=NULL; 12 | return fun(root,prev); 13 | } 14 | -------------------------------------------------------------------------------- /Tree/BST/Construct BST from Postorder: -------------------------------------------------------------------------------- 1 | Node* BST(Node* root,int d){ 2 | if(root==NULL) root=new Node(d); 3 | else if(root->data>d) root->left=BST(root->left,d); 4 | else root->right=BST(root->right,d); 5 | return root; 6 | } 7 | Node *constructTree (int post[], int size) 8 | { 9 | Node* root=NULL; 10 | for(int i=size-1;i>=0;i--) root=BST(root,post[i]); 11 | return root; 12 | } 13 | -------------------------------------------------------------------------------- /Tree/BST/Count BST nodes that lie in a given range: -------------------------------------------------------------------------------- 1 | void fun(Node*root,int l,int h, int &count) { 2 | if(!root) return ; 3 | if(root->data >= l && root->data <= h ){ 4 | count++; 5 | fun(root->left,l,h,count); 6 | fun(root->right,l,h,count); 7 | } 8 | if(root->data < l) fun(root->right,l,h,count); 9 | if(root->data > h) fun(root->left,l,h,count); 10 | return; 11 | } 12 | int getCount(Node *root, int l, int h) { 13 | int count=0; 14 | fun(root,l,h,count); 15 | return count; 16 | } 17 | -------------------------------------------------------------------------------- /Tree/BST/Delete a node from BST: -------------------------------------------------------------------------------- 1 | Node *deleteNode(Node *root, int X) 2 | { 3 | if(!root) return NULL; 4 | if(X>root->data) root->right = deleteNode(root->right,X); 5 | else if(Xdata) root->left = deleteNode(root->left,X); 6 | if(root->data==X){ 7 | Node *t1=root,*t2=root; 8 | while(t1->right!=NULL) t1=t1->right; 9 | if(t1==root) return NULL; 10 | while(t2->right!=t1 && t2->right!=NULL) t2=t2->right; 11 | root->data=t1->data; 12 | t2->right=NULL; 13 | } 14 | return root; 15 | } 16 | -------------------------------------------------------------------------------- /Tree/BST/Expression Tree: -------------------------------------------------------------------------------- 1 | int evalTree(node* root) { 2 | if(root!=NULL){ 3 | if(root->left==NULL && root->right==NULL) return stoi(root->data); 4 | int a=evalTree(root->left); 5 | int b=evalTree(root->right); 6 | if(root->data=="+") return a+b; 7 | else if(root->data=="-") return a-b; 8 | else if(root->data=="*") return a*b; 9 | else return a/b; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tree/BST/Find a pair with given target in BST: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | // root : the root Node of the given BST 4 | // target : the target sum 5 | void inOrder(Node* root,vector &v){ 6 | if(!root) return; 7 | inOrder(root->left,v); 8 | v.push_back(root->data); 9 | inOrder(root->right,v); 10 | } 11 | int isPairPresent(struct Node *root, int target) 12 | { 13 | vector v; 14 | inOrder(root,v); 15 | int i=0,j=v.size()-1; 16 | while(idata==K){ 7 | diff=0; 8 | return; 9 | } 10 | diff=min(diff,abs(root->data-K)); 11 | if(Kdata) fun(root->left,K,diff); 12 | else fun(root->right,K,diff); 13 | } 14 | } 15 | int minDiff(Node *root, int K) 16 | { 17 | int diff=INT_MAX; 18 | fun(root,K,diff); 19 | return diff; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Tree/BST/Inorder Successor in BST: -------------------------------------------------------------------------------- 1 | Node * inOrderSuccessor(Node *root, Node *x) 2 | { 3 | if(root==NULL) return NULL; 4 | Node *t=NULL; 5 | if(root->data<=x->data) t=inOrderSuccessor(root->right,x); 6 | else if(root->data>x->data) { 7 | t=inOrderSuccessor(root->left,x); 8 | if(t==NULL) t=root; 9 | } 10 | return t; 11 | } 12 | -------------------------------------------------------------------------------- /Tree/BST/Insert a node in a BST: -------------------------------------------------------------------------------- 1 | Node* insert(Node* root, int Key) 2 | { 3 | Node* t=root; 4 | while(true){ 5 | if(t->data==Key) return root; 6 | if(t->data>Key){ 7 | if(t->left==NULL){ 8 | t->left = new Node(Key); 9 | return root; 10 | } 11 | t=t->left; 12 | } 13 | else{ 14 | if(t->right==NULL){ 15 | t->right = new Node(Key); 16 | return root; 17 | } 18 | t=t->right; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Tree/BST/Kth largest element in BST: -------------------------------------------------------------------------------- 1 | void fun(Node* root,int k,int &count,int &ans){ 2 | if(root==NULL || count>=k) return; 3 | fun(root->right,k,count,ans); 4 | count++; 5 | if(count==k){ 6 | ans=root->data; 7 | return; 8 | } 9 | fun(root->left,k,count,ans); 10 | 11 | } 12 | int kthLargest(Node *root, int K) 13 | { 14 | int count=0,ans=0; 15 | fun(root,K,count,ans); 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Tree/BST/Largest BST: -------------------------------------------------------------------------------- 1 | bool isBST(Node* root,int min,int max){ 2 | if(!root) return true; 3 | if(root->data<=min || root->data>=max) return false; 4 | return (isBST(root->left,min,root->data) && isBST(root->right,root->data,max)); 5 | } 6 | int size(Node* root){ 7 | if(!root) return 0; 8 | return size(root->left)+1+size(root->right); 9 | } 10 | int largestBst(Node *root) 11 | { 12 | if(isBST(root,INT_MIN,INT_MAX)) return size(root); 13 | return max(largestBst(root->left),largestBst(root->right)); 14 | } 15 | -------------------------------------------------------------------------------- /Tree/BST/Lowest Common Ancestor in a BST: -------------------------------------------------------------------------------- 1 | Node* LCA(Node *root, int n1, int n2) 2 | { 3 | while(root!=NULL){ 4 | if(root->data>n1 && root->data>n2) root=root->left; 5 | else if(root->datadataright; 6 | else break; 7 | } 8 | return root; 9 | } 10 | -------------------------------------------------------------------------------- /Tree/BST/Minimum element in BST: -------------------------------------------------------------------------------- 1 | int minValue(Node* root) 2 | { 3 | if(root==NULL) return -1; 4 | while(root->left!=NULL) root=root->left; 5 | return root->data; 6 | } 7 | -------------------------------------------------------------------------------- /Tree/BST/Print BST elements in given range: -------------------------------------------------------------------------------- 1 | void fun(Node *root, int l, int h, vector &v){ 2 | if(!root) return; 3 | if(root->data>l) fun(root->left,l,h,v); 4 | if(root->data>=l && root->data<=h) v.push_back(root->data); 5 | if(root->dataright,l,h,v); 6 | } 7 | vector printNearNodes(Node *root, int low, int high) 8 | { 9 | vector v; 10 | fun(root,low,high,v); 11 | return v; 12 | } 13 | -------------------------------------------------------------------------------- /Tree/BST/Search a node in BST: -------------------------------------------------------------------------------- 1 | struct Node { 2 | int data; 3 | Node* right; 4 | Node* left; 5 | 6 | Node(int x){ 7 | data = x; 8 | right = NULL; 9 | left = NULL; 10 | } 11 | }; 12 | */ 13 | 14 | /*You are required to complete this method*/ 15 | bool search(Node* root, int x) 16 | { 17 | if(root==NULL) return false; 18 | if(root->data==x) return true; 19 | return(root->data>x)? search(root->left,x):search(root->right,x); 20 | } 21 | -------------------------------------------------------------------------------- /Tree/BST/Serialize and Deserialize a Binary Tree: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | public: 4 | void fun(Node *root,vector &A) 5 | { 6 | if(root==NULL){ 7 | A.push_back(-1); 8 | return; 9 | } 10 | A.push_back(root->data); 11 | fun(root->left,A); 12 | fun(root->right,A); 13 | } 14 | vector serialize(Node *root) { 15 | vector A; 16 | fun(root,A); 17 | return A; 18 | } 19 | /*this function deserializes 20 | the serialized vector A*/ 21 | int pre=0; 22 | Node * deSerialize(vector &A) 23 | { 24 | if (pre == A.size() || A[pre] == -1) { 25 | pre ++; 26 | return NULL; 27 | } 28 | Node *root = new Node(A[pre]); 29 | pre++; 30 | root->left = deSerialize(A); 31 | root->right = deSerialize(A); 32 | return root; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Tree/BST/k-th smallest element in BST: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | void fun(Node*root,int &ksmall,int &kthsmall){ 4 | if(!root) return; 5 | fun(root->left,ksmall,kthsmall); 6 | if(ksmall>0){ 7 | kthsmall=root->data; 8 | ksmall--; 9 | } 10 | fun(root->right,ksmall,kthsmall); 11 | } 12 | // Return the Kth smallest element in the given BST 13 | int KthSmallestElement(Node *root, int K) 14 | { 15 | int ksmall=K,kthsmall=0; 16 | fun(root,ksmall,kthsmall); 17 | if(ksmall!=0) return -1; 18 | return kthsmall; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Tree/Binary Tree to DLL: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to convert binary tree to doubly linked list and return it. 5 | void fun(Node* root,Node **head){ 6 | if(!root) return; 7 | static Node* prev = NULL; 8 | fun(root->left,head); 9 | if(!*head) *head = root; 10 | else{ 11 | root->left = prev; 12 | prev->right = root; 13 | } 14 | prev=root; 15 | fun(root->right,head); 16 | } 17 | Node * bToDLL(Node *root) 18 | { 19 | Node* head=NULL; 20 | fun(root,&head); 21 | return head; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Tree/Bottom View of Binary Tree: -------------------------------------------------------------------------------- 1 | vector bottomView(Node *root) 2 | { 3 | vector res; 4 | map> m; 5 | int h=0; 6 | queue > q; 7 | q.push(make_pair(root,h)); 8 | while(!q.empty()){ 9 | pair t=q.front(); 10 | q.pop(); 11 | h=t.second; 12 | Node* node=t.first; 13 | m[h].push_back(node->data); 14 | if(node->left) q.push(make_pair(node->left,h-1)); 15 | if(node->right) q.push(make_pair(node->right,h+1)); 16 | } 17 | map> :: iterator it; 18 | for(it=m.begin();it!=m.end();it++){ 19 | int n=it->second.size(); 20 | res.push_back(it->second[n-1]); 21 | } 22 | return res; 23 | } 24 | -------------------------------------------------------------------------------- /Tree/Check for Balanced Tree: -------------------------------------------------------------------------------- 1 | int height(Node *root){ 2 | if(root==NULL) return 0; 3 | return(1+max(height(root->left),height(root->right))); 4 | } 5 | bool isBalanced(Node *root) 6 | { 7 | if(root==NULL) return true; 8 | int lh=height(root->left); 9 | int rh=height(root->right); 10 | return(abs(lh-rh)<=1 && isBalanced(root->left) && isBalanced(root->right)); 11 | } 12 | -------------------------------------------------------------------------------- /Tree/Connect Nodes at Same Level: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | public: 4 | void connect(Node *root) 5 | { 6 | queue q; 7 | q.push(root); 8 | Node*t,*prev; 9 | while(!q.empty()){ 10 | prev=NULL; 11 | int size=q.size(); 12 | for(int i=0;inextRight=NULL; 16 | if(prev) prev->nextRight=t; 17 | prev=t; 18 | if(t->left) q.push(t->left); 19 | if(t->right) q.push(t->right); 20 | } 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Tree/Connect Nodes at Same Level Of Tree: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | void connect(Node *root) 4 | { 5 | queue q; 6 | q.push(root); 7 | 8 | while(!q.empty()){ 9 | Node*prev = NULL; 10 | int size = q.size(); 11 | while(size--){ 12 | Node* curr = q.front(); 13 | q.pop(); 14 | if(prev !=NULL){ 15 | prev->nextRight = curr; 16 | } 17 | prev = curr; 18 | if(curr->left) q.push(curr->left); 19 | if(curr->right) q.push(curr->right); 20 | } 21 | prev->nextRight = NULL; 22 | } 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Tree/Construct Binary Tree from Parent Array: -------------------------------------------------------------------------------- 1 | Node *createTree(int parent[], int N) 2 | { 3 | vector v; 4 | for(int i=0;ileft==NULL) v[parent[i]]->left=v[i]; 12 | else if(parent[i]!=-1 && v[parent[i]]->right==NULL) v[parent[i]]->right=v[i]; 13 | } 14 | return v[root]; 15 | } 16 | -------------------------------------------------------------------------------- /Tree/Construct Tree from Inorder & Preorder: -------------------------------------------------------------------------------- 1 | int p; 2 | int search(int in[],int start,int end,int x){ 3 | int i; 4 | for(i=start;i<=end;i++){ 5 | if(x==in[i]){ 6 | return i; 7 | } 8 | } 9 | } 10 | Node* construct(int in[],int pre[],int start,int end){ 11 | if(start>end) return NULL; 12 | Node* t=new Node(pre[p++]); 13 | if(start==end) return t; 14 | int idx=search(in,start,end,t->data); 15 | t->left=construct(in,pre,start,idx-1); 16 | t->right=construct(in,pre,idx+1,end); 17 | return t; 18 | } 19 | Node* buildTree(int in[],int pre[], int n){ 20 | p=0; 21 | return construct(in,pre,0,n-1); 22 | } 23 | -------------------------------------------------------------------------------- /Tree/Count Leaves in Binary Tree: -------------------------------------------------------------------------------- 1 | int countLeaves(Node* root) 2 | { 3 | if(root==NULL) return 0; 4 | if(root->left==NULL && root->right==NULL) return 1; 5 | return(countLeaves(root->left)+countLeaves(root->right)); 6 | } 7 | -------------------------------------------------------------------------------- /Tree/Count Non-Leaf Nodes in Tree: -------------------------------------------------------------------------------- 1 | /*Structure of the node of the tree is as 2 | struct Node 3 | { 4 | int data; 5 | struct Node* left; 6 | struct Node* right; 7 | }; 8 | */ 9 | // you are required to complete this function 10 | // the function should return the count of Non-Leaf Nodes 11 | int countNonLeafNodes(Node* root) 12 | { 13 | if(root==NULL) return 0; 14 | if(root->left == NULL && root->right == NULL) return 0; 15 | return 1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right); 16 | } 17 | -------------------------------------------------------------------------------- /Tree/Count Number of SubTrees having given Sum: -------------------------------------------------------------------------------- 1 | int check(Node* root,int x,int &count){ 2 | if(!root) return 0; 3 | int l=check(root->left,x,count); 4 | int r=check(root->right,x,count); 5 | if(l+r+root->data==x) count++; 6 | return l+r+root->data; 7 | 8 | } 9 | int countSubtreesWithSumX(Node* root, int X) 10 | { 11 | int count=0; 12 | check(root,X,count); 13 | return count; 14 | } 15 | -------------------------------------------------------------------------------- /Tree/Diagonal Traversal of Binary Tree: -------------------------------------------------------------------------------- 1 | vector diagonal(Node *root) 2 | { 3 | vector v; 4 | queue q; 5 | q.push(root); 6 | while(!q.empty()){ 7 | Node* t=q.front(); 8 | q.pop(); 9 | while(t){ 10 | v.push_back(t->data); 11 | if(t->left) q.push(t->left); 12 | t=t->right; 13 | } 14 | } 15 | return v; 16 | } 17 | -------------------------------------------------------------------------------- /Tree/Diameter of Binary Tree: -------------------------------------------------------------------------------- 1 | int height(Node *root){ 2 | if(root == NULL) return 0; 3 | return max(height(root->left)+1,height(root->right)+1); 4 | } 5 | int diameter(Node* root) { 6 | if(root == NULL) return 0; 7 | int rootleft = height(root->left); 8 | int rootright = height(root->right); 9 | int leftnodediameter = diameter(root->left); 10 | int rightnodediameter = diameter(root->right); 11 | return max(rootleft+rootright+1,max(leftnodediameter,rightnodediameter)); 12 | } 13 | -------------------------------------------------------------------------------- /Tree/Does array represent Heap: -------------------------------------------------------------------------------- 1 | bool isMaxHeap(int a[], int n) 2 | { 3 | for (int i=0; i<=(n-2)/2; i++) 4 | { 5 | // If left child is greater, return false 6 | if (2*i+1 < n && a[2*i +1] > a[i]) 7 | return false; 8 | 9 | // If right child is greater, return false 10 | if (2*i+2 < n && a[2*i+2] > a[i]) 11 | return false; 12 | } 13 | return true; 14 | } 15 | -------------------------------------------------------------------------------- /Tree/Duplicate Subtree: -------------------------------------------------------------------------------- 1 | string solve(Node *root, unordered_map &mp){ 2 | if(!root) return ""; 3 | 4 | string s = ""; 5 | 6 | if(!root->left && !root->right){ 7 | s += root->data; 8 | return s; 9 | } 10 | 11 | s = solve(root->left, mp) + root->data + solve(root->right, mp); 12 | mp[s]++; 13 | 14 | return s; 15 | } 16 | int dupSub(Node *root) { 17 | unordered_map mp; 18 | solve(root, mp); 19 | 20 | for(auto i: mp){ 21 | if(i.second >= 2) return true; 22 | } 23 | return false; 24 | } 25 | -------------------------------------------------------------------------------- /Tree/Full Binary Tree from Preorder and Postorder - Lalit Sir: -------------------------------------------------------------------------------- 1 | struct Node{ 2 | int key; 3 | Node *left,*right; 4 | } 5 | struct NewNode{ 6 | Node* node= new Node(); 7 | 8 | } 9 | Node *construct(){ 10 | 11 | } 12 | Node *ConstructBinaryTree(vector){ 13 | 14 | } 15 | int main(){ 16 | vector 17 | } 18 | -------------------------------------------------------------------------------- /Tree/Height of Binary Tree: -------------------------------------------------------------------------------- 1 | struct Node 2 | { 3 | int data; 4 | struct Node* left; 5 | struct Node* right; 6 | 7 | Node(int x){ 8 | data = x; 9 | left = right = NULL; 10 | } 11 | }; 12 | */ 13 | class Solution{ 14 | public: 15 | int height(struct Node* node){ 16 | return(node)? 1+max(height(node->left),height(node->right)):0; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Tree/Height of Heap: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int heapHeight(int N, int arr[]){ 4 | int c=N-1,h=0; 5 | while(c){ 6 | c=(c-1)/2; 7 | h++; 8 | } 9 | return h; 10 | } 11 | }; 12 | 13 | 14 | OR -->> 15 | 16 | class Solution{ 17 | public: 18 | int heapHeight(int N, int arr[]){ 19 | return ceil(log2(N + 1)) - 1; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Tree/Inorder Traversal: -------------------------------------------------------------------------------- 1 | 2 | /* A binary tree node has data, pointer to left child 3 | and a pointer to right child 4 | struct Node { 5 | int data; 6 | Node *left; 7 | Node *right; 8 | 9 | Node(int val) { 10 | data = val; 11 | left = right = NULL; 12 | } 13 | }; */ 14 | 15 | void inorderFun(Node *root, vector &res){ 16 | if (root == NULL)return; 17 | inorderFun(root->left, res); 18 | res.push_back (root->data); 19 | inorderFun(root->right, res); 20 | } 21 | vector inOrder(struct Node *root) { 22 | vector res; 23 | inorderFun(root, res); 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /Tree/Inorder Traversal (Iterative): -------------------------------------------------------------------------------- 1 | vector inOrder(Node* root) 2 | { 3 | vector v; 4 | stack s; 5 | Node* curr=root; 6 | while(curr || !s.empty()){ 7 | while(curr){ 8 | s.push(curr); 9 | curr=curr->left; 10 | } 11 | curr=s.top(); 12 | s.pop(); 13 | v.push_back(curr->data); 14 | curr = curr->right; 15 | } 16 | return v; 17 | } 18 | -------------------------------------------------------------------------------- /Tree/K distance from root: -------------------------------------------------------------------------------- 1 | vector Kdistance(struct Node *root, int k) 2 | { 3 | vector v; 4 | if(root==NULL) return v; 5 | queue q; 6 | q.push(root); 7 | k++; 8 | while(k--){ 9 | v.clear(); 10 | int size=q.size(); 11 | while(size--){ 12 | Node* t=q.front(); 13 | q.pop(); 14 | v.push_back(t->data); 15 | if(t->left!=NULL) q.push(t->left); 16 | if(t->right!=NULL) q.push(t->right); 17 | } 18 | } 19 | return v; 20 | } 21 | -------------------------------------------------------------------------------- /Tree/Kth Ancestor in a Tree: -------------------------------------------------------------------------------- 1 | bool solve(Node* root, int &count, int node, int &val){ 2 | if(!root) return false; 3 | if(root->data == node) return true; 4 | int l = solve(root->left,count, node, val); 5 | int r = solve(root->right,count, node, val); 6 | if(l||r){ 7 | count--; 8 | if(count == 0 ) val = root->data; 9 | return true; 10 | } 11 | return false; 12 | } 13 | int kthAncestor(Node *root, int k, int node) 14 | { 15 | int val = -1, count =k; 16 | 17 | solve(root , count, node , val); 18 | 19 | return val; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Tree/Left View of Binary Tree: -------------------------------------------------------------------------------- 1 | vector leftView(Node *root) 2 | { 3 | vector v; 4 | if(root==NULL) return v; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()){ 8 | int n=q.size(); 9 | for(int i=1;i<=n;i++){ 10 | Node* temp = q.front(); 11 | q.pop(); 12 | if(i==1) v.push_back(temp->data); 13 | if(temp->left!=NULL) q.push(temp->left); 14 | if(temp->right!=NULL) q.push(temp->right); 15 | } 16 | } 17 | return v; 18 | } 19 | -------------------------------------------------------------------------------- /Tree/Level order traversal: -------------------------------------------------------------------------------- 1 | vector levelOrder(Node* node) 2 | { 3 | vector v; 4 | if(node==NULL) return v; 5 | queue q; 6 | q.push(node); 7 | while(!q.empty()){ 8 | Node* t=q.front(); 9 | q.pop(); 10 | v.push_back(t->data); 11 | if(t->left!=NULL) q.push(t->left); 12 | if(t->right!=NULL) q.push(t->right); 13 | } 14 | return v; 15 | } 16 | -------------------------------------------------------------------------------- /Tree/Level order traversal Line by Line: -------------------------------------------------------------------------------- 1 | vector> levelOrder(Node* node) 2 | { 3 | vector> v; 4 | vector a; 5 | if(node==NULL) return v; 6 | queue q; 7 | q.push(node); 8 | int i=0; 9 | while(!q.empty()){ 10 | int size=q.size(); 11 | while(size--){ 12 | Node* t=q.front(); 13 | q.pop(); 14 | a.push_back(t->data); 15 | if(t->left!=NULL) q.push(t->left); 16 | if(t->right!=NULL) q.push(t->right); 17 | } 18 | v.push_back(a); 19 | a.clear(); 20 | } 21 | return v; 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Tree/Level order traversal in spiral form: -------------------------------------------------------------------------------- 1 | vector findSpiral(Node *root) 2 | { 3 | vector v; 4 | if(root==NULL) return v; 5 | stack s1; 6 | stack s2; 7 | s1.push(root); 8 | while(!s1.empty() || !s2.empty()){ 9 | while(!s1.empty()){ 10 | Node* t=s1.top(); 11 | s1.pop(); 12 | v.push_back(t->data); 13 | if(t->right)s2.push(t->right); 14 | if(t->left)s2.push(t->left); 15 | } 16 | while(!s2.empty()){ 17 | Node* t=s2.top(); 18 | s2.pop(); 19 | v.push_back(t->data); 20 | if(t->left) s1.push(t->left); 21 | if(t->right) s1.push(t->right); 22 | } 23 | } 24 | return v; 25 | } 26 | -------------------------------------------------------------------------------- /Tree/Lowest Common Ancestor in a Binary Tree: -------------------------------------------------------------------------------- 1 | Node* lca(Node* root ,int n1 ,int n2 ) 2 | { 3 | if(root==NULL) return root; 4 | if(root->data==n1 || root->data==n2) return root; 5 | Node* l=lca(root->left,n1,n2); 6 | Node* r=lca(root->right,n1,n2); 7 | if(l && r) return root; 8 | return (l==NULL)? r:l; 9 | } 10 | -------------------------------------------------------------------------------- /Tree/Maximum Path Sum between 2 Leaf Nodes: -------------------------------------------------------------------------------- 1 | int ans; 2 | int fun(Node* root){ 3 | if(!root) return INT_MIN; 4 | int l=fun(root->left); 5 | int r=fun(root->right); 6 | if(root->left && root->right) ans=max(ans,l+r+root->data); 7 | if(l==INT_MIN && r==INT_MIN) return root->data; 8 | else return max(l,r)+root->data; 9 | } 10 | int maxPathSum(Node* root) 11 | { 12 | ans=INT_MIN; 13 | fun(root); 14 | return ans; 15 | } 16 | -------------------------------------------------------------------------------- /Tree/Maximum Width of Tree: -------------------------------------------------------------------------------- 1 | int getMaxWidth(Node* root) 2 | { 3 | if(root==NULL) return 0; 4 | int m=0; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()){ 8 | //cout << q.size() << " "<< max<data << endl; 14 | q.pop(); 15 | if(t->left) q.push(t->left); 16 | if(t->right) q.push(t->right); 17 | } 18 | } 19 | return m; 20 | } 21 | -------------------------------------------------------------------------------- /Tree/Maximum difference between node and its ancestor: -------------------------------------------------------------------------------- 1 | int fun(Node* root,int &diff){ 2 | if(!root) return INT_MAX; 3 | if(!root->left && !root->right) return root->data; 4 | int l = fun(root->left,diff); 5 | int r = fun(root->right,diff); 6 | int m = min(l,r); 7 | diff = max(diff,root->data-m); 8 | //cout << l << " " << r<< " " << root->data << " " << diff << " " << endl; 9 | return min(m,root->data); 10 | } 11 | int maxDiff(Node* root) 12 | { 13 | int diff=INT_MIN; 14 | fun(root,diff); 15 | return diff; 16 | } 17 | -------------------------------------------------------------------------------- /Tree/Min distance between two given nodes of a Binary Tree: -------------------------------------------------------------------------------- 1 | Node* lca(Node* root,int a,int b){ 2 | if(!root) return NULL; 3 | Node *l=NULL,*r=NULL; 4 | if(root->data==a || root->data==b) return root; 5 | l=lca(root->left,a,b); 6 | r=lca(root->right,a,b); 7 | if(l && r) return root; 8 | return (l)?l:r; 9 | } 10 | int dist(Node* root,int x,int d){ 11 | if(!root) return -1; 12 | if(root->data==x)return d; 13 | int l=dist(root->left,x,d+1); 14 | int r=dist(root->right,x,d+1); 15 | return max(l,r); 16 | } 17 | int findDist(Node* root, int a, int b) { 18 | Node *anc= lca(root,a,b); 19 | int l=dist(anc,a,0); 20 | int r=dist(anc,b,0); 21 | return l+r; 22 | } 23 | -------------------------------------------------------------------------------- /Tree/Minimum Depth of a Binary Tree: -------------------------------------------------------------------------------- 1 | void height(Node* root,int h,int &ans){ 2 | if(root==NULL) return; 3 | if(root->left==NULL && root->right==NULL) ans=min(h,ans); 4 | if(root->left) height(root->left,h+1,ans); 5 | if(root->right) height(root->right,h+1,ans); 6 | } 7 | int minDepth(Node *node) { 8 | if(node==NULL) return 0; 9 | int h=1,ans=INT_MAX; 10 | height(node,h,ans); 11 | return ans; 12 | } 13 | -------------------------------------------------------------------------------- /Tree/Mirror Tree: -------------------------------------------------------------------------------- 1 | METHOD 1 ( USING QUEUE ) --> 2 | ------------------------ 3 | 4 | void mirror(Node* node) 5 | { 6 | if(node==NULL) return; 7 | queue q; 8 | q.push(node); 9 | while(!q.empty()){ 10 | Node* t=q.front(); 11 | q.pop(); 12 | swap(t->left,t->right); 13 | if(t->left) q.push(t->left); 14 | if(t->right) q.push(t->right); 15 | } 16 | return; 17 | } 18 | 19 | METHOD 2 ( USING RECURSION )--> 20 | ---------------------------- 21 | 22 | void mirror(Node* node) 23 | { 24 | if(node == NULL) return; 25 | mirror(node->left); 26 | mirror(node->right); 27 | Node* t=node->left; 28 | node->left=node->right; 29 | node->right=t; 30 | return; 31 | } 32 | -------------------------------------------------------------------------------- /Tree/Populate Inorder Successor for all nodes: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void populateNextNode(Node *root, Node* &prev){ 4 | if(!root) return; 5 | populateNextNode(root->left,prev); 6 | if(prev) prev->next = root; 7 | prev = root; 8 | populateNextNode(root->right,prev); 9 | } 10 | void populateNext(Node *root) { 11 | Node* prev=NULL; 12 | populateNextNode(root,prev); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Tree/Postorder Traversal: -------------------------------------------------------------------------------- 1 | /* A binary tree node has data, pointer to left child 2 | and a pointer to right child 3 | struct Node 4 | { 5 | int data; 6 | struct Node* left; 7 | struct Node* right; 8 | }; */ 9 | void fun(Node *root,vector &res){ 10 | if(root==NULL) return; 11 | fun(root->left,res); 12 | fun(root->right,res); 13 | res.push_back(root->data); 14 | } 15 | vector postOrder(Node* root) 16 | { 17 | vector res; 18 | fun(root,res); 19 | return res; 20 | } 21 | -------------------------------------------------------------------------------- /Tree/Postorder Traversal (Iterative): -------------------------------------------------------------------------------- 1 | vector postOrder(Node* node) { 2 | vector v; 3 | stack s; 4 | s.push(node); 5 | while(!s.empty()){ 6 | Node* t=s.top(); 7 | v.push_back(t->data); 8 | s.pop(); 9 | if(t->left) s.push(t->left); 10 | if(t->right) s.push(t->right); 11 | } 12 | reverse(v.begin(),v.end()); 13 | return v; 14 | } 15 | -------------------------------------------------------------------------------- /Tree/Preorder Traversal: -------------------------------------------------------------------------------- 1 | /* A binary tree node has data, pointer to left child 2 | and a pointer to right child 3 | 4 | /* 5 | struct Node 6 | { 7 | int data; 8 | struct Node* left; 9 | struct Node* right; 10 | 11 | Node(int x){ 12 | data = x; 13 | left = right = NULL; 14 | } 15 | }; 16 | */ 17 | 18 | void fun(Node *root,vector &res){ 19 | if(root==NULL) return; 20 | res.push_back(root->data); 21 | fun(root->left,res); 22 | fun(root->right,res); 23 | } 24 | vector preorder(Node* root) 25 | { 26 | vector res; 27 | fun(root,res); 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /Tree/Preorder traversal (Iterative): -------------------------------------------------------------------------------- 1 | vector preOrder(Node* root) 2 | { 3 | vector v; 4 | stack s; 5 | s.push(root); 6 | while(!s.empty()){ 7 | Node* t=s.top(); 8 | v.push_back(t->data); 9 | s.pop(); 10 | if(t->right) s.push(t->right); 11 | if(t->left) s.push(t->left); 12 | } 13 | return v; 14 | } 15 | -------------------------------------------------------------------------------- /Tree/Print all nodes that don't have sibling: -------------------------------------------------------------------------------- 1 | void fun(Node *root,vector &v){ 2 | if(root==NULL) return; 3 | if(root->left!=NULL && root->right==NULL)v.push_back(root->left->data); 4 | if(root->right!=NULL && root->left==NULL)v.push_back(root->right->data); 5 | if(root->left) fun(root->left,v); 6 | if(root->right) fun(root->right,v); 7 | return; 8 | } 9 | vector noSibling(Node* node) 10 | { 11 | vector v; 12 | fun(node,v); 13 | if(v.empty()) v.push_back(-1); 14 | else sort(v.begin(),v.end()); 15 | return v; 16 | } 17 | -------------------------------------------------------------------------------- /Tree/Remove Half Nodes: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* helper(Node* root){ 4 | if(!root) return NULL; 5 | root->left = helper(root->left); 6 | root->right = helper(root->right); 7 | if(!root->left && root->right) 8 | return root->right; 9 | if(root->left && !root->right) 10 | return root->left; 11 | return root; 12 | } 13 | Node *RemoveHalfNodes(Node *root) { 14 | return helper(root); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Tree/Reverse Level Order Traversal: -------------------------------------------------------------------------------- 1 | vector reverseLevelOrder(Node *root) 2 | { 3 | vector v; 4 | if(root==NULL) return v; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()){ 8 | Node* t=q.front(); 9 | q.pop(); 10 | v.push_back(t->data); 11 | if(t->right!=NULL) q.push(t->right); 12 | if(t->left!=NULL) q.push(t->left); 13 | } 14 | reverse(v.begin(),v.end()); 15 | return v; 16 | } 17 | -------------------------------------------------------------------------------- /Tree/Right View of Binary Tree: -------------------------------------------------------------------------------- 1 | vector rightView(Node *root) 2 | { 3 | vector v; 4 | if(root==NULL) return v; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()){ 8 | int size=q.size(); 9 | for(int i=1;i<=size;i++){ 10 | Node* t=q.front(); 11 | q.pop(); 12 | if(i==size) v.push_back(t->data); 13 | if(t->left != NULL) q.push(t->left); 14 | if(t->right != NULL) q.push(t->right); 15 | } 16 | } 17 | return v; 18 | } 19 | -------------------------------------------------------------------------------- /Tree/Root to leaf path sum: -------------------------------------------------------------------------------- 1 | bool hasPathSum(Node *root, int S){ 2 | if(root==NULL) return (S==0); 3 | bool ans=false; 4 | S-=root->data; 5 | if(S==0 && root->left==NULL && root->right==NULL) return true; 6 | if(root->left!=NULL) ans = ans || hasPathSum(root->left,S); 7 | if(root->right!=NULL) ans = ans || hasPathSum(root->right,S); 8 | return ans; 9 | } 10 | -------------------------------------------------------------------------------- /Tree/Size of Binary Tree: -------------------------------------------------------------------------------- 1 | int getSize(Node* node) 2 | { 3 | return(node)?getSize(node->left)+getSize(node->right)+1:0; 4 | } 5 | -------------------------------------------------------------------------------- /Tree/Sum Tree: -------------------------------------------------------------------------------- 1 | int sumtree(Node*root){ 2 | if(root==NULL) return 0; 3 | if(root->left==NULL && root->right==NULL) return root->data; 4 | if(root->data==sumtree(root->left)+sumtree(root->right)) return 2*root->data; 5 | } 6 | bool isSumTree(Node* root) 7 | { 8 | if(root==NULL) return true; 9 | if(root->data==sumtree(root)/2) return true; 10 | return false; 11 | } 12 | -------------------------------------------------------------------------------- /Tree/Sum of Binary Tree: -------------------------------------------------------------------------------- 1 | struct Node 2 | { 3 | int key; 4 | Node* left, *right; 5 | }; 6 | */ 7 | // Function should return the sum of all the elements 8 | // of the binary tree 9 | long int sumBT(Node* root) 10 | { 11 | return(root==NULL)?0:root->key+sumBT(root->left)+sumBT(root->right); 12 | } 13 | -------------------------------------------------------------------------------- /Tree/Symmetric Tree: -------------------------------------------------------------------------------- 1 | bool fun(Node* r1 , Node* r2){ 2 | if(r1==NULL && r2==NULL) 3 | return true; 4 | if(r1!=NULL && r2!=NULL && r1->data==r2->data) 5 | return(fun(r1->left,r2->right) && fun(r1->right,r2->left)); 6 | return false; 7 | } 8 | bool isSymmetric(struct Node* root) 9 | { 10 | return fun(root,root); 11 | } 12 | -------------------------------------------------------------------------------- /Tree/Top View of Binary Tree: -------------------------------------------------------------------------------- 1 | vector topView(struct Node *root) 2 | { 3 | vector res; 4 | map> m; 5 | int h=0; 6 | queue > q; 7 | q.push(make_pair(root,h)); 8 | while(!q.empty()){ 9 | pair t=q.front(); 10 | q.pop(); 11 | h=t.second; 12 | Node* node=t.first; 13 | m[h].push_back(node->data); 14 | if(node->left) q.push(make_pair(node->left,h-1)); 15 | if(node->right) q.push(make_pair(node->right,h+1)); 16 | } 17 | map> :: iterator it; 18 | for(it=m.begin();it!=m.end();it++){ 19 | res.push_back(it->second[0]); 20 | } 21 | return res; 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Tree/Transform to Sum Tree: -------------------------------------------------------------------------------- 1 | int fun(Node *root){ 2 | if(!root) return 0; 3 | int val=root->data; 4 | root->data=fun(root->left)+fun(root->right); 5 | return val+root->data; 6 | } 7 | void toSumTree(Node *node) 8 | { 9 | if(!node) return; 10 | fun(node); 11 | return; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Tree/Tree from Postorder and Inorder: -------------------------------------------------------------------------------- 1 | int p; 2 | int search(int in[],int start,int end,int x){ 3 | int i; 4 | for(i=start;i<=end;i++){ 5 | if(x==in[i]){ 6 | return i; 7 | } 8 | } 9 | } 10 | Node* construct(int in[],int post[],int start,int end){ 11 | if(start>end) return NULL; 12 | Node* t=new Node(post[p--]); 13 | if(start==end) return t; 14 | int idx=search(in,start,end,t->data); 15 | t->right=construct(in,post,idx+1,end); 16 | t->left=construct(in,post,start,idx-1); 17 | return t; 18 | } 19 | 20 | Node *buildTree(int in[], int post[], int n) { 21 | p=n-1; 22 | return construct(in,post,0,n-1); 23 | } 24 | 25 | 26 | //If we don't want search function we can use unordered map to store data and index pair and use that. 27 | -------------------------------------------------------------------------------- /Two Mirror Trees: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int areMirror(Node* a, Node* b) { 5 | if(!a && !b) return true; 6 | if(a && b && a->data==b->data) 7 | return areMirror(a->left,b->right) && areMirror(a->right,b->left); 8 | return false; 9 | } 10 | 11 | }; 12 | -------------------------------------------------------------------------------- /Variable Arguments - Python: -------------------------------------------------------------------------------- 1 | def multivar(a, *var): 2 | sum=a 3 | for i in range(0,len(var)): 4 | sum+=var[i] 5 | 6 | print (sum) 7 | ##*var takes multiple arguments inside it 8 | ##print the sum of a+elements of var 9 | 10 | -------------------------------------------------------------------------------- /Welcome aboard - Python: -------------------------------------------------------------------------------- 1 | # Function to Welcome the person 2 | def welcomeAboard(name): 3 | print ("Welcome",name) # Your code here 4 | 5 | -------------------------------------------------------------------------------- /Winner of an election: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | scanf("%d",&t); 7 | while(t--){ 8 | int n; 9 | cin >> n; 10 | string s; 11 | string ans; 12 | int max=0; 13 | map m; 14 | for(int i=0;i> s; 16 | m[s]++; 17 | if(m[s]>max){ 18 | max=m[s]; 19 | ans=s; 20 | } 21 | if(max==m[s])ans=min(ans,s); 22 | } 23 | cout << ans << " " << max << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Zero Converter - python: -------------------------------------------------------------------------------- 1 | def pos(n): 2 | for i in range(n-1,-1,-1): 3 | print(i,end=' ') 4 | 5 | def neg(n): 6 | for i in range(n,1,1): 7 | print(i,end=' ') 8 | 9 | -------------------------------------------------------------------------------- /getchar and putchar - C: -------------------------------------------------------------------------------- 1 | void get_put(char ch) 2 | { 3 | // your code here 4 | 5 | ch = getchar();// take input using getchar 6 | putchar(ch); 7 | //print using putchar 8 | } 9 | -------------------------------------------------------------------------------- /module 1 contest: -------------------------------------------------------------------------------- 1 | def digitsSum(n): 2 | ##Your code here 3 | sum=0 4 | while(n>0): 5 | res=n%10 6 | sum+=res 7 | n=n//10 8 | return sum 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | def mean(d,m): 18 | ##Your code here 19 | return ((d+(m*3))//4) 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /module 2 contest: -------------------------------------------------------------------------------- 1 | def aweSum(a, b): 2 | sum=a+b 3 | if(sum>19 and sum<41): 4 | return 42 5 | else: 6 | return sum 7 | 8 | 9 | def doge_count(str): 10 | count=0 11 | for i in range(0,len(str)-3): 12 | if(str[i]=='d' and str[i+1]=='o' and str[i+3]=='e'): 13 | count+=1 14 | return count 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /module 3 - contest: -------------------------------------------------------------------------------- 1 | def copyCat(str): 2 | return (str[-2:]*3) 3 | 4 | 5 | def boom(str): 6 | if(str[-4:]=='boom'): 7 | return True 8 | else: 9 | return False 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /module 4 - contest: -------------------------------------------------------------------------------- 1 | sum=lambda x,y:x+y 2 | 3 | 4 | 5 | class Cuboid: 6 | def __init__(self,l,b,h): 7 | self.l=l 8 | self.b=b 9 | self.h=h 10 | def getArea(self): 11 | return self.l*self.h*self.b 12 | def increaseDimensions(self): 13 | self.l=self.l+1 14 | self.b=self.b+1 15 | self.h=self.h+1 16 | def deepCopy(self,obj): 17 | self.l=obj.l 18 | self.b=obj.b 19 | self.h=obj.h##Your code here 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /module 5 - contest: -------------------------------------------------------------------------------- 1 | def has44(mylist): 2 | for i in range(0,len(mylist)-1): 3 | if(mylist[i]==4 and mylist[i+1]==4): 4 | return True 5 | return False 6 | 7 | 8 | 9 | 10 | 11 | def avg(mylist): 12 | temp=mylist 13 | temp.remove(min(temp)) 14 | temp.remove(max(temp)) 15 | s=sum(temp) 16 | s=s//len(temp) 17 | return s 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sep and end in Print(): -------------------------------------------------------------------------------- 1 | #Function using 'end' and 'sep' parameters to print desired output 2 | string1 = "Geeks" 3 | string2 = "For" 4 | def print_func(string1, string2): 5 | print ( string1,string2 ,string1 , sep = '$', end = '$') 6 | # Use string1 & string2 with sep and end parameter to print desired output 7 | --------------------------------------------------------------------------------