├── .gitattributes ├── .gitignore ├── Difficulty: Medium ├── Jump Game │ ├── README.md │ └── jump-game.java └── Topological sort │ ├── README.md │ └── topological-sort.java ├── arrays ├── ConvertArrayInZigZagManner.cpp ├── ElementOnLeftSideIsSmallerAndRightIsGreater.cpp ├── EquilibriumPoint.cpp ├── LastIndexOfOne.cpp ├── MaximumIndex.cpp ├── MaximumRectangularAreaInHistogram.cpp ├── RearrangeArrayAlternately.cpp ├── ReverseArrayInGroups.cpp ├── SequentialDigits.cpp ├── SmallestNumberOnLeft.cpp ├── StockBuySell.cpp ├── SubarrayWithGivenSum.cpp ├── TrappingRainWater.cpp ├── chocolate_distribution_problem.cpp ├── closest_sum_to_zero.cpp ├── count_possible_triangles.cpp ├── count_triplets.cpp ├── equilibrium_point.cpp ├── inversion_of_array.cpp ├── kadaneAlgorithm.cpp ├── kth_smallest_element.cpp ├── leaders_in_array.cpp ├── merge_without_extra_space.cpp ├── minimum_platforms.cpp ├── missing_number_in_array.cpp ├── number_of_pairs.cpp ├── rearrange_array_alternatively.cpp └── sort_0s_1s_2s.cpp ├── backtracking ├── N_queenProblem.cpp ├── RatInMazeProblem.cpp └── SolveTheSuduko.cpp ├── bit magic ├── bit_difference.cpp ├── check_kth_bit.cpp ├── first_set_bit.cpp ├── maximum_subset_xor.cpp ├── party_of_couples.cpp ├── powerOf2.cpp ├── rightmost_different_bit.cpp ├── rotate_bits.cpp ├── set_kth_bit.cpp └── toggle_bits_in_range.cpp ├── divide and conquer ├── BinarySearch.cpp ├── KthElementOfTwoSortedArrays.cpp ├── MergeSort.cpp ├── SearchInRotatedArray.cpp ├── SumOfMiddleElementsOfTwoSortedArray.cpp ├── element_appeared_once_in_sorted_array.cpp └── search_in_rotated_array.cpp ├── dynamic programming ├── 0-1Knapsack.cpp ├── BoxStacking.cpp ├── EggDropPuzzle.cpp ├── LongestCommonSubsequence.cpp ├── LongestCommonSubstring.cpp ├── LongestIncreasingSubsequence.cpp ├── LongestPathInMatrix.cpp ├── MaxLengthChain.cpp ├── MaximizeCutSegments.cpp ├── MaximumSumIncreasingSubsequence.cpp ├── MinimumNoOfJumps.cpp ├── MinimumOperations.cpp ├── MinimumSumPartition.cpp ├── NoOfWaysToCoverDistance.cpp ├── OptimalStrategyForGame.cpp ├── PartitionEqualSubsetSum.cpp ├── ShortestCommonSupersequence.cpp ├── coin_change.cpp └── edit_distance.cpp ├── graph ├── AlienDictionary.cpp ├── CircleOfStrings.cpp ├── DetectCycleInDirectedGraph.cpp ├── DetectCycleInUndirectedGraph.cpp ├── FindIfPathExists.cpp ├── FindNoOfIslands.cpp ├── FloydWarshall.cpp ├── Kosaraju'sAlgo.cpp ├── MinimumCostPath.cpp ├── MinimumSwapToSort.cpp ├── ShortestSourceToDestinationPath.cpp ├── SnakeAndLadder.cpp ├── StronglyConnectedComponents.cpp ├── WordBoggle.cpp ├── bfs.cpp ├── dfs.cpp └── topologicalSort.cpp ├── greedy ├── ActivitySelection.cpp ├── GeekCollectsTheBall.cpp ├── MaximizeToys.cpp ├── MinimizeTheSumOfProduct.cpp ├── N_meeting_in_a_room.cpp └── ShopInCandyStore.cpp ├── hashing ├── ArrayPairSumDivisibiltyProblem.cpp ├── CommonElements.cpp ├── CountDistinctElementInEveryWindow.cpp ├── FindAllSumFourNumber.cpp ├── LargestSubarrayWith0sum.cpp ├── LongestConsecutiveSubsequence.cpp ├── SortArrayAccordingToOther.cpp ├── SortingArrayOnFrequency.cpp └── SwappingPairsMakeSumEqual.cpp ├── linked list ├── FlatteningLinkedList.cpp ├── IntersectionPointInY-ShapedLinkedList.cpp ├── LoopInLinkedList.cpp ├── NthNodeFromEndOfLinkedList.cpp ├── RemoveLoopInLinkedList.cpp ├── ReverseLinkedListInGivenGroup.cpp ├── finding_middle_element.cpp ├── reverse_linked_list.cpp └── rotate_linked_list.cpp ├── recursion ├── DecodeString.cpp ├── floodFill.cpp ├── josephusProblem.cpp ├── numberOfPaths.cpp └── specialKeyboard.cpp ├── stack and queue ├── DecodeString.cpp ├── GetMinElementFromStack.cpp ├── QueueUsingTwoStack.cpp ├── StackUsingTwoQueue.cpp └── parenthesis_checker.cpp ├── string ├── Anagram.cpp ├── FormPalindrome.cpp ├── ImplementAtoi.cpp ├── ImplementStrstr.cpp ├── LongestCommonPrefix.cpp ├── LongestCommonPrefixInArray.cpp ├── LongestDistinctCharacter.cpp ├── PermutationOfString.cpp ├── RemoveDuplicates.cpp ├── ReverseWordInString.cpp ├── RomanToInteger.cpp └── RotateStringByTwoPlace.cpp └── tree and bst ├── BinaryTreeToDLL.cpp ├── BottomViewOfBinaryTree.cpp ├── ConnectNodesAtSameLevel.cpp ├── CountLeafNodes.cpp ├── HeightOfBinaryTree.cpp ├── LevelOrderTraversalInSpiralForm.cpp ├── LowestCommonAncestorInBinaryTree.cpp ├── MaximumSumBSTBinaryTree.cpp ├── MirrorTree.cpp ├── RecursivelyRemoveAllAdjacentDuplicates.cpp ├── SerializeAndDeserializeBinaryTree.cpp ├── SumTree.cpp ├── SymmetricTree.cpp ├── VerticalTraversalOfBinaryTree.cpp ├── check_for_bst.cpp └── left_view_of_binary_tee.cpp /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.bin 3 | *.prob -------------------------------------------------------------------------------- /Difficulty: Medium/Jump Game/README.md: -------------------------------------------------------------------------------- 1 |

Jump Game

Difficulty Level : Difficulty: Medium


Given an positive integer N and a list of N integers A[]. Each element in the array denotes the maximum length of jump you can cover. Find out if you can make it to the last index if you start at the first index of the list.

2 | 3 |


4 | Example 1:

5 | 6 |
Input:
 7 | N = 6
 8 | A[] = {1, 2, 0, 3, 0, 0} 
 9 | Output:
10 | 1
11 | Explanation:
12 | Jump 1 step from first index to
13 | second index. Then jump 2 steps to reach 
14 | 4th index, and now jump 2 steps to reach
15 | the end.
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input:
21 | N = 3
22 | A[] =  {1, 0, 2}
23 | Output:
24 | 0
25 | Explanation:
26 | You can't reach the end of the array.
27 | 
28 | 29 |


30 | Your Task:
31 | You don't need to read input or print anything. Your task is to complete the function canReach() which takes a Integer N and a list A of size N as input and returns 1 if the end of the array is reachable, else return 0.

32 | 33 |


34 | Expected Time Complexity: O(N)
35 | Expected Auxiliary Space: O(1)

36 | 37 |


38 | Constraints:
39 | 1 <= N <= 105
40 | 0 <= A[i] <= 105

41 |

Company Tags :
Amazon Microsoft Google Facebook 

Topic Tags :
Arrays Dynamic Programming Greedy Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Medium/Jump Game/jump-game.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class GFG { 6 | public static void main(String args[]) throws IOException { 7 | BufferedReader read = 8 | new BufferedReader(new InputStreamReader(System.in)); 9 | int t = Integer.parseInt(read.readLine()); 10 | while (t-- > 0) { 11 | int N = Integer.parseInt(read.readLine()); 12 | 13 | String S1[] = read.readLine().split(" "); 14 | 15 | int[] A = new int[N]; 16 | 17 | for(int i=0; i 0) { 13 | ArrayList> list = new ArrayList<>(); 14 | String st[] = read.readLine().trim().split("\\s+"); 15 | int edg = Integer.parseInt(st[0]); 16 | int nov = Integer.parseInt(st[1]); 17 | 18 | for (int i = 0; i < nov; i++) 19 | list.add(i, new ArrayList()); 20 | 21 | int p = 0; 22 | for (int i = 1; i <= edg; i++) { 23 | String s[] = read.readLine().trim().split("\\s+"); 24 | int u = Integer.parseInt(s[0]); 25 | int v = Integer.parseInt(s[1]); 26 | list.get(u).add(v); 27 | } 28 | 29 | int[] res = new Solution().topoSort(nov, list); 30 | 31 | if (check(list, nov, res) == true) 32 | System.out.println("1"); 33 | else 34 | System.out.println("0"); 35 | } 36 | } 37 | static boolean check(ArrayList> list, int V, int[] res) { 38 | 39 | if(V!=res.length) 40 | return false; 41 | 42 | int[] map = new int[V]; 43 | for (int i = 0; i < V; i++) { 44 | map[res[i]] = i; 45 | } 46 | for (int i = 0; i < V; i++) { 47 | for (int v : list.get(i)) { 48 | if (map[i] > map[v]) return false; 49 | } 50 | } 51 | return true; 52 | } 53 | } 54 | 55 | // } Driver Code Ends 56 | 57 | 58 | /*Complete the function below*/ 59 | 60 | 61 | class Solution 62 | { 63 | //Function to return list containing vertices in Topological order. 64 | 65 | public static void dfs(int i, ArrayList> adj, Stack ans, boolean[] vis){ 66 | vis[i] = true; 67 | 68 | for(int j=0; j> adj) 78 | { 79 | // add your code here 80 | Stack st = new Stack(); 81 | 82 | int n = adj.size(); 83 | boolean[] vis = new boolean[V]; 84 | 85 | for(int i=0; i < V; i++){ 86 | if(!vis[i]){ 87 | dfs(i, adj, st, vis); 88 | } 89 | } 90 | 91 | int[] ans = new int[n]; 92 | 93 | for(int i=0; i 3 | 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | //User function template for C++ 11 | class Solution{ 12 | public: 13 | // Program for zig-zag conversion of array 14 | void zigZag(int arr[], int n) { 15 | // code here 16 | for(int i=0; i arr[i+1]){ 26 | continue; 27 | }else{ 28 | swap(arr[i], arr[i+1]); 29 | } 30 | } 31 | } 32 | } 33 | }; 34 | 35 | // { Driver Code Starts. 36 | 37 | int main() { 38 | int t; 39 | cin >> t; 40 | while (t--) { 41 | int n; 42 | cin >> n; 43 | int arr[n]; 44 | for (int i = 0; i < n; i++) { 45 | cin >> arr[i]; 46 | } 47 | Solution ob; 48 | ob.zigZag(arr, n); 49 | for (int i = 0; i < n; i++) { 50 | cout << arr[i] << " "; 51 | } 52 | cout << "\n"; 53 | } 54 | return 0; 55 | } 56 | // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/ElementOnLeftSideIsSmallerAndRightIsGreater.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int findElement(int arr[], int n); 6 | 7 | int main() { 8 | int t; 9 | cin >> t; 10 | while (t--) { 11 | int n, i; 12 | cin >> n; 13 | int a[n]; 14 | for (i = 0; i < n; i++) cin >> a[i]; 15 | cout << findElement(a, n) << endl; 16 | } 17 | return 0; 18 | } 19 | // } Driver Code Ends 20 | 21 | 22 | int findElement(int arr[], int n) { 23 | int min = arr[0]; 24 | int max = arr[n-1]; 25 | for(int i=1; i= arr[j]){ 31 | j++; 32 | }else{ 33 | flag = 1; 34 | break; 35 | } 36 | } 37 | if(flag == 0){ 38 | while(k>i){ 39 | if(arr[i] <= arr[k]){ 40 | k--; 41 | }else{ 42 | break; 43 | } 44 | } 45 | if(k == i){ 46 | return arr[i]; 47 | } 48 | } 49 | } 50 | return -1; 51 | } -------------------------------------------------------------------------------- /arrays/EquilibriumPoint.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // Position this line where user code will be pasted. 6 | 7 | int equilibriumPoint(long long a[], int n); 8 | 9 | int main() { 10 | 11 | long long t; 12 | 13 | //taking testcases 14 | cin >> t; 15 | 16 | while (t--) { 17 | long long n; 18 | 19 | //taking input n 20 | cin >> n; 21 | long long a[n]; 22 | 23 | //adding elements to the array 24 | for (long long i = 0; i < n; i++) { 25 | cin >> a[i]; 26 | } 27 | 28 | //calling equilibriumPoint() function 29 | cout << equilibriumPoint(a, n) << endl; 30 | } 31 | return 0; 32 | } 33 | // } Driver Code Ends 34 | 35 | 36 | // Function to find equilibrium point 37 | // a: input array 38 | // n: size of array 39 | int equilibriumPoint(long long a[], int n) { 40 | 41 | // Your code here 42 | if(n == 1){ 43 | return 1; 44 | }else if(n == 2){ 45 | return -1; 46 | } 47 | int lsum[n]; 48 | int sum = 0; 49 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | 10 | 11 | class Solution{ 12 | public: 13 | int lastIndex(string s) 14 | { 15 | for(int i=s.size()-1; i>=0; i--){ 16 | if(s[i] == '1'){ 17 | return i; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | }; 24 | 25 | // { Driver Code Starts. 26 | 27 | int main() { 28 | long long t; 29 | cin >> t; 30 | while (t--) { 31 | string s; 32 | cin >> s; 33 | Solution ob; 34 | cout << ob.lastIndex(s) << endl; 35 | } 36 | return 0; 37 | } // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/MaximumIndex.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | 10 | // A[]: input array 11 | // N: size of array 12 | // Function to find the maximum index difference. 13 | int maxIndexDiff(int A[], int N) 14 | { 15 | // Your code here 16 | int max = 0; 17 | for(int i=0; i=i+max; j--){ 19 | if(A[j] >= A[i]){ 20 | if(j-i > max){ 21 | max = j-i; 22 | } 23 | } 24 | } 25 | 26 | } 27 | return max; 28 | } 29 | }; 30 | 31 | // { Driver Code Starts. 32 | 33 | /* Driver program to test above functions */ 34 | int main() 35 | { 36 | int T; 37 | //testcases 38 | cin>>T; 39 | while(T--){ 40 | int num; 41 | //size of array 42 | cin>>num; 43 | int arr[num]; 44 | 45 | //inserting elements 46 | for (int i = 0; i>arr[i]; 48 | Solution ob; 49 | 50 | //calling maxIndexDiff() function 51 | cout< 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution 8 | { 9 | public: 10 | long long getMaxArea(long long arr[], int n) 11 | { 12 | 13 | stack st; 14 | vector left(n),right(n); 15 | 16 | for(int i=0;i=0;i--){ 38 | while(!st.empty() && arr[i]<=arr[st.top()]){ 39 | st.pop(); 40 | } 41 | 42 | if(st.empty()){ 43 | right[i]=n-1; 44 | }else{ 45 | right[i]= st.top()-1; 46 | } 47 | st.push(i); 48 | 49 | } 50 | 51 | 52 | long long int res=0; 53 | for(int i=0;i>t; 71 | while(t--) 72 | { 73 | int n; 74 | cin>>n; 75 | 76 | long long arr[n]; 77 | for(int i=0;i>arr[i]; 79 | Solution ob; 80 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | // This function wants you to modify the given input 12 | // array and no need to return anything 13 | // arr: input array 14 | // n: size of array 15 | void rearrange(long long *arr, int n) 16 | { 17 | 18 | // Your code here 19 | int k=0; 20 | int j=n-1; 21 | int max = arr[n-1] + 1; 22 | int min = arr[0]; 23 | for(int i=0; i> t; 46 | 47 | while(t--){ 48 | 49 | //size of array 50 | int n; 51 | cin >> n; 52 | 53 | long long arr[n]; 54 | 55 | //adding elements to the array 56 | for(int i = 0;i> arr[i]; 58 | } 59 | 60 | //calling rearrange() function 61 | rearrange(arr, n); 62 | 63 | //printing the elements 64 | for (int i = 0; i < n; i++) 65 | cout << arr[i] << " "; 66 | 67 | cout << endl; 68 | } 69 | return 0; 70 | } 71 | // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/ReverseArrayInGroups.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function template for C++ 12 | 13 | class Solution{ 14 | public: 15 | void reverseInGroups(vector& arr, int n, int k){ 16 | // code here 17 | int i; 18 | for(i=0; i < n-k ; i+=k){ 19 | reverse(arr.begin()+i, arr.begin()+i+k); 20 | } 21 | reverse(arr.begin()+i , arr.begin()+n); 22 | } 23 | }; 24 | 25 | // { Driver Code Starts. 26 | int main() { 27 | int t; 28 | cin >> t; 29 | while(t--){ 30 | int n; 31 | cin >> n; 32 | vector arr; 33 | int k; 34 | cin >> k; 35 | 36 | for(long long i = 0; i> x; 40 | arr.push_back(x); 41 | } 42 | Solution ob; 43 | ob.reverseInGroups(arr, n, k); 44 | 45 | for(long long i = 0; i sequentialDigits(int low, int high) { 4 | vector v; 5 | int arr[36] = {12, 23, 34, 45, 56, 67, 78, 89, 6 | 123, 234, 345, 456, 567, 678, 789, 7 | 1234, 2345, 3456, 4567, 5678, 6789, 8 | 12345, 23456, 34567, 45678, 56789, 9 | 123456, 234567, 345678, 456789, 10 | 1234567, 2345678, 3456789, 11 | 12345678, 23456789, 12 | 123456789}; 13 | for(int i=0; i<36; i++){ 14 | if(arr[i] < low) continue; 15 | if(arr[i] > high) break; 16 | v.push_back(arr[i]); 17 | } 18 | 19 | // string digits = "123456789"; 20 | 21 | // int nl = to_string(low).length(); 22 | // int nh = to_string(high).length(); 23 | 24 | // for(int i=nl; i<=nh; i++){ 25 | // for(int j=0; j<10-i; j++){ 26 | // int num = stoi(digits.substr(j, i)); 27 | // if(num >= low && num <= high){ 28 | // v.push_back(num); 29 | // } 30 | // } 31 | // } 32 | return v; 33 | } 34 | }; -------------------------------------------------------------------------------- /arrays/SmallestNumberOnLeft.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | // class Solution{ 11 | // public: 12 | // vector leftSmaller(int n, int a[]){ 13 | // // code here 14 | // vector v; 15 | // for(int i=n-1; i>0; i--){ 16 | // for(int j=i-1; j>=0; j--){ 17 | // if(a[i] > a[j]){ 18 | // v.push_back(a[j]); 19 | // break; 20 | // } 21 | // if(j==0 && a[j] >= a[i]){ 22 | // v.push_back(-1); 23 | // } 24 | // } 25 | // } 26 | // v.push_back(-1); 27 | // reverse(v.begin(), v.end()); 28 | // return v; 29 | // } 30 | // }; 31 | 32 | class Solution{ 33 | public: 34 | vector leftSmaller(int n, int a[]){ 35 | // code here 36 | vector v; 37 | stack s; 38 | for(int i=0; i= a[i]){ 40 | s.pop(); 41 | } 42 | 43 | if(s.empty()){ 44 | v.push_back(-1); 45 | }else{ 46 | int a = s.top(); 47 | v.push_back(a); 48 | } 49 | 50 | s.push(a[i]); 51 | } 52 | return v; 53 | } 54 | }; 55 | 56 | // { Driver Code Starts. 57 | 58 | int main(){ 59 | int t; 60 | cin>>t; 61 | while(t--){ 62 | int n; 63 | cin>>n; 64 | int a[n]; 65 | for(int i = 0;i < n;i++) 66 | cin>>a[i]; 67 | 68 | Solution ob; 69 | vector ans = ob.leftSmaller(n, a); 70 | for(int i = 0;i < n;i++) 71 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function template for C++ 12 | 13 | class Solution{ 14 | public: 15 | vector > stockBuySell(vector A, int n){ 16 | // code here 17 | int max = 0; 18 | int left = 0; 19 | int right = 0; 20 | vector> v; 21 | vector ans; 22 | for(int i=0; i A[i]){ 24 | ans.push_back(i); 25 | while(A[i+1] >= A[i] && i>t; 44 | while(t--){ 45 | int n; 46 | cin>>n; 47 | vector A(n); 48 | for (int i=0; i>A[i]; 50 | } 51 | Solution ob; 52 | vector > ans = ob.stockBuySell(A, n); 53 | if(ans.size()==0) 54 | cout<<"No Profit"; 55 | else{ 56 | for (int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to find the subarray with given sum k 10 | // arr: input array 11 | // n: size of array 12 | vector subarraySum(int arr[], int n, int s){ 13 | 14 | // Your code here 15 | int left = 0, right = 0, sum = 0; 16 | vector ans; 17 | ans.push_back(-1); 18 | for(int i=0; i s){ 26 | sum -= arr[left++] + arr[i--]; 27 | } 28 | } 29 | return ans; 30 | } 31 | 32 | // { Driver Code Starts. 33 | 34 | int main() 35 | { 36 | int t; 37 | cin>>t; 38 | while(t--) 39 | { 40 | int n; 41 | long long s; 42 | cin>>n>>s; 43 | int arr[n]; 44 | 45 | for(int i=0;i>arr[i]; 47 | 48 | vectorres; 49 | res = subarraySum(arr, n, s); 50 | 51 | for(int i = 0;i 3 | 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | 11 | 12 | // function to find the trapped water in between buildings 13 | // arr: input array 14 | // n: size of array 15 | int trappingWater(int arr[], int n){ 16 | 17 | // Your code here 18 | if(n < 3){ 19 | return 0; 20 | } 21 | int r = n-1; 22 | int l = 0; 23 | int lmax = 0; 24 | int rmax = 0; 25 | int ans = 0; 26 | while(l <= r){ 27 | if(arr[l] <= arr[r]){ 28 | if(lmax < arr[l]) lmax = arr[l]; 29 | else ans+= lmax - arr[l]; 30 | l++; 31 | }else{ 32 | if(rmax < arr[r]) rmax = arr[r]; 33 | else ans+= rmax - arr[r]; 34 | r--; 35 | } 36 | } 37 | return ans; 38 | } 39 | 40 | // { Driver Code Starts. 41 | 42 | int main(){ 43 | 44 | int t; 45 | //testcases 46 | cin >> t; 47 | 48 | while(t--){ 49 | int n; 50 | 51 | //size of array 52 | cin >> n; 53 | 54 | int a[n]; 55 | 56 | //adding elements to the array 57 | for(int i =0;i> a[i]; 59 | } 60 | 61 | //calling trappingWater() function 62 | cout << trappingWater(a, n) << endl; 63 | 64 | } 65 | 66 | return 0; 67 | } // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/chocolate_distribution_problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int distribute(int arr[], int k, int n){ 5 | sort(arr, arr+n); 6 | int min = INT_MAX; 7 | for(int i=0; i> t; 23 | while(t--){ 24 | int n; 25 | cin >> n; 26 | int arr[n]; 27 | for(int i=0; i> arr[i]; 29 | } 30 | int k; 31 | cin >> k; 32 | cout << distribute(arr, k, n) << endl; 33 | } 34 | return 0; 35 | } -------------------------------------------------------------------------------- /arrays/closest_sum_to_zero.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | 10 | class Solution 11 | { 12 | public: 13 | int closestToZero(int arr[], int n) 14 | { 15 | // your code here 16 | sort (arr, arr + n); // sorting the array 17 | int i = 0, j = n - 1; 18 | int sum = arr[i] + arr[j]; // initializing sum 19 | int diff = abs (sum); // initializing the result 20 | 21 | while (i < j) 22 | { 23 | // if we have zero sum, there's no result better. Hence, we return 24 | if (arr[i] + arr[j] == 0) 25 | return 0; 26 | 27 | // if we get a better result, we update the difference 28 | if (abs (arr[i] + arr[j]) < abs (diff)) 29 | { 30 | diff = (arr[i] + arr[j]); 31 | sum = arr[i] + arr[j]; 32 | } 33 | 34 | // if the current sum is greater than zero, we search for a smaller sum 35 | if (arr[i] + arr[j] > 0) 36 | j--; 37 | // else, we search for a larger sum 38 | else 39 | i++; 40 | } 41 | return sum; 42 | } 43 | }; 44 | 45 | // { Driver Code Starts. 46 | int main () 47 | { 48 | int t; 49 | cin >> t; 50 | while (t--) 51 | { 52 | int n; 53 | cin >> n; 54 | int arr[n]; 55 | for (int i = 0; i < n; i++) 56 | cin >> arr[i]; 57 | Solution ob; 58 | cout << ob.closestToZero(arr, n) << endl; 59 | } 60 | } // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/count_possible_triangles.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | class Solution 10 | { 11 | public: 12 | int findNumberOfTriangles(int arr[], int n) 13 | { 14 | // code here 15 | sort(arr, arr+n); 16 | 17 | int count = 0; 18 | 19 | for(int c = n-1; c >= 2; c--) 20 | { 21 | int a = 0, b = c - 1; 22 | 23 | while(a < b) 24 | { 25 | if(arr[a] + arr[b] > arr[c]) 26 | { 27 | count += b - a; 28 | 29 | b--; 30 | } 31 | else 32 | { 33 | a++; 34 | } 35 | } 36 | } 37 | return count; 38 | } 39 | }; 40 | 41 | 42 | // { Driver Code Starts. 43 | 44 | int main() 45 | { 46 | int T; 47 | cin>>T; 48 | while(T--) 49 | { 50 | int n; 51 | cin>>n; 52 | int arr[n]; 53 | for(int i=0; i>arr[i]; 55 | Solution ob; 56 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | int t, n, i; 6 | cin >> t; 7 | while(t--){ 8 | cin >> n; 9 | int arr[n], ans = 0; 10 | for(i=0; i> arr[i]; 12 | }; 13 | 14 | sort(arr, arr+n); 15 | 16 | for(i=n-1; i>=0; i--){ 17 | int j = 0; 18 | int k = i-1; 19 | while(k > j){ 20 | if(arr[i] == arr[j] + arr[k]){ 21 | ans ++; 22 | j++; 23 | k--; 24 | }else if(arr[i] > arr[j] + arr[k]){ 25 | j++; 26 | }else{ 27 | k--; 28 | } 29 | } 30 | } 31 | 32 | cout << ans << endl; 33 | } 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /arrays/equilibrium_point.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // 6 | int t; 7 | cin >> t; 8 | while(t--){ 9 | int n; 10 | cin >> n; 11 | int arr[n], sum[n], s = 0; 12 | for(int i=0; i> arr[i]; 14 | } 15 | for(int i=0; i 1){ 22 | for(int i=0; i 0 && i < n-1){ 24 | aft = sum[n-1] - sum[i]; 25 | bef = sum[i-1]; 26 | if(aft == bef && aft > 0){ 27 | ans = i + 1; 28 | break; 29 | } 30 | }else if(i == 0){ 31 | aft = sum[n-1]; 32 | if(aft == bef && aft > 0){ 33 | ans = i + 1; 34 | break; 35 | } 36 | }else if(i == n-1){ 37 | bef = sum[i-1]; 38 | if(aft == bef && aft > 0){ 39 | ans = i + 1; 40 | break; 41 | } 42 | } 43 | aft = 0, bef = 0; 44 | } 45 | }else if(n == 1){ 46 | ans = 1; 47 | } 48 | cout << ans << endl; 49 | } 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /arrays/inversion_of_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | using namespace std; 4 | 5 | ll query(ll bit[],ll pos){ 6 | ll sum=0; 7 | while(pos>0){ 8 | sum+=bit[pos]; 9 | pos-=pos&(-pos); 10 | } 11 | return sum; 12 | } 13 | 14 | void update(ll bit[],ll n,ll pos){ 15 | while(pos<=n){ 16 | bit[pos]+=1; 17 | pos+=pos&(-pos); 18 | } 19 | } 20 | 21 | int main() 22 | { 23 | ll t; 24 | cin>>t; 25 | while(t--){ 26 | ll n,i,summ=0; 27 | cin>>n; 28 | ll a[n],temp[n],bit[n+1]={0}; 29 | for(i=0;i>a[i]; 31 | temp[i]=a[i]; 32 | } 33 | sort(temp,temp+n); 34 | for(i=0;i=0;i--){ 38 | summ+=query(bit,a[i]-1); 39 | update(bit,n,a[i]); 40 | } 41 | cout< 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to find subarray with maximum sum 10 | // arr: input array 11 | // n: size of array 12 | int maxSubarraySum(int arr[], int n){ 13 | 14 | // Your code here 15 | int sum=0, ans = 0, j = 0; 16 | for(int i=0; i>t; //input testcases 35 | while(t--) //while testcases exist 36 | { 37 | 38 | cin>>n; //input size of array 39 | 40 | int a[n]; 41 | 42 | for(int i=0;i>a[i]; //inputting elements of array 44 | 45 | cout << maxSubarraySum(a, n) << endl; 46 | } 47 | } 48 | // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/kth_smallest_element.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial function template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | int kthSmallest(int *, int, int, int); 8 | 9 | int main() 10 | { 11 | // ios_base::sync_with_stdio(false); 12 | // cin.tie(NULL); 13 | 14 | int test_case; 15 | cin>>test_case; 16 | while(test_case--) 17 | { 18 | int number_of_elements; 19 | cin>>number_of_elements; 20 | int a[number_of_elements]; 21 | 22 | for(int i=0;i>a[i]; 24 | 25 | int k; 26 | cin>>k; 27 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | 12 | 13 | vector leaders(int a[], int n){ 14 | // code here 15 | int max = INT_MIN; 16 | vector ans; 17 | for(int i=n-1; i>=0; i--){ 18 | if(max <= a[i]){ 19 | max = a[i]; 20 | ans.push_back(max); 21 | } 22 | } 23 | reverse(ans.begin(), ans.end()); 24 | return ans; 25 | } 26 | 27 | // { Driver Code Starts. 28 | 29 | int main() 30 | { 31 | long long t; 32 | cin >> t;//testcases 33 | while (t--) 34 | { 35 | long long n; 36 | cin >> n;//total size of array 37 | 38 | int a[n]; 39 | 40 | //inserting elements in the array 41 | for(long long i =0;i> a[i]; 43 | } 44 | 45 | //calling leaders() function 46 | vector v = leaders(a, n); 47 | 48 | //printing elements of the vector 49 | for(auto it = v.begin();it!=v.end();it++){ 50 | cout << *it << " "; 51 | } 52 | 53 | cout << endl; 54 | 55 | } 56 | } 57 | // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/merge_without_extra_space.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | void merge(int a[], int b[], int n, int m) { 12 | // code here 13 | int c=n,sr=0,i=0,j=0; 14 | while(c-- && i=b[j]) 19 | { 20 | sr++; 21 | j++; 22 | } 23 | 24 | } 25 | for(i=0;i> t; 36 | while (t--) { 37 | int n, m, i; 38 | cin >> n >> m; 39 | int arr1[n], arr2[m]; 40 | for (i = 0; i < n; i++) { 41 | cin >> arr1[i]; 42 | } 43 | for (i = 0; i < m; i++) { 44 | cin >> arr2[i]; 45 | } 46 | Solution ob; 47 | ob.merge(arr1, arr2, n, m); 48 | for (i = 0; i < n; i++) { 49 | cout << arr1[i] << " "; 50 | } 51 | for (i = 0; i < m; i++) { 52 | cout << arr2[i] << " "; 53 | } 54 | cout << "\n"; 55 | } 56 | return 0; 57 | } // } Driver Code Ends -------------------------------------------------------------------------------- /arrays/minimum_platforms.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Program to find minimum number of platforms 3 | // required on a railway station 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | int findPlatform(int arr[], int dep[], int n) 12 | { 13 | // Your code here 14 | sort(arr, arr+n); 15 | sort(dep, dep+n); 16 | int i = 1; 17 | int j = 0; 18 | int p = 1; 19 | int max = 1; 20 | while(i dep[j]){ 22 | p--; 23 | j++; 24 | }else if(arr[i] <= dep[j]){ 25 | p++; 26 | i++; 27 | if(p > max){ 28 | max = p; 29 | } 30 | } 31 | } 32 | return max; 33 | } 34 | 35 | 36 | // { Driver Code Starts. 37 | // Driver code 38 | int main() 39 | { 40 | int t; 41 | cin>>t; 42 | while(t--) 43 | { 44 | int n; 45 | cin>>n; 46 | int arr[n]; 47 | int dep[n]; 48 | for(int i=0;i>arr[i]; 50 | for(int j=0;j>dep[j]; 52 | } 53 | cout < 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | void merge(int arr1[], int arr2[], int n, int m) 10 | { 11 | int x=n-1, y = 0; 12 | while(x>=0 && y arr2[y]){ 14 | swap(arr1[x], arr2[y]); 15 | x--; 16 | y++; 17 | }else{ 18 | break; 19 | } 20 | } 21 | sort(arr1 , arr1+n); 22 | sort(arr2 , arr2+m); 23 | } 24 | 25 | 26 | // { Driver Code Starts. 27 | 28 | int main() 29 | { 30 | 31 | int T; 32 | cin >> T; 33 | 34 | while(T--){ 35 | int n, m; 36 | cin >> n >> m; 37 | 38 | int arr1[n], arr2[m]; 39 | 40 | for(int i = 0;i> arr1[i]; 42 | } 43 | 44 | for(int i = 0;i> arr2[i]; 46 | } 47 | 48 | merge(arr1, arr2, n, m); 49 | 50 | for (int i = 0; i < n; i++) 51 | printf("%d ", arr1[i]); 52 | 53 | 54 | for (int i = 0; i < m; i++) 55 | printf("%d ", arr2[i]); 56 | 57 | cout< 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | 10 | 11 | // Function to count number of pairs such that x^y is greater than y^x 12 | // X[], Y[]: input arrau 13 | // m, n: size of arrays X[] and Y[] respectively 14 | int getIndex(int Y[] , int n , int ele){ 15 | 16 | int low = 0; 17 | int high = n-1; 18 | int ans = -1; 19 | while(low<=high){ 20 | int mid = (low+high)/2; 21 | if(Y[mid] > ele){ 22 | ans = mid; 23 | high = mid -1; 24 | }else{ 25 | low = mid+1; 26 | } 27 | } 28 | return ans; 29 | } 30 | 31 | long long countPairs(int X[], int Y[], int m, int n) 32 | { 33 | //Your code here 34 | int zero = 0, one = 0, three = 0, four = 0, two= 0; 35 | sort(X, X+m); 36 | sort(Y, Y+n); 37 | 38 | for(int i=0;i>T; 84 | while(T--) 85 | { 86 | int M,N; 87 | cin>>M>>N; 88 | int i,a[M],b[N]; 89 | for(i=0;i>a[i]; 92 | } 93 | for(i=0;i>b[i]; 96 | } 97 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | //code 6 | int t; 7 | cin >> t; 8 | int n; 9 | while(t--){ 10 | cin >> n; 11 | int arr[n]; 12 | for(int i=0; i> arr[i]; 14 | } 15 | 16 | int size = sizeof(arr)/sizeof(arr[0]); 17 | 18 | sort(arr, arr+size); 19 | 20 | if(n%2 == 0){ 21 | for(int i=0; i 3 | using namespace std; 4 | void sort012(int[],int); 5 | 6 | int main() { 7 | 8 | int t; 9 | cin >> t; 10 | 11 | while(t--){ 12 | int n; 13 | cin >>n; 14 | int a[n]; 15 | for(int i=0;i> a[i]; 17 | } 18 | 19 | sort012(a, n); 20 | 21 | for(int i=0;i m; 39 | for(int i=0; i i){ 47 | a[i] = 0; 48 | }else if(one > i){ 49 | a[i] = 1; 50 | }else if(two > i){ 51 | a[i] = 2; 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /backtracking/N_queenProblem.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | unordered_map diag1, diag2; 12 | public: 13 | 14 | void solve(vector> &ans, int i, int n, vector cols, vector vec){ 15 | if(i==n){ 16 | ans.push_back(vec); 17 | return; 18 | } 19 | 20 | for(int j=0; j> nQueen(int n) { 38 | vector cols(n,false); 39 | vector> ans; 40 | solve(ans, 0, n, cols, {}); 41 | return ans; 42 | } 43 | }; 44 | 45 | // { Driver Code Starts. 46 | 47 | int main(){ 48 | int t; 49 | cin>>t; 50 | while(t--){ 51 | int n; 52 | cin>>n; 53 | 54 | Solution ob; 55 | vector> ans = ob.nQueen(n); 56 | if(ans.size() == 0) 57 | cout<<-1<<"\n"; 58 | else { 59 | for(int i = 0;i < ans.size();i++){ 60 | cout<<"["; 61 | for(int u: ans[i]) 62 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | // User function template for C++ 10 | 11 | class Solution{ 12 | public: 13 | void solve(vector> &m, int i, int j, int n, vector &v, string s){ 14 | if(i>n-1 || j>n-1 || i<0 || j<0 || m[i][j] == 0){ 15 | return; 16 | } 17 | if(i==n-1 && j==n-1){ 18 | v.push_back(s); 19 | } 20 | m[i][j] = 0; 21 | solve(m, i+1, j, n, v, s+"D"); 22 | solve(m, i, j+1, n, v, s+"R"); 23 | solve(m, i-1, j, n, v, s+"U"); 24 | solve(m, i, j-1, n, v, s+"L"); 25 | m[i][j] = 1; 26 | } 27 | 28 | vector findPath(vector> &m, int n) { 29 | // Your code goes here 30 | vector v; 31 | string s; 32 | solve(m, 0, 0, n, v, s); 33 | sort(v.begin(), v.end()); 34 | return v; 35 | } 36 | }; 37 | 38 | 39 | 40 | 41 | // { Driver Code Starts. 42 | 43 | int main() { 44 | int t; 45 | cin >> t; 46 | while (t--) { 47 | int n; 48 | cin >> n; 49 | vector> m(n, vector (n,0)); 50 | for (int i = 0; i < n; i++) { 51 | for (int j = 0; j < n; j++) { 52 | cin >> m[i][j]; 53 | } 54 | } 55 | Solution obj; 56 | vector result = obj.findPath(m, n); 57 | if (result.size() == 0) 58 | cout << -1; 59 | else 60 | for (int i = 0; i < result.size(); i++) cout << result[i] << " "; 61 | cout << endl; 62 | } 63 | return 0; 64 | } // } Driver Code Ends -------------------------------------------------------------------------------- /backtracking/SolveTheSuduko.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | // UNASSIGNED is used for empty cells in sudoku grid 5 | #define UNASSIGNED 0 6 | 7 | // N is used for the size of Sudoku grid. 8 | // Size will be NxN 9 | #define N 9 10 | 11 | 12 | // } Driver Code Ends 13 | 14 | 15 | class Solution { 16 | public: 17 | bool isSafe(int grid[N][N], int i, int j, int val){ 18 | for(int k=0; k>t; 83 | while(t--) 84 | { 85 | int grid[N][N]; 86 | 87 | for(int i=0;i<9;i++) 88 | for(int j=0;j<9;j++) 89 | cin>>grid[i][j]; 90 | 91 | Solution ob; 92 | 93 | if (ob.SolveSudoku(grid) == true) 94 | ob.printGrid(grid); 95 | else 96 | cout << "No solution exists"; 97 | 98 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | // Function to find number of bits to be flip 14 | // to convert A to B 15 | int countBitsFlip(int a, int b){ 16 | 17 | // Your logic here 18 | int x = a^b; 19 | int ans=0; 20 | while(x){ 21 | ans += x&1; 22 | x >>= 1; 23 | } 24 | return ans; 25 | } 26 | 27 | // { Driver Code Starts. 28 | 29 | // Driver Code 30 | int main() 31 | { 32 | int t; 33 | cin>>t;// input the testcases 34 | while(t--) //while testcases exist 35 | { 36 | int a,b; 37 | cin>>a>>b; //input a and b 38 | 39 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | // Function to check if Kth bit is set or not 14 | bool checkKthBit(int n, int k){ 15 | 16 | // Your code here 17 | // It can be a one liner logic!! Think of it!! 18 | if(n & (1 << k)){ 19 | return true; 20 | }else{ 21 | return false; 22 | } 23 | 24 | } 25 | 26 | // { Driver Code Starts. 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int t; 32 | cin>>t;//taking testcases 33 | while(t--) 34 | { 35 | long long n; 36 | cin>>n;//input n 37 | int k; 38 | cin>>k;//bit number k 39 | 40 | if(checkKthBit(n, k)) 41 | cout << "Yes" << endl; 42 | else 43 | cout << "No" << endl; 44 | } 45 | return 0; 46 | } // } Driver Code Ends -------------------------------------------------------------------------------- /bit magic/first_set_bit.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | // } Driver Code Ends 10 | 11 | //User function Template for C++ 12 | 13 | /* function to find position of first set 14 | bit in the given number 15 | * n: given input for which we want to get 16 | the position of first set bit 17 | */ 18 | unsigned int getFirstSetBit(int n){ 19 | 20 | // Your code here 21 | int ans; 22 | if((n & 1) != 0){ 23 | ans = 1; 24 | }else{ 25 | for(int i=1; i<20; i++){ 26 | if((n&(1<>t; // testcases 42 | while(t--) 43 | { 44 | int n; 45 | cin>>n; //input n 46 | printf("%u\n", getFirstSetBit(n)); // function to get answer 47 | } 48 | return 0; 49 | } 50 | // } Driver Code Ends -------------------------------------------------------------------------------- /bit magic/maximum_subset_xor.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // Number of bits to represent int 6 | #define INT_BITS 32 7 | int maxSubarrayXOR(int [], int n); 8 | int main() 9 | { 10 | 11 | int t,n,a[100004],k; 12 | scanf("%d",&t); 13 | while(t--) 14 | { 15 | //cin>>n; 16 | scanf("%d",&n); 17 | 18 | for(int i=0;i 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | //User function Template for C++ 11 | 12 | class Solution{ 13 | public: 14 | int findSingle(int N, int arr[]){ 15 | // code here 16 | sort(arr, arr+N); 17 | int ans; 18 | for(int i=0; i>t; 38 | while(t--) 39 | { 40 | int N, X; 41 | cin >> N; 42 | int arr[N]; 43 | for(int i = 0; i < N; i++){ 44 | cin >> arr[i]; 45 | } 46 | 47 | Solution ob; 48 | cout << ob.findSingle(N, arr) << endl; 49 | } 50 | return 0; 51 | } // } Driver Code Ends -------------------------------------------------------------------------------- /bit magic/powerOf2.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | // Function to check power of two 14 | bool isPowerofTwo(long long n){ 15 | 16 | // Your code here 17 | if((n & n - 1) == 0){ 18 | return true; 19 | }else { 20 | return false; 21 | } 22 | 23 | } 24 | 25 | // { Driver Code Starts. 26 | 27 | // Driver code 28 | int main() 29 | { 30 | 31 | int t; 32 | cin>>t;//testcases 33 | 34 | for(int i=0;i>n; 38 | if(n<=0) // if n is less than equal to zero then it can't be a power of 2 39 | { 40 | cout<<"NO"< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | /* Function to find the first position with different bits 14 | * This function returns the position with different bit 15 | */ 16 | int posOfRightMostDiffBit(int m, int n) 17 | { 18 | // Your code here 19 | int ans, x; 20 | ans = (m ^ n); 21 | if(ans == 0){ 22 | x = -1; 23 | }else{ 24 | for(int i=1; i<11; i++){ 25 | if(ans&1 == true){ 26 | x = 1; 27 | break; 28 | }else if((ans&(1<>t; //input number of testcases 44 | while(t--) 45 | { 46 | int m,n; 47 | cin>>m>>n; //input m and n 48 | cout << posOfRightMostDiffBit(m, n)< 2 | using namespace std; 3 | # define ll long long int 4 | int main() 5 | { 6 | ll t; 7 | t=1; 8 | cin>>t; 9 | while(t--) 10 | { 11 | ll n,d,i,ans=0,t; 12 | cin>>n>>d; 13 | t=n; 14 | int x[16]={0},m=0; 15 | while(n>0) 16 | { 17 | x[m++] = n%2; 18 | n/=2; 19 | } 20 | d%=16; 21 | int arr[16]={0},k=0; 22 | for(i=d-1;i>=0;i--) 23 | arr[k++] = x[i]; 24 | for(i=15;i>=d;i--) 25 | arr[k++] = x[i]; 26 | reverse(arr,arr+16); 27 | for(i=0;i<16;i++) 28 | { 29 | if(arr[i]) 30 | ans += (ll)pow(2,i); 31 | } 32 | cout<<(t< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | class Solution 8 | { 9 | public: 10 | int setKthBit(int N, int K) 11 | { 12 | // Write Your Code here 13 | int ans = N | (1<> t; 23 | while (t--) 24 | { 25 | int N, K; 26 | cin >> N >> K; 27 | 28 | Solution ob; 29 | int ans = ob.setKthBit(N,K); 30 | cout << ans << endl; 31 | } 32 | return 0; 33 | } // } Driver Code Ends -------------------------------------------------------------------------------- /bit magic/toggle_bits_in_range.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution { 9 | public: 10 | int toggleBits(int N , int L , int R) { 11 | // code here 12 | for(int i=L; i<=R; i++){ 13 | N = (N^(1 << i-1)); 14 | } 15 | return N; 16 | } 17 | }; 18 | 19 | // { Driver Code Starts. 20 | int main() { 21 | int t; 22 | cin >> t; 23 | while (t--) { 24 | int N,L,R; 25 | 26 | cin>>N>>L>>R; 27 | 28 | Solution ob; 29 | cout << ob.toggleBits(N,L,R) << endl; 30 | } 31 | return 0; 32 | } // } Driver Code Ends -------------------------------------------------------------------------------- /divide and conquer/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int bin_search(int A[],int left,int right,int k); 6 | 7 | int main() 8 | { 9 | int t; 10 | cin>>t; 11 | 12 | while(t--) 13 | { 14 | int N; 15 | cin>>N; 16 | int a[N]; 17 | for(int i=0;i>a[i]; 19 | int key; 20 | cin>>key; 21 | int found = bin_search(a,0,N-1,key); 22 | cout<= left){ 32 | int mid = (left+right)/2; 33 | 34 | if(A[mid] == k){ 35 | return mid; 36 | }else if(A[mid] > k){ 37 | return bin_search(A, left, mid-1, k); 38 | }else if(A[mid] < k){ 39 | return bin_search(A, mid+1, right, k); 40 | } 41 | } 42 | return -1; 43 | } -------------------------------------------------------------------------------- /divide and conquer/KthElementOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | int kthElement(int arr1[], int arr2[], int n, int m, int k) 10 | { 11 | int a[n+m]; 12 | 13 | merge(arr1, arr1+n, arr2, arr2+m, a); 14 | 15 | return a[k-1]; 16 | } 17 | }; 18 | 19 | // { Driver Code Starts. 20 | 21 | // Driver code 22 | int main() 23 | { 24 | int t; 25 | cin>>t; 26 | while(t--){ 27 | int n,m,k; 28 | cin>>n>>m>>k; 29 | int arr1[n],arr2[m]; 30 | for(int i=0;i>arr1[i]; 32 | for(int i=0;i>arr2[i]; 34 | 35 | Solution ob; 36 | cout << ob.kthElement(arr1, arr2, n, m, k)< 3 | #include 4 | using namespace std; 5 | 6 | 7 | 8 | /* Function to print an array */ 9 | void printArray(int arr[], int size) 10 | { 11 | int i; 12 | for (i=0; i < size; i++) 13 | printf("%d ", arr[i]); 14 | printf("\n"); 15 | } 16 | 17 | 18 | // } Driver Code Ends 19 | class Solution 20 | { 21 | public: 22 | void merge(int arr[], int l, int m, int r) 23 | { 24 | // Your code here 25 | int n1, n2; 26 | n1 = m-l+1; 27 | n2 = r-m; 28 | int a[n1], b[n2]; 29 | for(int i=0; i 3 | using namespace std; 4 | int search(int A[], int l, int h, int key); 5 | 6 | 7 | int main() { 8 | int t; 9 | cin >> t; 10 | while(t--){ 11 | int n; 12 | cin >> n; 13 | int A[n]; 14 | for(int i = 0; i < n; i++) 15 | cin >> A[i]; 16 | int key; 17 | cin >> key; 18 | cout << search(A, 0, n - 1, key) << endl; 19 | } 20 | return 0; 21 | }// } Driver Code Ends 22 | 23 | 24 | int search(int A[], int l, int h, int key){ 25 | //complete the function here 26 | for(int i=l; i<=h; i++){ 27 | if(A[i] == key){ 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } -------------------------------------------------------------------------------- /divide and conquer/SumOfMiddleElementsOfTwoSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // } Driver Code Ends 9 | //User function template for C++ 10 | 11 | class Solution { 12 | public: 13 | int findMidSum(int ar1[], int ar2[], int n) { 14 | // code here 15 | int i=0, j=n-1; 16 | while(ar2[i] < ar1[j]){ 17 | swap(ar2[i], ar1[j]); 18 | i++; 19 | j--; 20 | } 21 | sort(ar1, ar1+n); 22 | sort(ar2, ar2+n); 23 | return ar2[0] + ar1[n-1]; 24 | } 25 | }; 26 | 27 | // { Driver Code Starts. 28 | int main() { 29 | int t; 30 | cin >> t; 31 | while (t--) { 32 | int n, i; 33 | cin >> n; 34 | int ar1[n], ar2[n]; 35 | for (i = 0; i < n; i++) { 36 | cin >> ar1[i]; 37 | } 38 | for (i = 0; i < n; i++) { 39 | cin >> ar2[i]; 40 | } 41 | Solution ob; 42 | auto ans = ob.findMidSum(ar1, ar2, n); 43 | cout << ans << "\n"; 44 | } 45 | return 0; 46 | } // } Driver Code Ends -------------------------------------------------------------------------------- /divide and conquer/element_appeared_once_in_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Driver code 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | class Solution 11 | { 12 | public: 13 | int findOnce(int arr[], int n) 14 | { 15 | //code here. 16 | for(int i = 0; i> t; 32 | 33 | while (t--) 34 | { 35 | int n; 36 | cin >> n; 37 | int A[n]; 38 | for(int i = 0;i < n;i++) 39 | { 40 | cin>>A[i]; 41 | } 42 | 43 | Solution ob; 44 | 45 | int res = ob.findOnce(A,n); 46 | cout << res << endl; 47 | } 48 | 49 | return 0; 50 | } // } Driver Code Ends -------------------------------------------------------------------------------- /divide and conquer/search_in_rotated_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | //code 6 | int t; 7 | cin >> t; 8 | while(t--){ 9 | int n; 10 | cin >> n; 11 | int arr[n], k; 12 | for(int i=0; i> arr[i]; 14 | } 15 | int ans = -1; 16 | cin >> k; 17 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Returns the maximum value that 10 | // can be put in a knapsack of capacity W 11 | int knapSack(int W, int wt[], int val[], int n) 12 | { 13 | // Your code here 14 | int dp[n+1][W+1]; 15 | for(int i=0; i<=n; i++){ 16 | dp[i][0] = 0; 17 | } 18 | for(int j=0; j<=W; j++){ 19 | dp[0][j] = 0; 20 | } 21 | for(int i=1; i<=n; i++){ 22 | for(int j=1; j<=W; j++){ 23 | if(wt[i-1] > j){ 24 | dp[i][j] = dp[i-1][j]; 25 | }else{ 26 | dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j]); 27 | } 28 | } 29 | } 30 | return dp[n][W]; 31 | } 32 | 33 | 34 | 35 | 36 | 37 | // { Driver Code Starts. 38 | 39 | int main() 40 | { 41 | //taking total testcases 42 | int t; 43 | cin>>t; 44 | while(t--) 45 | { 46 | //reading number of elements and weight 47 | int n, w; 48 | cin>>n>>w; 49 | 50 | int val[n]; 51 | int wt[n]; 52 | 53 | //inserting the values 54 | for(int i=0;i>val[i]; 56 | 57 | //inserting the weights 58 | for(int i=0;i>wt[i]; 60 | 61 | //calling method knapSack() 62 | cout< 3 | 4 | using namespace std; 5 | 6 | int maxHeight(int height[],int width[],int length[],int n); 7 | 8 | int main() 9 | { 10 | int t; 11 | cin>>t; 12 | while(t--){ 13 | int n; 14 | cin>>n; 15 | 16 | 17 | int A[1000],B[1000],C[10001]; 18 | for(int i=0;i>a>>b>>c; 22 | A[i]=a; 23 | B[i]=b; 24 | C[i]=c; 25 | } 26 | cout<, pair>> v; 40 | 41 | for(int i=0; i dp(m); 51 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | /* Function to get minimum number of trials needed in worst 10 | case with n eggs and k floors */ 11 | int eggDrop(int n, int k){ 12 | vector dp(n + 1, 0); 13 | int i; 14 | for (i = 0; dp[n] < k; i++){ 15 | for (int k = n; k > 0; --k){ 16 | dp[k] += dp[k - 1] + 1; 17 | } 18 | } 19 | return i; 20 | } 21 | 22 | // { Driver Code Starts. 23 | 24 | int main() 25 | { 26 | //taking total testcases 27 | int t; 28 | cin>>t; 29 | while(t--) 30 | { 31 | //taking eggs and floors count 32 | int n, k; 33 | cin>>n>>k; 34 | 35 | //calling function eggDrop() 36 | cout< 3 | const int mod=1e9+7; 4 | using namespace std; 5 | 6 | int lcs(int, int, string, string); 7 | 8 | int main() 9 | { 10 | int t,n,k,x,y; 11 | 12 | cin>>t; 13 | while(t--) 14 | { 15 | cin>>x>>y; // Take size of both the strings as input 16 | string s1,s2; 17 | cin>>s1>>s2; // Take both the string as input 18 | 19 | cout << lcs(x, y, s1, s2) << endl; 20 | } 21 | return 0; 22 | } 23 | // } Driver Code Ends 24 | 25 | 26 | // function to find longest common subsequence 27 | 28 | int lcs(int x, int y, string s1, string s2){ 29 | 30 | // your code here 31 | int dp[x+1][y+1]; 32 | for(int i=0; i<=x; i++){ 33 | dp[i][0] = 0; 34 | } 35 | for(int j=0; j<=y; j++){ 36 | dp[0][j] = 0; 37 | } 38 | for(int i=1; i<=x; i++){ 39 | for(int j=1; j<=y; j++){ 40 | if(s1[i-1] == s2[j-1]){ 41 | dp[i][j] = 1 + dp[i-1][j-1]; 42 | }else{ 43 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 44 | } 45 | } 46 | } 47 | return dp[x][y]; 48 | } 49 | -------------------------------------------------------------------------------- /dynamic programming/LongestCommonSubstring.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | 9 | 10 | class Solution{ 11 | public: 12 | 13 | int longestCommonSubstr (string S1, string S2, int n, int m) 14 | { 15 | // your code here 16 | int dp[n+1][m+1]; 17 | int max = 0; 18 | memset(dp, 0, sizeof(dp)); 19 | for(int i=1; i<=n; i++){ 20 | for(int j=1; j<=m; j++){ 21 | if(S1[i-1] == S2[j-1]){ 22 | dp[i][j] = 1 + dp[i-1][j-1]; 23 | if(max < dp[i][j]){ 24 | max = dp[i][j]; 25 | } 26 | }else{ 27 | dp[i][j] = 0; 28 | } 29 | } 30 | } 31 | return max; 32 | } 33 | }; 34 | 35 | // { Driver Code Starts. 36 | 37 | int main() 38 | { 39 | int t; cin >> t; 40 | while (t--) 41 | { 42 | int n, m; cin >> n >> m; 43 | string s1, s2; 44 | cin >> s1 >> s2; 45 | Solution ob; 46 | 47 | cout << ob.longestCommonSubstr (s1, s2, n, m) << endl; 48 | } 49 | } 50 | // Contributed By: Pranay Bansal 51 | // } Driver Code Ends -------------------------------------------------------------------------------- /dynamic programming/LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int longestSubsequence(int, int[]); 6 | 7 | int main() 8 | { 9 | //taking total testcases 10 | int t,n; 11 | cin>>t; 12 | while(t--) 13 | { 14 | //taking size of array 15 | cin>>n; 16 | int a[n]; 17 | 18 | //inserting elements to the array 19 | for(int i=0;i>a[i]; 21 | 22 | //calling method longestSubsequence() 23 | cout << longestSubsequence(n, a) << endl; 24 | } 25 | } 26 | // } Driver Code Ends 27 | 28 | 29 | // return length of longest strictly increasing subsequence 30 | 31 | int longestSubsequence(int n, int a[]) 32 | { 33 | // your code here 34 | vector v; 35 | v.push_back(a[0]); 36 | for(int i=1; i v.back()){ 38 | v.push_back(a[i]); 39 | }else{ 40 | int min = lower_bound(v.begin(), v.end(), a[i]) - v.begin(); 41 | v[min] = a[i]; 42 | } 43 | } 44 | return v.size(); 45 | } -------------------------------------------------------------------------------- /dynamic programming/LongestPathInMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define n 3 3 | using namespace std; 4 | 5 | int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]) 6 | { 7 | if (i < 0 || i >= n || j < 0 || j >= n) 8 | return 0; 9 | 10 | if (dp[i][j] != -1) 11 | return dp[i][j]; 12 | 13 | int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN; 14 | 15 | if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) 16 | x = 1 + findLongestFromACell(i, j + 1, mat, dp); 17 | 18 | if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) 19 | y = 1 + findLongestFromACell(i, j - 1, mat, dp); 20 | 21 | if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) 22 | z = 1 + findLongestFromACell(i - 1, j, mat, dp); 23 | 24 | if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) 25 | w = 1 + findLongestFromACell(i + 1, j, mat, dp); 26 | 27 | return dp[i][j] = max(x, max(y, max(z, max(w, 1)))); 28 | } 29 | 30 | int finLongestOverAll(int mat[n][n]) 31 | { 32 | int result = 1; 33 | 34 | int dp[n][n]; 35 | memset(dp, -1, sizeof dp); 36 | for (int i = 0; i < n; i++) { 37 | for (int j = 0; j < n; j++) { 38 | if (dp[i][j] == -1) { 39 | findLongestFromACell(i, j, mat, dp); 40 | } 41 | result = max(result, dp[i][j]); 42 | } 43 | } 44 | 45 | return result; 46 | } 47 | 48 | // Driver program 49 | int main() 50 | { 51 | int mat[n][n] = { { 1, 2, 9 }, 52 | { 5, 3, 8 }, 53 | { 4, 6, 7 } }; 54 | cout << "Length of the longest path is " 55 | << finLongestOverAll(mat); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /dynamic programming/MaxLengthChain.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | struct val{ 6 | int first; 7 | int second; 8 | }; 9 | 10 | 11 | 12 | int maxChainLen(struct val p[],int n); 13 | int main() { 14 | // your code goes here 15 | int t; 16 | cin>>t; 17 | while(t--) 18 | { 19 | int n; 20 | cin>>n; 21 | val p[n]; 22 | for(int i=0;i>p[i].first>>p[i].second; 25 | } 26 | 27 | cout<a.second); 43 | } 44 | int maxChainLen(struct val p[],int n) 45 | { 46 | //Your code here 47 | sort(p, p+n, comp); 48 | int end = 0, sum = 1; 49 | int dp[n]; 50 | for(int i=0; i sum){ 64 | sum = dp[i]; 65 | } 66 | } 67 | return sum; 68 | } -------------------------------------------------------------------------------- /dynamic programming/MaximizeCutSegments.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int maximizeTheCuts(int n, int x, int y, int z); 6 | 7 | int main() { 8 | 9 | //taking testcases 10 | int t; 11 | cin >> t; 12 | while(t--) 13 | { 14 | //taking length of line segment 15 | int n; 16 | cin >> n; 17 | 18 | //taking types of segments 19 | int x,y,z; 20 | cin>>x>>y>>z; 21 | 22 | //calling function maximizeTheCuts() 23 | cout<= 0){ 42 | dp[i] = max(dp[i], dp[i-a]); 43 | } 44 | 45 | if(i-b >= 0){ 46 | dp[i] = max(dp[i], dp[i-b]); 47 | } 48 | 49 | if(i-c >= 0){ 50 | dp[i] = max(dp[i], dp[i-c]); 51 | } 52 | 53 | if(dp[i] != -1){ 54 | dp[i]++; 55 | } 56 | } 57 | 58 | return max(dp[n], 0); 59 | } -------------------------------------------------------------------------------- /dynamic programming/MaximumSumIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution{ 9 | 10 | public: 11 | int maxSumIS(int arr[], int n) 12 | { 13 | // Your code goes here 14 | int dp[n]; 15 | int ans = 0; 16 | for(int i=0; i arr[j]){ 22 | dp[i] = max(dp[i], dp[j]+arr[i]); 23 | } 24 | } 25 | } 26 | sort(dp, dp+n); 27 | return dp[n-1]; 28 | } 29 | }; 30 | 31 | // { Driver Code Starts. 32 | int main() 33 | { 34 | 35 | 36 | int t; 37 | cin >> t; 38 | while (t--) 39 | { 40 | int n; 41 | cin >> n; 42 | 43 | int a[n]; 44 | 45 | for(int i = 0; i < n; i++) 46 | cin >> a[i]; 47 | 48 | 49 | 50 | Solution ob; 51 | cout << ob.maxSumIS(a, n) << "\n"; 52 | 53 | } 54 | return 0; 55 | } 56 | 57 | // } Driver Code Ends -------------------------------------------------------------------------------- /dynamic programming/MinimumNoOfJumps.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to return minimum number of jumps to end of array 10 | int minJumps(int arr[], int n){ 11 | 12 | int count = 0; 13 | int i = 0; 14 | while(i < n-1) { 15 | if(arr[i] == 0) 16 | return -1; 17 | if(arr[i]+i >= n-1) { 18 | count++; 19 | return count; 20 | } 21 | int mx = INT_MIN; 22 | int loc = 0; 23 | for(int j = 1; j <= arr[i]; j++) { 24 | if(mx+loc < arr[j+i]+j) { 25 | mx = arr[j+i]; 26 | loc = j; 27 | } 28 | } 29 | count++; 30 | i += loc; 31 | } 32 | return count; 33 | 34 | } 35 | 36 | 37 | // { Driver Code Starts. 38 | 39 | int main() 40 | { 41 | int t; 42 | cin>>t; 43 | while(t--) 44 | { 45 | int n,i,j; 46 | cin>>n; 47 | int arr[n]; 48 | for(int i=0; i>arr[i]; 50 | 51 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution 9 | { 10 | public: 11 | int minOperation(int n) 12 | { 13 | //code here. 14 | int count = 0; 15 | while(n != 0){ 16 | if(n%2 == 0){ 17 | n /= 2; 18 | }else{ 19 | n -= 1; 20 | } 21 | count++; 22 | } 23 | return count; 24 | } 25 | }; 26 | 27 | // { Driver Code Starts. 28 | int main() 29 | { 30 | int t; 31 | cin>>t; 32 | while(t--) 33 | { 34 | int n; 35 | cin>>n; 36 | Solution ob; 37 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | 8 | public: 9 | int minDiffernce(int arr[], int n) 10 | { 11 | // Your code goes here 12 | int s=0 ; 13 | 14 | for(int i=0; i=0; i-- ) 36 | { 37 | if(t[n][i]){ 38 | break; 39 | } 40 | } 41 | return s-2*i ; 42 | } 43 | }; 44 | 45 | 46 | // { Driver Code Starts. 47 | int main() 48 | { 49 | 50 | 51 | int t; 52 | cin >> t; 53 | while (t--) 54 | { 55 | int n; 56 | cin >> n; 57 | 58 | int a[n]; 59 | for(int i = 0; i < n; i++) 60 | cin >> a[i]; 61 | 62 | 63 | 64 | Solution ob; 65 | cout << ob.minDiffernce(a, n) << "\n"; 66 | 67 | } 68 | return 0; 69 | } // } Driver Code Ends -------------------------------------------------------------------------------- /dynamic programming/NoOfWaysToCoverDistance.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | long long countWays(int); 6 | 7 | int main() 8 | { 9 | //taking testcases 10 | int t; 11 | cin >> t; 12 | 13 | while(t--) 14 | { 15 | //taking number of steps in stair 16 | int n; 17 | cin>>n; 18 | 19 | //calling function countWays() 20 | cout << countWays(n) << endl; 21 | } 22 | 23 | return 0; 24 | 25 | } 26 | // } Driver Code Ends 27 | 28 | 29 | // function to count number of ways to reach top of the stair 30 | long long countWays(int n){ 31 | 32 | // your code here 33 | long long dp[n+1]; 34 | dp[0] = 0; 35 | dp[1] = 1; 36 | dp[2] = 2; 37 | dp[3] = 4; 38 | 39 | for(long long i=4; i<=n; i++){ 40 | dp[i] = (dp[i-1] + dp[i-2] + dp[i-3])%1000000007; 41 | } 42 | return dp[n]; 43 | 44 | } -------------------------------------------------------------------------------- /dynamic programming/OptimalStrategyForGame.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | long long maximumAmount(int arr[], int n) 10 | { 11 | // long long ans = 0; 12 | long long dp[n][n]; 13 | 14 | for(int g = 0; g < n; g++) { 15 | for(int i = 0, j = g; j < n; i++, j++) { 16 | if(g == 0) { 17 | dp[i][j] = arr[i]; 18 | }else if(g == 1) { 19 | dp[i][j] = max(arr[i] , arr[j]); 20 | }else { 21 | int val1 = arr[i] + min(dp[i + 2][j], dp[i + 1][j - 1]); 22 | int val2 = arr[j] + min(dp[i + 1][j - 1], dp[i][j - 2]); 23 | int val = max(val1 , val2); 24 | dp[i][j] = val; 25 | } 26 | } 27 | } 28 | 29 | return dp[0][n -1]; 30 | } 31 | 32 | // { Driver Code Starts. 33 | 34 | int main() { 35 | 36 | //taking total testcases 37 | int T; 38 | cin>>T; 39 | while(T--) 40 | { 41 | //taking number of elements 42 | int N; 43 | cin>>N; 44 | 45 | int A[N]; 46 | 47 | //inserting the elements 48 | for(int i=0;i>A[i]; 50 | 51 | //calling function maximumAmount() 52 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | // User function Template for C++ 11 | 12 | class Solution{ 13 | public: 14 | int equalPartition(int N, int arr[]){ 15 | int sum=0; 16 | for(int i=0;i> dp(N+1,vector(target+1)); 25 | for(int i=0;i<=N;i++){ 26 | dp[i][0]=1; 27 | } 28 | for(int j=1;j<=target;j++){ 29 | dp[0][j]=0; 30 | } 31 | for(int i=1;i<=N;i++){ 32 | for(int j=1;j<=target;j++){ 33 | if(arr[i-1]<=j) 34 | dp[i][j]=(dp[i-1][j-arr[i-1]] || dp[i-1][j]); 35 | else 36 | dp[i][j]=dp[i-1][j]; 37 | } 38 | } 39 | return dp[N][target]; 40 | } 41 | }; 42 | 43 | // { Driver Code Starts. 44 | 45 | int main(){ 46 | int t; 47 | cin>>t; 48 | while(t--){ 49 | int N; 50 | cin>>N; 51 | int arr[N]; 52 | for(int i = 0;i < N;i++) 53 | cin>>arr[i]; 54 | 55 | Solution ob; 56 | if(ob.equalPartition(N, arr)) 57 | cout<<"YES\n"; 58 | else 59 | cout<<"NO\n"; 60 | } 61 | return 0; 62 | } // } Driver Code Ends -------------------------------------------------------------------------------- /dynamic programming/ShortestCommonSupersequence.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | int shortestCommonSupersequence(char* , char*, int, int ); 8 | 9 | int main() 10 | { 11 | 12 | int t; 13 | char X[10001], Y[10001]; 14 | 15 | //taking total testcases 16 | cin >> t; 17 | while(t--){ 18 | 19 | //taking String X and Y 20 | cin >> X >> Y; 21 | 22 | //calling function shortestCommonSupersequence() 23 | cout << shortestCommonSupersequence(X, Y, strlen(X), strlen(Y))<< endl; 24 | } 25 | return 0; 26 | } 27 | 28 | // } Driver Code Ends 29 | 30 | 31 | //User function template for C++ 32 | 33 | // X : 1st given string of size m 34 | // Y : 2nd given string of size n 35 | int shortestCommonSupersequence(char* X, char* Y, int m, int n) { 36 | //code here 37 | int dp[m+1][n+1]; 38 | memset(dp, 0, sizeof(dp)); 39 | for(int i=1; i<=m; i++){ 40 | for(int j=1; j<=n; j++){ 41 | if(X[i-1] == Y[j-1]){ 42 | dp[i][j] = 1 + dp[i-1][j-1]; 43 | }else{ 44 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 45 | } 46 | } 47 | } 48 | return m+n-dp[m][n]; 49 | } -------------------------------------------------------------------------------- /dynamic programming/coin_change.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution 9 | { 10 | public: 11 | long long int count( int S[], int m, int n){ 12 | 13 | long long int dp[m+1][n+1]; 14 | for(int i=0;i<=m;i++){ 15 | dp[i][0]=1; 16 | } 17 | for(int i=1;i<=n;i++){ 18 | dp[0][i]=0; 19 | } 20 | for(int i=1;i<=m;i++){ 21 | for(int j=1;j<=n;j++){ 22 | dp[i][j]=dp[i-1][j]; 23 | if(j-S[i-1]>=0){ 24 | dp[i][j]+=dp[i][j-S[i-1]]; 25 | } 26 | } 27 | } 28 | return dp[m][n]; 29 | } 30 | }; 31 | 32 | // { Driver Code Starts. 33 | int main() 34 | { 35 | int t; 36 | cin>>t; 37 | while(t--) 38 | { 39 | int n,m; 40 | cin>>n>>m; 41 | int arr[m]; 42 | for(int i=0;i>arr[i]; 44 | Solution ob; 45 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution 9 | { 10 | public: 11 | int editDistance(string s, string t) 12 | { 13 | int m = s.length(); 14 | int n = t.length(); 15 | int dp[m+1][n+1]; 16 | int i,j; 17 | for(i=0;i<=m;i++){ 18 | for(j=0;j<=n;j++){ 19 | if(i == 0) 20 | dp[i][j] = j; 21 | else if(j == 0) 22 | dp[i][j] = i; 23 | else if(s[i-1] == t[j-1]) 24 | dp[i][j] = dp[i-1][j-1]; 25 | else{ 26 | dp[i][j] = 1 + min(min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1]); 27 | } 28 | } 29 | } 30 | return dp[m][n]; 31 | } 32 | }; 33 | 34 | // { Driver Code Starts. 35 | int main(){ 36 | int T; 37 | cin >> T; 38 | while(T--) 39 | { 40 | string s, t; 41 | cin >> s >> t; 42 | Solution ob; 43 | int ans = ob.editDistance(s, t); 44 | cout << ans <<"\n"; 45 | } 46 | return 0; 47 | } 48 | // } Driver Code Ends -------------------------------------------------------------------------------- /graph/AlienDictionary.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | void dfs(int i, bool vis[], vector> v, string ans){ 11 | vis[i] = true; 12 | for(auto x:v[i]){ 13 | if(!vis[x]){ 14 | dfs(x, vis, v, ans); 15 | } 16 | } 17 | char ch = i + 'a'; 18 | ans = ch + ans; 19 | } 20 | 21 | class Solution{ 22 | public: 23 | string findOrder(string dict[], int N, int K) { 24 | //code here 25 | vector> v(K); 26 | for(int i=0; i> t; 68 | while (t--) { 69 | int N, K; 70 | cin >> N >> K; 71 | string dict[N]; 72 | for (int i = 0; i < N; i++) cin >> dict[i]; 73 | 74 | Solution obj; 75 | string ans = obj.findOrder(dict, N, K); 76 | order = ""; 77 | for (int i = 0; i < ans.size(); i++) order += ans[i]; 78 | 79 | string temp[N]; 80 | std::copy(dict, dict + N, temp); 81 | sort(temp, temp + N, f); 82 | 83 | bool f = true; 84 | for (int i = 0; i < N; i++) 85 | if (dict[i] != temp[i]) f = false; 86 | 87 | if(f)cout << 1; 88 | else cout << 0; 89 | cout << endl; 90 | } 91 | return 0; 92 | } 93 | // } Driver Code Ends -------------------------------------------------------------------------------- /graph/CircleOfStrings.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution 11 | { 12 | public: 13 | int isCircle(int N, vector A) 14 | { 15 | vector adj[26]; 16 | vector in(26, 0); 17 | vector out(26, 0); 18 | for(int i=0; i vis(26, 0); 36 | dfs(adj, vis, src); 37 | for(int i=0; i<26; i++) { 38 | if(out[i] && !vis[i]) 39 | return 0; 40 | } 41 | return 1; 42 | } 43 | void dfs(vector adj[], vector& vis, int s) { 44 | vis[s] = 1; 45 | for(auto& it: adj[s]) { 46 | if(!vis[it]) { 47 | dfs(adj, vis, it); 48 | } 49 | } 50 | } 51 | }; 52 | 53 | // { Driver Code Starts. 54 | int main() 55 | { 56 | int t; 57 | cin>>t; 58 | while(t--){ 59 | int N; 60 | cin>>N; 61 | vector A; 62 | string s; 63 | 64 | for(int i = 0;i < N; i++) 65 | { 66 | cin>>s; 67 | A.push_back(s); 68 | } 69 | 70 | Solution ob; 71 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | /* This function is used to detect a cycle in undirected graph 9 | 10 | * g[]: array of vectors to represent graph 11 | * V: number of vertices 12 | */ 13 | bool isCyclicUtil(int i, int V, vector adj[],bool visited[], bool inTheCall[]) 14 | { 15 | visited[i]=true; 16 | inTheCall[i]=true; 17 | for(int j=0;j adj[], int V) 30 | { 31 | bool visited[V]; 32 | bool inTheCall[V]; 33 | for(int i=0;i>T; 53 | while(T--) 54 | { 55 | int V, E; 56 | cin>>V>>E; 57 | 58 | // array of vectors to represent graph 59 | vector adj[V]; 60 | 61 | int u, v; 62 | for(int i=0;i>u>>v; 65 | 66 | // adding edge to the graph 67 | adj[u].push_back(v); 68 | adj[v].push_back(u); 69 | } 70 | 71 | cout << isCyclic(adj, V)< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | /* This function is used to detect a cycle in undirected graph 9 | 10 | * g[]: array of vectors to represent graph 11 | * V: number of vertices 12 | */ 13 | bool isCyclicUtil(vector g[], int curr, vector &visited, int parent){ 14 | visited[curr] = true; 15 | for(auto i:g[curr]){ 16 | if(!visited[i]){ 17 | if(isCyclicUtil(g, i, visited, curr)){ 18 | return true; 19 | } 20 | }else if(i != parent || i == curr){ 21 | return true; 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | bool isCyclic(vector g[], int V) 28 | { 29 | // Your code here 30 | vector visited(V); 31 | for(int i=0; i>T; 47 | while(T--) 48 | { 49 | int V, E; 50 | cin>>V>>E; 51 | 52 | // array of vectors to represent graph 53 | vector adj[V]; 54 | 55 | int u, v; 56 | for(int i=0;i>u>>v; 59 | 60 | // adding edge to the graph 61 | adj[u].push_back(v); 62 | adj[v].push_back(u); 63 | } 64 | 65 | cout << isCyclic(adj, V)< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution 9 | { 10 | public: 11 | //Function to find whether a path exists from the source to destination. 12 | bool dfs(vector>&grid,int i,int j){ 13 | int n = grid.size(), m=grid[0].size(); 14 | if(i<0 || j<0 || i>=n || j>=m || grid[i][j]==0){ 15 | return false; 16 | } 17 | if(grid[i][j]==2){ 18 | return true; 19 | } 20 | int x = grid[i][j]; 21 | 22 | grid[i][j]=0; 23 | 24 | return(dfs(grid,i+1,j) || dfs(grid,i-1,j) || dfs(grid,i,j+1) || dfs(grid,i,j-1)); 25 | } 26 | 27 | bool is_Possible(vector>& grid) 28 | { 29 | //code here 30 | int n = grid.size(); 31 | for(int i=0; i> tc; 47 | while(tc--){ 48 | int n; 49 | cin >> n; 50 | vector>grid(n, vector(n, -1)); 51 | for(int i = 0; i < n; i++){ 52 | for(int j = 0; j < n; j++){ 53 | cin >> grid[i][j]; 54 | } 55 | } 56 | Solution obj; 57 | bool ans = obj.is_Possible(grid); 58 | cout << ((ans) ? "1\n" : "0\n"); 59 | } 60 | return 0; 61 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/FindNoOfIslands.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution { 7 | public: 8 | void mark(int rows, int cols, int i, int j, vector>& grid){ 9 | if(i<0 || i>=rows || j<0 || j>=cols || grid[i][j] != '1'){ 10 | return; 11 | } 12 | 13 | grid[i][j] = '2'; 14 | mark(rows, cols, i+1, j, grid); 15 | mark(rows, cols, i-1, j, grid); 16 | mark(rows, cols, i, j+1, grid); 17 | mark(rows, cols, i, j-1, grid); 18 | mark(rows, cols, i-1, j-1, grid); 19 | mark(rows, cols, i+1, j+1, grid); 20 | mark(rows, cols, i+1, j-1, grid); 21 | mark(rows, cols, i-1, j+1, grid); 22 | } 23 | 24 | int numIslands(vector>& grid) { 25 | // Code here 26 | int rows = grid.size(); 27 | int cols = grid[0].size(); 28 | if(rows == 0){ 29 | return 0; 30 | } 31 | int is = 0; 32 | for(int i=0; i> tc; 48 | while(tc--){ 49 | int n, m; 50 | cin >> n >> m; 51 | vector>grid(n, vector(m, '#')); 52 | for(int i = 0; i < n; i++){ 53 | for(int j = 0; j < m; j++){ 54 | cin >> grid[i][j]; 55 | } 56 | } 57 | Solution obj; 58 | int ans = obj.numIslands(grid); 59 | cout << ans <<'\n'; 60 | } 61 | return 0; 62 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/FloydWarshall.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | 10 | class Solution { 11 | public: 12 | void shortest_distance(vector>&matrix){ 13 | // Code here 14 | int n = matrix.size(); 15 | for(int k=0; k> tc; 35 | while(tc--){ 36 | int n; 37 | cin >> n; 38 | vector>matrix(n, vector(n, -1)); 39 | for(int i = 0; i < n; i++){ 40 | for(int j = 0; j < n; j++){ 41 | cin >> matrix[i][j]; 42 | } 43 | } 44 | Solution obj; 45 | obj.shortest_distance(matrix); 46 | for(int i = 0; i < n; i++){ 47 | for(int j = 0; j < n; j++){ 48 | cout << matrix[i][j] << " "; 49 | } 50 | cout << "\n"; 51 | } 52 | } 53 | return 0; 54 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/Kosaraju'sAlgo.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | 9 | class Solution 10 | { 11 | public: 12 | //Function to find number of strongly connected components in the graph. 13 | vector order; 14 | 15 | void dfs(int src, vector &vis, vector g[]){ 16 | vis[src] = 1; 17 | for(auto x:g[src]){ 18 | if(!vis[x]){ 19 | dfs(x, vis, g); 20 | } 21 | } 22 | order.push_back(src); 23 | } 24 | 25 | void rdfs(int src, vector &vis1, vector rev[]){ 26 | vis1[src] = 1; 27 | for(auto x:rev[src]){ 28 | if(!vis1[x]){ 29 | rdfs(x, vis1, rev); 30 | } 31 | } 32 | } 33 | 34 | int kosaraju(int V, vector adj[]) 35 | { 36 | //code here 37 | order.clear(); 38 | vector rev[V]; 39 | for(int y=0; y vis(V, 0); 45 | for(int i=0; i vis1(V, 0); 52 | int count = 0; 53 | for(int i=V-1; i>=0; i--){ 54 | if(!vis1[order[i]]){ 55 | rdfs(order[i], vis1, rev); 56 | count++; 57 | } 58 | } 59 | return count; 60 | } 61 | }; 62 | 63 | // { Driver Code Starts. 64 | 65 | 66 | int main() 67 | { 68 | 69 | int t; 70 | cin >> t; 71 | while(t--) 72 | { 73 | int V, E; 74 | cin >> V >> E; 75 | 76 | vector adj[V]; 77 | 78 | for(int i = 0; i < E; i++) 79 | { 80 | int u, v; 81 | cin >> u >> v; 82 | adj[u].push_back(v); 83 | } 84 | 85 | Solution obj; 86 | cout << obj.kosaraju(V, adj) << "\n"; 87 | } 88 | 89 | return 0; 90 | } 91 | 92 | // } Driver Code Ends -------------------------------------------------------------------------------- /graph/MinimumCostPath.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution { 7 | public: 8 | 9 | bool isright(int a,int b,int n) 10 | { 11 | if(a>=0&&a=0&&b>& grid) { 17 | 18 | // Your code goes here 19 | int n = grid.size(); 20 | int dis[n][n]; 21 | for(int i=0;i>> s; 26 | s.insert({grid[0][0],{0,0}}); 27 | while(s.size()) 28 | { 29 | auto it=s.begin(); 30 | pair> p=*it; 31 | int d=p.first; 32 | int i=p.second.first; 33 | int j=p.second.second; 34 | s.erase(it); 35 | for(int k=-1;k<=1;k++) 36 | for(int l=-1;l<=1;l++) 37 | { 38 | int x=i+k; 39 | int y=j+l; 40 | if(k!=l&&k!=(-1)*l&&isright(x,y,n)) 41 | { 42 | 43 | if(d+grid[x][y]>=dis[x][y]) continue; 44 | if(dis[x][y]!=INT_MAX) 45 | s.erase(s.find({dis[x][y],{x,y}})); 46 | dis[x][y] = d+grid[x][y]; 47 | s.insert({dis[x][y],{x,y}}); 48 | } 49 | } 50 | } 51 | 52 | return dis[n-1][n-1]; 53 | } 54 | }; 55 | 56 | // { Driver Code Starts. 57 | int main(){ 58 | int tc; 59 | cin >> tc; 60 | while(tc--){ 61 | int n; 62 | cin >> n; 63 | vector>grid(n, vector(n, -1)); 64 | for(int i = 0; i < n; i++){ 65 | for(int j = 0; j < n; j++){ 66 | cin >> grid[i][j]; 67 | } 68 | } 69 | Solution obj; 70 | int ans = obj.minimumCostPath(grid); 71 | cout << ans << "\n"; 72 | } 73 | return 0; 74 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/MinimumSwapToSort.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | 9 | class Solution 10 | { 11 | public: 12 | //Function to find the minimum number of swaps required to sort the array. 13 | int minSwaps(vector&nums) 14 | { 15 | // Code here 16 | int n = nums.size(); 17 | int ans = 0; 18 | vector> v(n); 19 | for(int i=0; i> tc; 40 | while(tc--){ 41 | int n; 42 | cin >> n; 43 | vectornums(n); 44 | for(int i = 0; i < n; i++) 45 | cin >> nums[i]; 46 | Solution obj; 47 | int ans = obj.minSwaps(nums); 48 | cout << ans <<"\n"; 49 | } 50 | return 0; 51 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/ShortestSourceToDestinationPath.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution { 11 | public: 12 | int shortestDistance(int N, int M, vector> A, int X, int Y) { 13 | // code here 14 | if(A[0][0]==0) return -1; 15 | int dx[4]={1,-1,0,0}; 16 | int dy[4]={0,0,1,-1}; 17 | queue> q; 18 | q.push({0,0}); 19 | int count=0; 20 | A[0][0]=0; 21 | while(!q.empty()){ 22 | int sz=q.size(); 23 | while(sz--){ 24 | pair p=q.front(); 25 | q.pop(); 26 | int i=p.first; 27 | int j=p.second; 28 | if(i==X&&j==Y) return count; 29 | for(int d=0; d<4; d++){ 30 | int x=i+dx[d]; 31 | int y=j+dy[d]; 32 | if(x>=0&&y>=0&&x> t; 49 | while (t--) { 50 | int N, M, x, y; 51 | cin >> N >> M; 52 | vector> v(N, vector(M)); 53 | for (int i = 0; i < N; i++) 54 | for (int j = 0; j < M; j++) cin >> v[i][j]; 55 | cin >> x >> y; 56 | Solution ob; 57 | cout << ob.shortestDistance(N, M, v, x, y) << "\n"; 58 | } 59 | } // } Driver Code Ends -------------------------------------------------------------------------------- /graph/SnakeAndLadder.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | int minThrow(int n, int a[]){ 13 | // code here 14 | mapmp; 15 | for(int i=0;i<2*n-1;i+=2) 16 | { 17 | mp[a[i]]=a[i+1]; 18 | } 19 | int moves=0; 20 | vectorvisited(31,0); 21 | queueq; 22 | q.push(1); 23 | visited[1]=1; 24 | bool found=false; 25 | while(!q.empty()&&found==false) 26 | { 27 | int p=q.size(); 28 | while(p--) 29 | { 30 | int t=q.front(); 31 | q.pop(); 32 | for(int die=1;die<=6;die++) 33 | { 34 | if(t+die==30) 35 | found=true; 36 | if(t+die<=30&&mp[t+die]&&!visited[t+die]) 37 | { 38 | visited[mp[t+die]]=1; 39 | if(t+die==30) 40 | found=true; 41 | q.push(mp[t+die]); 42 | } 43 | else if(t+die<=30&&!visited[t+die]) 44 | { 45 | visited[t+die]=1; 46 | q.push(t+die); 47 | } 48 | } 49 | } 50 | moves++; 51 | } 52 | if(found) 53 | return moves; 54 | return -1; 55 | 56 | } 57 | }; 58 | 59 | // { Driver Code Starts. 60 | 61 | int main(){ 62 | int t; 63 | cin>>t; 64 | while(t--){ 65 | int N; 66 | cin>>N; 67 | int arr[2*N]; 68 | for(int i = 0;i < 2*N;i++) 69 | cin>>arr[i]; 70 | 71 | Solution ob; 72 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution 9 | { 10 | public: 11 | //Function to find number of strongly connected components in the graph. 12 | 13 | void topo_sort(vectoradj[],int V,bool visited[],int s,stack&st) 14 | { 15 | visited[s]=true; 16 | for(auto x:adj[s]) 17 | { 18 | if(visited[x]==false) 19 | topo_sort(adj,V,visited,x,st); 20 | } 21 | st.push(s); 22 | } 23 | 24 | void topo(vectoradj[],int V,stack&st) 25 | { 26 | 27 | bool visited[V]={false}; 28 | for(int i=0;iadj[],int V,vectortranspose[]) 37 | { 38 | for(int i=0;itranspose[],int V,bool visited2[],int s) 47 | { 48 | visited2[s]=true; 49 | for(auto x:transpose[s]) 50 | { 51 | if(visited2[x]==false) 52 | helper(transpose,V,visited2,x); 53 | } 54 | } 55 | 56 | 57 | int kosaraju(int V, vector adj[]) 58 | { 59 | stackst; 60 | topo(adj,V,st); 61 | 62 | 63 | int topo_arr[V]; 64 | int i=0; 65 | while(st.empty()==false) 66 | { 67 | int u=st.top(); 68 | st.pop(); 69 | topo_arr[i++]=u; 70 | } 71 | 72 | vectortranspose[V]; 73 | reverse(adj,V,transpose); 74 | 75 | bool visited2[V]={false}; 76 | int count=0; 77 | for(int i=0;i> t; 98 | while(t--) 99 | { 100 | int V, E; 101 | cin >> V >> E; 102 | 103 | vector adj[V]; 104 | 105 | for(int i = 0; i < E; i++) 106 | { 107 | int u, v; 108 | cin >> u >> v; 109 | adj[u].push_back(v); 110 | } 111 | 112 | Solution obj; 113 | cout << obj.kosaraju(V, adj) << "\n"; 114 | } 115 | 116 | return 0; 117 | } 118 | 119 | // } Driver Code Ends -------------------------------------------------------------------------------- /graph/WordBoggle.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | class Solution { 10 | public: 11 | 12 | bool dfs(vector > &board, string word, vector > &visited, int row, int col, int idx){ 13 | if(idx == word.length()){ 14 | return true; 15 | } 16 | 17 | if(row >=0 && row < board.size() && col >=0 && col < board[0].size() && visited[row][col] == false && board[row][col] == word[idx]){ 18 | visited[row][col] = true; 19 | 20 | if(dfs(board, word, visited, row-1, col-1, idx+1) || 21 | dfs(board, word, visited, row-1, col, idx+1) || 22 | dfs(board, word, visited, row-1, col+1, idx+1) || 23 | dfs(board, word, visited, row, col-1, idx+1) || 24 | dfs(board, word, visited, row, col+1, idx+1) || 25 | dfs(board, word, visited, row+1, col-1, idx+1) || 26 | dfs(board, word, visited, row+1, col, idx+1) || 27 | dfs(board, word, visited, row+1, col+1, idx+1)) 28 | return true; 29 | 30 | visited[row][col] = false; 31 | } 32 | return false; 33 | } 34 | 35 | bool valid(vector > &board, string word){ 36 | int m = board.size(); 37 | int n = board[0].size(); 38 | 39 | vector > visited(m, vector(n, false)); 40 | 41 | int idx = 0; 42 | for(int i=0; i wordBoggle(vector >& board, vector& dictionary) { 55 | // Code here 56 | vector ans; 57 | for(int i=0; i> t; 72 | while (t--) { 73 | int N; 74 | cin >> N; 75 | vector dictionary; 76 | for (int i = 0; i < N; ++i) { 77 | string s; 78 | cin >> s; 79 | dictionary.push_back(s); 80 | } 81 | 82 | int R, C; 83 | cin >> R >> C; 84 | vector > board(R); 85 | for (int i = 0; i < R; i++) { 86 | board[i].resize(C); 87 | for (int j = 0; j < C; j++) cin >> board[i][j]; 88 | } 89 | Solution obj; 90 | vector output = obj.wordBoggle(board, dictionary); 91 | if (output.size() == 0) 92 | cout << "-1"; 93 | else { 94 | sort(output.begin(), output.end()); 95 | for (int i = 0; i < output.size(); i++) cout << output[i] << " "; 96 | } 97 | cout << endl; 98 | } 99 | } 100 | // } Driver Code Ends -------------------------------------------------------------------------------- /graph/bfs.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector bfs(vector g[], int N); 7 | 8 | int main() { 9 | int T; 10 | cin >> T; 11 | while (T--) { 12 | int N, E; 13 | cin >> N >> E; 14 | vector adj[N]; 15 | for (int i = 0; i < E; i++) { 16 | int u, v; 17 | cin >> u >> v; 18 | adj[u].push_back(v); 19 | } 20 | vector res = bfs(adj, N); 21 | for (int i = 0; i < res.size (); i++) cout << res[i] << " "; 22 | cout << endl; 23 | } 24 | }// } Driver Code Ends 25 | 26 | 27 | /* You have to complete this function*/ 28 | 29 | /* Function to do BFS of graph 30 | * g[]: adj list of the graph 31 | * N : number of vertices 32 | */ 33 | vector bfs(vector g[], int N) { 34 | 35 | // Your code here 36 | queue queue; 37 | vector ans; 38 | vector visited(N); 39 | 40 | if(N){ 41 | queue.push(0); 42 | } 43 | while(queue.size()){ 44 | int node = queue.front(); 45 | queue.pop(); 46 | if(visited[node]){ 47 | continue; 48 | } 49 | visited[node] = true; 50 | ans.push_back(node); 51 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | /* Function to do DFS of graph 10 | 11 | g : adjacency list of graph 12 | N : number of vertices 13 | 14 | return a list containing the DFS traversal of the given graph 15 | */ 16 | vector dfs(vector g[], int N) 17 | { 18 | // Your code here 19 | vector ans; 20 | stack s; 21 | vector visited(N); 22 | if(N){ 23 | s.push(0); 24 | } 25 | while(s.size()){ 26 | int node = s.top(); 27 | s.pop(); 28 | if(visited[node]) continue; 29 | ans.push_back(node); 30 | visited[node] = 1; 31 | 32 | for(int i = g[node].size()-1; i>=0; i--){ 33 | if(!visited[g[node][i]]){ 34 | s.push(g[node][i]); 35 | } 36 | } 37 | } 38 | return ans; 39 | 40 | } 41 | 42 | // { Driver Code Starts. 43 | 44 | int main() 45 | { 46 | int T; 47 | cin>>T; 48 | while(T--) 49 | { 50 | 51 | int N, E; 52 | cin>>N>>E; 53 | 54 | vector g[N]; 55 | 56 | 57 | for(int i=0;i>u>>v; 61 | g[u].push_back(v); 62 | g[v].push_back(u); 63 | } 64 | 65 | vector res = dfs(g, N); 66 | for (int i = 0; i < res.size (); i++) 67 | cout << res[i] << " "; 68 | cout< 3 | 4 | using namespace std; 5 | 6 | vector topoSort(int N, vector adj[]); 7 | 8 | /* Function to check if elements returned by user 9 | * contains the elements in topological sorted form 10 | * V: number of vertices 11 | * *res: array containing elements in topological sorted form 12 | * adj[]: graph input 13 | */ 14 | bool check(int V, vector &res, vector adj[]) { 15 | vector map(V, -1); 16 | for (int i = 0; i < V; i++) { 17 | map[res[i]] = i; 18 | } 19 | for (int i = 0; i < V; i++) { 20 | for (int v : adj[i]) { 21 | if (map[i] > map[v]) return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | // Driver Code 28 | int main() { 29 | int T; 30 | cin >> T; 31 | while (T--) { 32 | int N, E; 33 | cin >> E >> N; 34 | int u, v; 35 | 36 | vector adj[N]; 37 | 38 | for (int i = 0; i < E; i++) { 39 | cin >> u >> v; 40 | adj[u].push_back(v); 41 | } 42 | 43 | vector res = topoSort(N, adj); 44 | 45 | cout << check(N, res, adj) << endl; 46 | } 47 | }// } Driver Code Ends 48 | 49 | 50 | // The Graph structure is as folows 51 | 52 | /* Function which sorts the graph vertices in topological form 53 | * N: number of vertices 54 | * adj[]: input graph 55 | */ 56 | vector topoSort(int V, vector adj[]) { 57 | // Your code here 58 | vector inorder(V, 0); 59 | queue q; 60 | vector ans; 61 | 62 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | bool comp(pair a, pair b){ 9 | return a.second < b.second; 10 | } 11 | 12 | int activitySelection(int start[], int end[], int n){ 13 | // Your code here 14 | vector> jobTime; 15 | for(int i=0; i= last){ 25 | count++; 26 | last = jobTime[i].second; 27 | } 28 | } 29 | return count; 30 | } 31 | 32 | // { Driver Code Starts. 33 | int main() 34 | { 35 | int t; 36 | 37 | //testcases 38 | cin >> t; 39 | while(t--) 40 | { 41 | //size of array 42 | int n; 43 | cin >> n; 44 | int start[n], end[n]; 45 | 46 | //adding elements to arrays start and end 47 | for(int i=0;i>start[i]; 49 | for(int i=0;i>end[i]; 51 | 52 | //function call 53 | cout << activitySelection(start, end, n) << endl; 54 | } 55 | return 0; 56 | } 57 | // } Driver Code Ends -------------------------------------------------------------------------------- /greedy/GeekCollectsTheBall.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | int maxBalls(int N, int M, int a[], int b[]){ 13 | // code here 14 | int sum1 = 0; 15 | int sum2 = 0; 16 | int ans = 0; 17 | int i=0, j=0; 18 | while(i < N && j < M){ 19 | if(a[i] == b[j]){ 20 | while(a[i] == a[i+1] && i+1 < N){ 21 | sum1 += a[i]; 22 | i++; 23 | } 24 | while(b[j] == b[j+1] && j+1 < M){ 25 | sum2 += b[j]; 26 | j++; 27 | } 28 | ans += max(sum1, sum2) + a[i]; 29 | sum1 = 0; 30 | sum2 = 0; 31 | i++; 32 | j++; 33 | }else if(a[i] > b[j]){ 34 | sum2 += b[j]; 35 | j++; 36 | }else{ 37 | sum1 += a[i]; 38 | i++; 39 | } 40 | } 41 | if(i == N){ 42 | while(j>t; 62 | while(t--){ 63 | int N, M; 64 | cin>>N>>M; 65 | int a[N], b[M]; 66 | for(int i = 0;i < N;i++) 67 | cin>>a[i]; 68 | for(int i = 0;i < M;i++) 69 | cin>>b[i]; 70 | 71 | Solution ob; 72 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | //User function Template for C++ 11 | 12 | class Solution{ 13 | public: 14 | int toyCount(int N, int K, int arr[]) 15 | { 16 | // code here 17 | sort(arr, arr+N); 18 | int sum = 0; 19 | int count = 0; 20 | for(int i=0; i K){ 23 | return count; 24 | } 25 | count++; 26 | } 27 | return count; 28 | } 29 | }; 30 | 31 | // { Driver Code Starts. 32 | 33 | int main(){ 34 | int t; 35 | cin>>t; 36 | while(t--){ 37 | int N, K; 38 | cin>>N>>K; 39 | int arr[N]; 40 | for(int i = 0;i < N;i++) 41 | cin>>arr[i]; 42 | 43 | Solution ob; 44 | cout< 3 | using namespace std; 4 | #define ll long long 5 | 6 | long long int minValue(int a[], int b[], int n); 7 | 8 | int main() 9 | { 10 | ll t; 11 | cin>>t; 12 | while(t--) 13 | { 14 | int n, i; 15 | cin>>n; 16 | int a[n], b[n]; 17 | for(i=0;i>a[i]; 19 | for(i=0;i>b[i]; 21 | 22 | cout<< minValue(a, b, n) < ()); 36 | for(int i=0; i 3 | 4 | using namespace std; 5 | 6 | void maxMeetings(int *, int *, int); 7 | 8 | int main() { 9 | int t; 10 | cin >> t; 11 | while (t--) { 12 | int n; 13 | cin >> n; 14 | int start[n], end[n]; 15 | for (int i = 0; i < n; i++) cin >> start[i]; 16 | 17 | for (int i = 0; i < n; i++) cin >> end[i]; 18 | 19 | maxMeetings(start, end, n); 20 | cout << endl; 21 | } 22 | return 0; 23 | }// } Driver Code Ends 24 | 25 | 26 | void maxMeetings(int start[], int end[], int n) { 27 | // Your code here 28 | multimap, int> meetings; 29 | int last = 0; 30 | vector ans; 31 | for(int i=0; i last){ 35 | ans.push_back(it.first.second), last = it.first.first; 36 | } 37 | }for(auto it: ans) 38 | cout << it << " "; 39 | 40 | } -------------------------------------------------------------------------------- /greedy/ShopInCandyStore.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; cin>>t; 6 | while(t--) 7 | { 8 | int n,k; cin>>n>>k; long int a[n],min=0,max=0,c=0; 9 | for(int i=0;i>a[i]; 10 | sort(a,a+n); 11 | int x=(n/(k+1)); if((n%(k+1))>0) {x++;} 12 | 13 | for(int i=0;i 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution { 7 | public: 8 | bool canPair(vector nums, int k) { 9 | // Code here. 10 | int n = nums.size(); 11 | if(n & 1 != 0){ 12 | return false; 13 | } 14 | map m; 15 | for(int i=0; i> tc; 42 | while (tc--) { 43 | int n, k; 44 | cin >> n >> k; 45 | vector nums(n); 46 | for (int i = 0; i < nums.size(); i++) cin >> nums[i]; 47 | Solution ob; 48 | bool ans = ob.canPair(nums, k); 49 | if (ans) 50 | cout << "True\n"; 51 | else 52 | cout << "False\n"; 53 | } 54 | return 0; 55 | } // } Driver Code Ends -------------------------------------------------------------------------------- /hashing/CommonElements.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | //Back-end complete function Template for C++ 11 | 12 | vector common_element(vectorv1,vectorv2) 13 | { 14 | // Your code here 15 | int a[100001] = {}; 16 | vector ans; 17 | for(int i=0; i 0){ 22 | ans.push_back(v2[i]); 23 | a[v2[i]]--; 24 | } 25 | } 26 | sort(ans.begin(), ans.end()); 27 | return ans; 28 | } 29 | 30 | // { Driver Code Starts. 31 | 32 | 33 | int main(){ 34 | int t; 35 | cin>>t; 36 | while(t--){ 37 | 38 | int n; 39 | cin>>n; 40 | vectorv1(n,0); 41 | for(int i=0;i>v1[i]; 44 | } 45 | int m; 46 | cin>>m; 47 | vectorv2(m,0); 48 | for(int i=0;i>v2[i]; 51 | } 52 | vectorresult; 53 | result=common_element(v1,v2); 54 | for(auto i:result) 55 | { 56 | cout< 3 | using namespace std; 4 | 5 | vector countDistinct(int[], int, int); 6 | 7 | int main() 8 | { 9 | int t; 10 | cin >> t; 11 | while (t--) 12 | { 13 | 14 | int n, k; 15 | cin >> n >> k; 16 | int a[n]; 17 | for (int i = 0; i < n; i++) 18 | cin >> a[i]; 19 | vector result = countDistinct(a, n, k); 20 | for (int i : result) 21 | cout << i << " "; 22 | cout << endl; 23 | } 24 | return 0; 25 | }// } Driver Code Ends 26 | 27 | 28 | 29 | vector countDistinct (int A[], int n, int k) 30 | { 31 | //code here. 32 | unordered_map m; 33 | 34 | for(int i = 0; i < k; i++) 35 | { 36 | m[A[i]]++; 37 | } 38 | 39 | vector v; 40 | v.push_back(m.size()); 41 | 42 | for(int i = k; i < n; i++) 43 | { 44 | m[A[i - k]]--; 45 | 46 | if(m[A[i - k]] == 0) 47 | { 48 | m.erase(A[i - k]); 49 | } 50 | 51 | m[A[i]]++; 52 | 53 | v.push_back(m.size()); 54 | } 55 | 56 | return v; 57 | } -------------------------------------------------------------------------------- /hashing/FindAllSumFourNumber.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector > fourSum(vector &a, int k); 7 | 8 | // Position this line where user code will be pasted. 9 | int main() { 10 | int t; 11 | cin >> t; 12 | while (t--) { 13 | int n, k, i; 14 | cin >> n >> k; 15 | vector a(n); 16 | for (i = 0; i < n; i++) { 17 | cin >> a[i]; 18 | } 19 | vector > ans = fourSum(a, k); 20 | for (auto &v : ans) { 21 | for (int &u : v) { 22 | cout << u << " "; 23 | } 24 | cout << "$"; 25 | } 26 | if (ans.empty()) { 27 | cout << -1; 28 | } 29 | cout << "\n"; 30 | } 31 | return 0; 32 | }// } Driver Code Ends 33 | 34 | 35 | // User function template for C++ 36 | 37 | // arr[] : int input array of integers 38 | // k : the quadruple sum required 39 | vector > fourSum(vector &arr, int k) { 40 | 41 | if(arr.size() < 4){ 42 | return {{}}; 43 | } 44 | int n = arr.size(); 45 | vector> v; 46 | long long sumA,sumB; 47 | sort(arr.begin(),arr.end()); 48 | int left,right; 49 | for(int i = 0 ; i < n-3 ; i++) 50 | { 51 | if(i > 0 && arr[i] == arr[i-1]){ 52 | continue; 53 | } 54 | for(int j = i+1 ; j < n-2; j++){ 55 | if(j > i+1 && arr[j] == arr[j-1]){ 56 | continue; 57 | } 58 | sumA = arr[i]+arr[j]; 59 | left = j+1; 60 | right = n-1; 61 | while(left < right){ 62 | sumB = sumA + arr[left]+arr[right]; 63 | if(sumB == k){ 64 | v.push_back({arr[i],arr[j],arr[left],arr[right]}); 65 | left++; 66 | right--; 67 | while(left < right && arr[left] == arr[left-1]){ 68 | left++; 69 | } 70 | while(left < right && arr[right] == arr[right+1]){ 71 | right--; 72 | } 73 | } 74 | else if(sumB < k){ 75 | left++; 76 | } 77 | else{ 78 | right--; 79 | } 80 | } 81 | } 82 | } 83 | return v; 84 | } -------------------------------------------------------------------------------- /hashing/LargestSubarrayWith0sum.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int maxLen(int A[], int n); 6 | 7 | int main() 8 | { 9 | int T; 10 | cin >> T; 11 | while (T--) 12 | { 13 | int N; 14 | cin >> N; 15 | int A[N]; 16 | for (int i = 0; i < N; i++) 17 | cin >> A[i]; 18 | cout << maxLen(A, N) << endl; 19 | } 20 | } 21 | // } Driver Code Ends 22 | 23 | 24 | /*You are required to complete this function*/ 25 | 26 | int maxLen(int A[], int n) 27 | { 28 | // Your code here 29 | map m; 30 | int sum = 0, ans = 0; 31 | for(int i=0; i 47 | using namespace std; 48 | 49 | int maxLen(int A[], int n); 50 | 51 | int main() 52 | { 53 | int T; 54 | cin >> T; 55 | while (T--) 56 | { 57 | int N; 58 | cin >> N; 59 | int A[N]; 60 | for (int i = 0; i < N; i++) 61 | cin >> A[i]; 62 | cout << maxLen(A, N) << endl; 63 | } 64 | } 65 | // } Driver Code Ends 66 | 67 | 68 | /*You are required to complete this function*/ 69 | 70 | int maxLen(int A[], int n) 71 | { 72 | // Your code here 73 | map m; 74 | int sum = 0, ans = 0; 75 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | class Solution{ 10 | public: 11 | // arr[] : the input array 12 | // N : size of the array arr[] 13 | 14 | // return the length of the longest subsequene of consecutive integers 15 | int findLongestConseqSubseq(int arr[], int N) 16 | { 17 | //Your code here 18 | if(N==1){ 19 | return 1; 20 | } 21 | int m = 0, count = 1; 22 | sort(arr, arr+N); 23 | for(int i=1; i>t; 44 | while(t--) 45 | { 46 | cin>>n; 47 | for(i=0;i>a[i]; 49 | Solution obj; 50 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function template in C++ 10 | class Solution{ 11 | public: 12 | // A1[] : the input array-1 13 | // N : size of the array A1[] 14 | // A2[] : the input array-2 15 | // M : size of the array A2[] 16 | vector sortA1ByA2(vector A1, int N, vector A2, int M) 17 | { 18 | //Your code here 19 | vector v; 20 | map m; 21 | for(int i=0; isecond--){ 27 | v.push_back(A2[i]); 28 | } 29 | } 30 | } 31 | for(int i=0; i> t; 52 | 53 | while(t--){ 54 | 55 | int n, m; 56 | cin >> n >> m; 57 | 58 | vector a1(n); 59 | vector a2(m); 60 | 61 | for(int i = 0;i> a1[i]; 63 | } 64 | 65 | for(int i = 0;i> a2[i]; 67 | } 68 | 69 | Solution ob; 70 | a1 = ob.sortA1ByA2(a1, n, a2, m); 71 | 72 | 73 | for (int i = 0; i < n; i++) 74 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | //code 6 | int t; 7 | cin >> t; 8 | while(t--){ 9 | int n; 10 | cin >> n; 11 | int arr[n]; 12 | for(int i=0; i> arr[i]; 14 | } 15 | sort(arr, arr+n); 16 | map m; 17 | for(int i=0; i> v(n); 21 | for(auto x: m){ 22 | v[x.second].push_back(x.first); 23 | } 24 | for(int i=n-1; i>=0; i--){ 25 | if(v.size() != 0){ 26 | for(auto x: v[i]){ 27 | for(int count = 1; count <= i; count++){ 28 | cout << x << " "; 29 | } 30 | } 31 | } 32 | } 33 | cout << endl; 34 | } 35 | return 0; 36 | } -------------------------------------------------------------------------------- /hashing/SwappingPairsMakeSumEqual.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | 8 | public: 9 | int findSwapValues(int A[], int n, int B[], int m) 10 | { 11 | // Your code goes here 12 | int sumA=0, sumB=0, sum=0; 13 | map m1; 14 | map m2; 15 | for(int i=0; i 0 && m2[A[i]] > 0 ){ 26 | return 1; 27 | } 28 | } 29 | return -1; 30 | }else if(sumA>sumB){ 31 | sum = (sumA-sumB); 32 | if(sum&1 != 0){ 33 | return -1; 34 | } 35 | for(int i=0; i 0){ 37 | return 1; 38 | } 39 | } 40 | }else{ 41 | sum = (sumB-sumA); 42 | if(sum&1 != 0){ 43 | return -1; 44 | } 45 | for(int i=0; i> t; 62 | while (t--) 63 | { 64 | int n,m; 65 | cin>>n>>m; 66 | int a[n]; 67 | int b[m]; 68 | for(int i=0;i>a[i]; 70 | for(int i=0;i>b[i]; 72 | 73 | 74 | Solution ob; 75 | cout << ob.findSwapValues(a, n, b, m); 76 | cout << "\n"; 77 | 78 | } 79 | return 0; 80 | } 81 | 82 | 83 | 84 | 85 | 86 | // } Driver Code Ends -------------------------------------------------------------------------------- /linked list/FlatteningLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | struct Node{ 5 | int data; 6 | struct Node * next; 7 | struct Node * bottom; 8 | 9 | Node(int x){ 10 | data = x; 11 | next = NULL; 12 | bottom = NULL; 13 | } 14 | 15 | }; 16 | 17 | using namespace std; 18 | 19 | void printList(Node *Node) 20 | { 21 | while (Node != NULL) 22 | { 23 | printf("%d ", Node->data); 24 | Node = Node->bottom; 25 | } 26 | } 27 | 28 | Node* flatten (Node* root); 29 | 30 | int main(void) { 31 | 32 | int t; 33 | cin>>t; 34 | while(t--){ 35 | int n,m,flag=1,flag1=1; 36 | struct Node * temp=NULL; 37 | struct Node * head=NULL; 38 | struct Node * pre=NULL; 39 | struct Node * tempB=NULL; 40 | struct Node * preB=NULL; 41 | cin>>n; 42 | int work[n]; 43 | for(int i=0;i>work[i]; 45 | for(int i=0;inext = NULL; 52 | temp->bottom = NULL; 53 | 54 | if(flag){ 55 | head = temp; 56 | pre = temp; 57 | flag = 0; 58 | flag1 = 1; 59 | } 60 | else{ 61 | pre->next = temp; 62 | pre = temp; 63 | flag1 = 1; 64 | } 65 | for(int j=0;jbottom=tempB; 73 | preB=tempB; 74 | flag1=0; 75 | } 76 | else{ 77 | preB->bottom=tempB; 78 | preB=tempB; 79 | } 80 | } 81 | } 82 | Node *fun = head; 83 | Node *fun2=head; 84 | 85 | Node* root = flatten(head); 86 | printList(root); 87 | cout<data <= b->data){ 121 | a->bottom = merge(a->bottom, b); 122 | return a; 123 | }else{ 124 | b->bottom = merge(b->bottom, a); 125 | return b; 126 | } 127 | } 128 | 129 | /* Function which returns the root of 130 | the flattened linked list. */ 131 | Node *flatten(Node *root) 132 | { 133 | // Your code here 134 | if(root == NULL || root->next == NULL){ 135 | return root; 136 | } 137 | root->next = flatten(root->next); 138 | 139 | root = merge(root, root->next); 140 | 141 | return root; 142 | } 143 | 144 | -------------------------------------------------------------------------------- /linked list/IntersectionPointInY-ShapedLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /* Link list Node */ 7 | struct Node 8 | { 9 | int data; 10 | struct Node *next; 11 | Node(int x) 12 | { 13 | data = x; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | int intersectPoint(struct Node* head1, struct Node* head2); 19 | 20 | Node* inputList(int size) 21 | { 22 | if(size==0) return NULL; 23 | 24 | int val; 25 | cin>> val; 26 | 27 | Node *head = new Node(val); 28 | Node *tail = head; 29 | 30 | for(int i=0; i>val; 33 | tail->next = new Node(val); 34 | tail = tail->next; 35 | } 36 | 37 | return head; 38 | } 39 | 40 | /* Driver program to test above function*/ 41 | int main() 42 | { 43 | int T,n1,n2,n3; 44 | 45 | cin>>T; 46 | while(T--) 47 | { 48 | cin>>n1>>n2>>n3; 49 | 50 | Node* head1 = inputList(n1); 51 | Node* head2 = inputList(n2); 52 | Node* common = inputList(n3); 53 | 54 | Node* temp = head1; 55 | while(temp!=NULL && temp->next != NULL) 56 | temp = temp->next; 57 | if(temp!=NULL) temp->next = common; 58 | 59 | temp = head2; 60 | while(temp!=NULL && temp->next != NULL) 61 | temp = temp->next; 62 | if(temp!=NULL) temp->next = common; 63 | 64 | cout << intersectPoint(head1, head2) << endl; 65 | } 66 | return 0; 67 | } 68 | 69 | // } Driver Code Ends 70 | 71 | 72 | /* Linked List Node 73 | struct Node { 74 | int data; 75 | struct Node *next; 76 | Node(int x) { 77 | data = x; 78 | next = NULL; 79 | } 80 | }; */ 81 | 82 | /* Should return data of intersection point of two linked 83 | lists head1 and head2. 84 | If there is no intersecting point, then return -1. */ 85 | int intersectPoint(Node* head1, Node* head2) 86 | { 87 | // Your Code Here 88 | if(head1 == NULL || head2 == NULL){ 89 | return -1; 90 | } 91 | int n=0, m=0; 92 | Node* temp=head1; 93 | Node* temp1=head1; 94 | Node* temp2=head2; 95 | while(temp){ 96 | temp=temp->next; 97 | n++; 98 | } 99 | temp = head2; 100 | while(temp){ 101 | temp=temp->next; 102 | m++; 103 | } 104 | if(m > n){ 105 | int t=m-n; 106 | for(int i=0; inext; 108 | } 109 | for(int i=0; inext == temp1->next){ 111 | return temp2->next->data; 112 | } 113 | temp1 = temp1->next; 114 | temp2 = temp2->next; 115 | } 116 | }else{ 117 | int t=n-m; 118 | for(int i=0; inext; 120 | } 121 | for(int i=0; inext == temp1->next){ 123 | return temp2->next->data; 124 | } 125 | temp1 = temp1->next; 126 | temp2 = temp2->next; 127 | } 128 | } 129 | return -1; 130 | } 131 | 132 | -------------------------------------------------------------------------------- /linked list/LoopInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // driver code 3 | 4 | #include 5 | using namespace std; 6 | 7 | struct Node 8 | { 9 | int data; 10 | Node* next; 11 | 12 | Node(int val) 13 | { 14 | data = val; 15 | next = NULL; 16 | } 17 | }; 18 | 19 | void loopHere(Node* head, Node* tail, int position) 20 | { 21 | if(position==0) return; 22 | 23 | Node* walk = head; 24 | for(int i=1; inext; 26 | tail->next = walk; 27 | } 28 | 29 | 30 | // } Driver Code Ends 31 | /* 32 | 33 | struct Node 34 | { 35 | int data; 36 | struct Node *next; 37 | Node(int x) { 38 | data = x; 39 | next = NULL; 40 | } 41 | 42 | */ 43 | class Solution 44 | { 45 | public: 46 | bool detectLoop(Node* head) 47 | { 48 | // your code here 49 | if(head == NULL){ 50 | return false; 51 | } 52 | Node* fast = head; 53 | Node* slow = head; 54 | while(fast->next != NULL && fast->next->next != NULL){ 55 | fast = fast->next->next; 56 | slow = slow->next; 57 | if(fast == slow){ 58 | return true; 59 | } 60 | } 61 | return false; 62 | } 63 | }; 64 | 65 | 66 | // { Driver Code Starts. 67 | 68 | int main() 69 | { 70 | int t; 71 | cin>>t; 72 | while(t--) 73 | { 74 | int n, num; 75 | cin>>n; 76 | 77 | Node *head, *tail; 78 | cin>> num; 79 | head = tail = new Node(num); 80 | 81 | for(int i=0 ; i> num; 84 | tail->next = new Node(num); 85 | tail = tail->next; 86 | } 87 | 88 | int pos; 89 | cin>> pos; 90 | loopHere(head,tail,pos); 91 | 92 | Solution ob; 93 | if(ob.detectLoop(head) ) 94 | cout<< "True\n"; 95 | else 96 | cout<< "False\n"; 97 | } 98 | return 0; 99 | } 100 | // } Driver Code Ends -------------------------------------------------------------------------------- /linked list/NthNodeFromEndOfLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // C program to find n'th Node in linked list 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | /* Link list Node */ 9 | struct Node { 10 | int data; 11 | struct Node *next; 12 | Node(int x) { 13 | data = x; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | 19 | /* Function to get the nth node from the last of a linked list*/ 20 | int getNthFromLast(struct Node* head, int n); 21 | 22 | 23 | 24 | /* Driver program to test above function*/ 25 | int main() 26 | { 27 | int T,i,n,l,k; 28 | 29 | cin>>T; 30 | 31 | while(T--){ 32 | struct Node *head = NULL, *tail = NULL; 33 | 34 | cin>>n>>k; 35 | int firstdata; 36 | cin>>firstdata; 37 | head = new Node(firstdata); 38 | tail = head; 39 | for(i=1;i>l; 42 | tail->next = new Node(l); 43 | tail = tail->next; 44 | } 45 | 46 | cout<next; 73 | count++; 74 | } 75 | if(n>count){ 76 | return -1; 77 | } 78 | temp = head; 79 | for(int i=0; i<=count-n-1; i++){ 80 | temp=temp->next; 81 | } 82 | return temp->data; 83 | } 84 | -------------------------------------------------------------------------------- /linked list/RemoveLoopInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // driver code 3 | 4 | #include 5 | using namespace std; 6 | 7 | struct Node 8 | { 9 | int data; 10 | Node* next; 11 | 12 | Node(int val) 13 | { 14 | data = val; 15 | next = NULL; 16 | } 17 | }; 18 | 19 | void loopHere(Node* head, Node* tail, int position) 20 | { 21 | if(position==0) return; 22 | 23 | Node* walk = head; 24 | for(int i=1; inext; 26 | tail->next = walk; 27 | } 28 | 29 | bool isLoop(Node* head) 30 | { 31 | if(!head) return false; 32 | 33 | Node* fast = head->next; 34 | Node* slow = head; 35 | 36 | while( fast != slow) 37 | { 38 | if( !fast || !fast->next ) return false; 39 | fast=fast->next->next; 40 | slow=slow->next; 41 | } 42 | 43 | return true; 44 | } 45 | 46 | int length(Node* head) 47 | { 48 | int ret = 0; 49 | while(head) 50 | { 51 | ret++; 52 | head = head->next; 53 | } 54 | return ret; 55 | } 56 | 57 | 58 | // } Driver Code Ends 59 | /* 60 | structure of linked list node: 61 | 62 | struct Node 63 | { 64 | int data; 65 | Node* next; 66 | 67 | Node(int val) 68 | { 69 | data = val; 70 | next = NULL; 71 | } 72 | }; 73 | 74 | */ 75 | 76 | class Solution 77 | { 78 | public: 79 | void removeLoop(Node* head){ 80 | Node *slow=head; 81 | Node *fast=head; 82 | if(head == NULL || head->next == NULL){ 83 | return; 84 | } 85 | while(fast!=NULL && fast->next!=NULL){ 86 | slow = slow->next; 87 | fast = fast->next->next; 88 | if(slow == fast){ 89 | break; 90 | } 91 | } 92 | if(slow==head){ 93 | while(slow->next!=head){ 94 | slow=slow->next; 95 | } 96 | slow->next = NULL; 97 | } 98 | if(slow == fast){ 99 | slow = head; 100 | while(slow->next != fast->next){ 101 | if(slow == fast->next){ 102 | fast->next== NULL; 103 | } 104 | slow = slow->next; 105 | fast = fast->next; 106 | } 107 | fast->next = NULL; 108 | } 109 | } 110 | }; 111 | 112 | // { Driver Code Starts. 113 | 114 | int main() 115 | { 116 | int t; 117 | cin>>t; 118 | while(t--) 119 | { 120 | int n, num; 121 | cin>>n; 122 | 123 | Node *head, *tail; 124 | cin>> num; 125 | head = tail = new Node(num); 126 | 127 | for(int i=0 ; i> num; 130 | tail->next = new Node(num); 131 | tail = tail->next; 132 | } 133 | 134 | int pos; 135 | cin>> pos; 136 | loopHere(head,tail,pos); 137 | 138 | Solution ob; 139 | ob.removeLoop(head); 140 | 141 | if( isLoop(head) || length(head)!=n ) 142 | cout<<"0\n"; 143 | else 144 | cout<<"1\n"; 145 | } 146 | return 0; 147 | } 148 | // } Driver Code Ends -------------------------------------------------------------------------------- /linked list/ReverseLinkedListInGivenGroup.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | struct node 7 | { 8 | int data; 9 | struct node* next; 10 | 11 | node(int x){ 12 | data = x; 13 | next = NULL; 14 | } 15 | 16 | }; 17 | 18 | /* Function to print linked list */ 19 | void printList(struct node *node) 20 | { 21 | while (node != NULL) 22 | { 23 | printf("%d ", node->data); 24 | node = node->next; 25 | } 26 | printf("\n"); 27 | } 28 | 29 | 30 | // } Driver Code Ends 31 | /* 32 | Reverse a linked list 33 | The input list will have at least one element 34 | Return the node which points to the head of the new LinkedList 35 | Node is defined as 36 | struct node 37 | { 38 | int data; 39 | struct node* next; 40 | 41 | node(int x){ 42 | data = x; 43 | next = NULL; 44 | } 45 | 46 | }*head; 47 | */ 48 | 49 | class Solution 50 | { 51 | public: 52 | struct node *reverse (struct node *head, int k) 53 | { 54 | // Complete this method 55 | int c=0; 56 | struct node *parso=NULL; 57 | struct node *aaj=head; 58 | struct node *kal=NULL; 59 | 60 | while(aaj!=NULL && cnext; 62 | aaj->next=parso; 63 | parso=aaj; 64 | aaj=kal; 65 | c++; 66 | } 67 | 68 | if(kal!=NULL){ 69 | head->next=reverse(kal, k); 70 | } 71 | 72 | return parso; 73 | } 74 | }; 75 | 76 | 77 | // { Driver Code Starts. 78 | 79 | /* Drier program to test above function*/ 80 | int main(void) 81 | { 82 | int t; 83 | cin>>t; 84 | 85 | while(t--) 86 | { 87 | struct node* head = NULL; 88 | struct node* temp = NULL; 89 | int n; 90 | cin >> n; 91 | 92 | for(int i=0 ; i> value; 96 | if(i == 0) 97 | { 98 | head = new node(value); 99 | temp = head; 100 | } 101 | else 102 | { 103 | temp->next = new node(value); 104 | temp = temp->next; 105 | } 106 | } 107 | 108 | int k; 109 | cin>>k; 110 | 111 | Solution ob; 112 | head = ob.reverse(head, k); 113 | printList(head); 114 | } 115 | 116 | return(0); 117 | } 118 | 119 | // } Driver Code Ends -------------------------------------------------------------------------------- /linked list/finding_middle_element.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node* next; 9 | 10 | Node(int x){ 11 | data = x; 12 | next = NULL; 13 | } 14 | }; 15 | void printList(Node* node) 16 | { 17 | while (node != NULL) { 18 | cout << node->data <<" "; 19 | node = node->next; 20 | } 21 | cout<<"\n"; 22 | } 23 | /* Function to get the middle of the linked list*/ 24 | int getMiddle(Node *head); 25 | int main() 26 | { 27 | int t; 28 | cin>>t; 29 | while(t--) 30 | { 31 | int n; 32 | cin>>n; 33 | 34 | int data; 35 | cin>>data; 36 | struct Node *head = new Node(data); 37 | struct Node *tail = head; 38 | for (int i = 0; i < n-1; ++i) 39 | { 40 | cin>>data; 41 | tail->next = new Node(data); 42 | tail = tail->next; 43 | } 44 | cout<next != NULL){ 72 | while(temp->next){ 73 | temp = temp->next; 74 | count ++; 75 | } 76 | if(count%2 == 0){ 77 | for(int i=0; i<(count/2); i++){ 78 | head = head->next; 79 | } 80 | }else{ 81 | for(int i=0; i<((count -1)/2); i++){ 82 | head = head->next; 83 | } 84 | } 85 | ans = head->data; 86 | }else if(head == NULL){ 87 | ans = -1; 88 | }else{ 89 | ans = head->data; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /linked list/reverse_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | // C program to find n'th Node in linked list 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | /* Link list Node */ 11 | struct Node { 12 | int data; 13 | struct Node *next; 14 | Node(int x) 15 | { 16 | data = x; 17 | next = NULL; 18 | } 19 | }; 20 | 21 | 22 | /* Function to get the middle of the linked list*/ 23 | struct Node *reverseList(struct Node *head); 24 | 25 | void printList(struct Node *head) 26 | { 27 | struct Node *temp = head; 28 | while (temp != NULL) 29 | { 30 | printf("%d ", temp->data); 31 | temp = temp->next; 32 | } 33 | } 34 | 35 | /* Driver program to test above function*/ 36 | int main() 37 | { 38 | int T,n,l,firstdata; 39 | cin>>T; 40 | 41 | while(T--) 42 | { 43 | struct Node *head = NULL, *tail = NULL; 44 | 45 | cin>>n; 46 | 47 | cin>>firstdata; 48 | head = new Node(firstdata); 49 | tail = head; 50 | 51 | for (int i=1; i>l; 54 | tail->next = new Node(l); 55 | tail = tail->next; 56 | } 57 | 58 | head = reverseList(head); 59 | 60 | printList(head); 61 | cout << endl; 62 | } 63 | return 0; 64 | } 65 | 66 | // } Driver Code Ends 67 | 68 | 69 | /* Linked List Node structure: 70 | 71 | struct Node 72 | { 73 | int data; 74 | struct Node *next; 75 | } 76 | 77 | */ 78 | 79 | // Should reverse list and return new head. 80 | struct Node* reverseList(struct Node *head) 81 | { 82 | // code here 83 | // return head of reversed list 84 | struct Node* temp = head; 85 | struct Node* curr = head; 86 | struct Node* prev = head; 87 | if(temp->next == NULL){ 88 | return head; 89 | }else{ 90 | while(temp->next){ 91 | curr = temp->next; 92 | temp->next = prev; 93 | prev = temp; 94 | temp = curr; 95 | } 96 | head->next = NULL; 97 | head = temp; 98 | head->next = prev; 99 | return head; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /linked list/rotate_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | struct Node *next; 8 | Node(int x) { 9 | data = x; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | Node *rotate(struct Node *head, int k); 15 | 16 | void printList(Node *n) 17 | { 18 | while (n != NULL) 19 | { 20 | cout<< n->data << " "; 21 | n = n->next; 22 | } 23 | cout<< endl; 24 | } 25 | 26 | int main() 27 | { 28 | int t; 29 | cin>>t; 30 | while(t--) 31 | { 32 | int n, val, k; 33 | cin>>n; 34 | 35 | cin>> val; 36 | Node *head = new Node(val); 37 | Node *tail = head; 38 | 39 | for(int i=0; i> val; 42 | tail->next = new Node(val); 43 | tail = tail->next; 44 | } 45 | 46 | cin>> k; 47 | 48 | head = rotate(head,k); 49 | printList(head); 50 | } 51 | return 1; 52 | } 53 | // } Driver Code Ends 54 | 55 | 56 | /* 57 | 58 | struct Node { 59 | int data; 60 | struct Node *next; 61 | Node(int x) { 62 | data = x; 63 | next = NULL; 64 | } 65 | }; 66 | 67 | */ 68 | 69 | // This function should rotate list counter-clockwise 70 | // by k and return new head (if changed) 71 | 72 | Node* rotate(Node* head, int k) 73 | { 74 | // Your code here 75 | struct Node* temp = head; 76 | struct Node* curr = head; 77 | struct Node* first = head; 78 | k -= 1; 79 | while(k--){ 80 | temp = temp->next; 81 | } 82 | if(temp->next != NULL){ 83 | head = temp->next; 84 | curr = temp; 85 | while(temp->next){ 86 | temp = temp->next; 87 | } 88 | temp->next = first; 89 | curr->next = NULL; 90 | } 91 | 92 | return head; 93 | } 94 | -------------------------------------------------------------------------------- /recursion/DecodeString.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | string decodeString(string& s, int& i) { 13 | string result; 14 | while(i < s.length() && s[i] != ']'){ 15 | if(isdigit(s[i])){ 16 | int k = 0; 17 | while(i < s.length() && isdigit(s[i])) 18 | k = k*10 + s[i++] - '0'; 19 | i++; 20 | string r = decodeString(s, i); 21 | while(k-- > 0) 22 | result += r; 23 | i++; 24 | } else 25 | result += s[i++]; 26 | } 27 | return result; 28 | } 29 | 30 | string decodedString(string s){ 31 | // code here 32 | int i=0; 33 | return decodeString(s, i); 34 | } 35 | }; 36 | 37 | // { Driver Code Starts. 38 | 39 | int main(){ 40 | int t; 41 | cin>>t; 42 | while(t--){ 43 | string s; 44 | cin>>s; 45 | 46 | Solution ob; 47 | cout< 2 | using namespace std; 3 | 4 | void floodFill(vector> &vs,int n,int m,int x,int y,int val,int k){ 5 | if(x<0 || x>=n || y<0 || y>=m) 6 | return; 7 | if(vs[x][y]!=val) 8 | return; 9 | 10 | vs[x][y] = k; 11 | floodFill(vs,n,m,x+1,y,val,k); 12 | floodFill(vs,n,m,x,y+1,val,k); 13 | floodFill(vs,n,m,x-1,y,val,k); 14 | floodFill(vs,n,m,x,y-1,val,k); 15 | } 16 | 17 | int main() 18 | { 19 | //code 20 | int t,n,m,x,y,k,a; 21 | cin >> t; 22 | while(t--){ 23 | cin >> n >> m; 24 | vector>vs; 25 | vectorv; 26 | for(int i=0;i> a; 29 | v.push_back(a); 30 | } 31 | vs.push_back(v); 32 | v.clear(); 33 | } 34 | cin >> x >> y >> k; 35 | int val = vs[x][y]; 36 | 37 | floodFill(vs,n,m,x,y,val,k); 38 | for(int i=0;i 3 | using namespace std; 4 | 5 | 6 | int josephus(int n, int k); 7 | 8 | int main() { 9 | 10 | int t; 11 | cin>>t;//testcases 12 | while(t--) 13 | { 14 | int n,k; 15 | cin>>n>>k;//taking input n and k 16 | 17 | //calling josephus() function 18 | cout< &v,int k,int i){ 26 | if(v.size()==1) 27 | return v[0]; 28 | i=(i+(k-1))%v.size(); 29 | v.erase(v.begin()+i); 30 | 31 | return find_pos(v,k,i); 32 | } 33 | 34 | int josephus(int n, int k){ 35 | vector v; 36 | for(int i=0;i 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | 11 | long long numberOfPaths(int m, int n) 12 | { 13 | // Code Here 14 | if(m==1 || n==1) return 1; 15 | return numberOfPaths(m-1, n) + numberOfPaths(m, n-1); 16 | } 17 | 18 | // { Driver Code Starts. 19 | 20 | 21 | int main() 22 | { 23 | int t; 24 | cin>>t; 25 | while(t--) 26 | { 27 | int n,m; 28 | cin>>m>>n; 29 | cout << numberOfPaths(m, n)< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | // User function Template for C++ 11 | 12 | class Solution{ 13 | public: 14 | unsigned long long int optimalKeys(int N){ 15 | // code here 16 | int n = N; 17 | unsigned long long int dp[n+1]; 18 | for(int i=0; i<=5; i++){ 19 | dp[i] = i; 20 | }for(int j=6; j<=n; j++){ 21 | dp[j] = dp[j-1] + 1; 22 | for(int i=1; i<=j-3; i++){ 23 | dp[j] = max(dp[j], (j-i-1)*dp[i]); 24 | } 25 | } 26 | return dp[n]; 27 | } 28 | }; 29 | 30 | // { Driver Code Starts. 31 | 32 | int main(){ 33 | int t; 34 | cin>>t; 35 | while(t--){ 36 | int N; 37 | cin>>N; 38 | 39 | Solution ob; 40 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | string decodedString(string str){ 13 | // code here 14 | stack ins; 15 | stack ss; 16 | string result = ""; 17 | int i = 0; 18 | while(i < str.length()){ 19 | int k = 0; 20 | if(isdigit(str[i])){ 21 | while(i < str.length() && isdigit(str[i])){ 22 | k = k*10 + str[i] - '0'; 23 | i++; 24 | } 25 | ins.push(k); 26 | }else if(str[i] == ']'){ 27 | string s = ss.top(); 28 | ss.pop(); 29 | int n = ins.top(); 30 | ins.pop(); 31 | for(int i=0; i>t; 54 | while(t--){ 55 | string s; 56 | cin>>s; 57 | 58 | Solution ob; 59 | cout< 3 | using namespace std; 4 | class _stack{ 5 | stack s; 6 | int minEle; 7 | public : 8 | int getMin(); 9 | int pop(); 10 | void push(int); 11 | }; 12 | 13 | 14 | int main() 15 | { 16 | int t; 17 | cin>>t; 18 | while(t--) 19 | { 20 | int q; 21 | cin>>q; 22 | _stack *a = new _stack(); 23 | while(q--){ 24 | 25 | int qt; 26 | cin>>qt; 27 | 28 | if(qt==1) 29 | { 30 | //push 31 | int att; 32 | cin>>att; 33 | a->push(att); 34 | } 35 | else if(qt==2) 36 | { 37 | //pop 38 | cout<pop()<<" "; 39 | } 40 | else if(qt==3) 41 | { 42 | //getMin 43 | cout<getMin()<<" "; 44 | } 45 | } 46 | cout< s; 59 | int minEle; 60 | public : 61 | int getMin(); 62 | int pop(); 63 | void push(int); 64 | }; 65 | */ 66 | 67 | /*returns min element from stack*/ 68 | int _stack :: getMin() 69 | { 70 | //Your code here 71 | if(s.size() <= 0){ 72 | return -1; 73 | } 74 | return minEle; 75 | } 76 | 77 | /*returns poped element from stack*/ 78 | int _stack ::pop() 79 | { 80 | //Your code here 81 | if(s.size() <= 0){ 82 | return -1; 83 | } 84 | if(s.top() >= minEle){ 85 | int a= s.top(); 86 | s.pop(); 87 | return a; 88 | }else{ 89 | int a = s.top(); 90 | int b = minEle; 91 | minEle = 2*minEle - a; 92 | s.pop(); 93 | return b; 94 | } 95 | } 96 | 97 | /*push element x into the stack*/ 98 | void _stack::push(int x) 99 | { 100 | //Your code here 101 | if(s.size() == 0){ 102 | minEle = x; 103 | s.push(x); 104 | }else if(x < minEle){ 105 | s.push(2*x - minEle); 106 | minEle = x; 107 | }else{ 108 | s.push(x); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /stack and queue/QueueUsingTwoStack.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | class StackQueue{ 7 | private: 8 | stack s1; 9 | stack s2; 10 | public: 11 | void push(int B); 12 | int pop(); 13 | 14 | }; 15 | int main() 16 | { 17 | 18 | int T; 19 | cin>>T; 20 | while(T--) 21 | { 22 | StackQueue *sq = new StackQueue(); 23 | 24 | int Q; 25 | cin>>Q; 26 | while(Q--){ 27 | int QueryType=0; 28 | cin>>QueryType; 29 | if(QueryType==1) 30 | { 31 | int a; 32 | cin>>a; 33 | sq->push(a); 34 | }else if(QueryType==2){ 35 | cout<pop()<<" "; 36 | 37 | } 38 | } 39 | cout< s1; 52 | stack s2; 53 | public: 54 | void push(int); 55 | int pop(); 56 | }; */ 57 | 58 | /* The method push to push element into the queue */ 59 | void StackQueue :: push(int x) 60 | { 61 | // Your Code 62 | s1.push(x); 63 | } 64 | 65 | /*The method pop which return the element poped out of the queue*/ 66 | int StackQueue :: pop() 67 | { 68 | // Your Code 69 | if(s1.size() <= 0){ 70 | return -1; 71 | } 72 | int n = s1.size(); 73 | for(int i=0; i 3 | using namespace std; 4 | 5 | class QueueStack{ 6 | private: 7 | queue q1; 8 | queue q2; 9 | public: 10 | void push(int); 11 | int pop(); 12 | }; 13 | 14 | 15 | int main() 16 | { 17 | int T; 18 | cin>>T; 19 | while(T--) 20 | { 21 | QueueStack *qs = new QueueStack(); 22 | 23 | int Q; 24 | cin>>Q; 25 | while(Q--){ 26 | int QueryType=0; 27 | cin>>QueryType; 28 | if(QueryType==1) 29 | { 30 | int a; 31 | cin>>a; 32 | qs->push(a); 33 | }else if(QueryType==2){ 34 | cout<pop()<<" "; 35 | 36 | } 37 | } 38 | cout< q1; 48 | queue q2; 49 | public: 50 | void push(int); 51 | int pop(); 52 | }; 53 | */ 54 | 55 | /* The method push to push element into the stack */ 56 | void QueueStack :: push(int x) 57 | { 58 | // Your Code 59 | q1.push(x); 60 | } 61 | 62 | /*The method pop which return the element poped out of the stack*/ 63 | int QueueStack :: pop() 64 | { 65 | // Your Code 66 | if(q1.size() == 0){ 67 | return -1; 68 | } 69 | int m = q1.size() - 1; 70 | for(int i=0; i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to return if the paranthesis are balanced or not 10 | bool ispar(string x) 11 | { 12 | // Your code here 13 | stack st; 14 | int result = 1; 15 | for(int i=0; i>t; 61 | while(t--) 62 | { 63 | cin>>a; 64 | if(ispar(a)) 65 | cout<<"balanced"< 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | /* Function to check if two strings are anagram 10 | * a, b: input string 11 | */ 12 | bool isAnagram(string a, string b){ 13 | // Your code here 14 | if(a.size() != b.size()){ 15 | return false; 16 | } 17 | sort(a.begin(), a.end()); 18 | sort(b.begin(), b.end()); 19 | for(int i=0; i m1; 25 | // map m2; 26 | // for(int i=0; i> t; 51 | 52 | while(t--){ 53 | string c, d; 54 | 55 | cin >> c >> d; 56 | 57 | if(isAnagram(c, d)) cout << "YES" << endl; 58 | else cout << "NO" << endl; 59 | } 60 | 61 | } 62 | // } Driver Code Ends -------------------------------------------------------------------------------- /string/FormPalindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int lcs(string s, int x){ 5 | string t = s; 6 | reverse(t.begin(), t.end()); 7 | int y = t.length(); 8 | int dp[x+1][y+1]; 9 | for(int i=0;i<=x;i++) 10 | dp[i][0] = 0; 11 | for(int j=0;j<=y;j++) 12 | dp[0][j] = 0; 13 | for(int i=1;i<=x;i++){ 14 | for(int j=1;j<=y;j++){ 15 | if(s[i-1] == t[j-1]) 16 | dp[i][j] = dp[i-1][j-1] + 1; 17 | else 18 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 19 | } 20 | } 21 | return dp[x][y]; 22 | } 23 | 24 | int minInsertions(string s, int n){ 25 | int x = lcs(s, n); 26 | return n-x; 27 | } 28 | 29 | int main() { 30 | int t; 31 | cin>>t; 32 | while(t--){ 33 | string s; 34 | cin>>s; 35 | int n = s.length(); 36 | cout< 3 | using namespace std; 4 | 5 | int atoi(string str); 6 | int main() 7 | { 8 | int t; 9 | cin>>t; 10 | while(t--) 11 | { 12 | string s; 13 | cin>>s; 14 | cout<= '0' && str[i] <= '9'){ 30 | ans = ans*10 + (str[i++] - '0'); 31 | }else{ 32 | return -1; 33 | } 34 | } 35 | return ans*flag; 36 | } -------------------------------------------------------------------------------- /string/ImplementStrstr.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | int strstr(string ,string); 6 | 7 | int main() 8 | { 9 | int t; 10 | cin>>t; 11 | while(t--) 12 | { 13 | string a; 14 | string b; 15 | 16 | cin>>a; 17 | cin>>b; 18 | 19 | cout< 2 | using namespace std; 3 | 4 | string longestCommonPrefix(vector& prefix, string min_string, int n){ 5 | string ans = ""; 6 | for(int i=0; i> t; 22 | while(t--){ 23 | int n; 24 | cin >> n; 25 | vector prefix(n); 26 | int min_length = INT_MAX; 27 | string min_string; 28 | for(int i=0; i> prefix[i]; 30 | if(prefix[i].length() < min_length){ 31 | min_string = prefix[i]; 32 | min_length = prefix[i].length(); 33 | } 34 | } 35 | string result = longestCommonPrefix(prefix, min_string, n); 36 | if(result.empty()) cout << -1 << endl; 37 | else cout << result << endl; 38 | 39 | } 40 | return 0; 41 | } -------------------------------------------------------------------------------- /string/LongestCommonPrefixInArray.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | 9 | class Solution{ 10 | public: 11 | 12 | string longestCommonPrefix (string arr[], int N) 13 | { 14 | // your code here 15 | int min = INT_MAX; 16 | for(int i=0; i> t; 48 | while (t--) 49 | { 50 | int n; cin >> n; 51 | string arr[n]; 52 | for (int i = 0; i < n; ++i) 53 | cin >> arr[i]; 54 | 55 | Solution ob; 56 | cout << ob.longestCommonPrefix (arr, n) << endl; 57 | } 58 | } 59 | 60 | // Contributed By: Pranay Bansal 61 | // } Driver Code Ends -------------------------------------------------------------------------------- /string/LongestDistinctCharacter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | //code 5 | int t; 6 | cin >> t; 7 | while(t--){ 8 | string s; 9 | cin >> s; 10 | int n = s.size(); 11 | if(s.size()==0){ 12 | return 0; 13 | } 14 | int i=0, j=0; 15 | vector cnt(326, 0); 16 | cnt[s[0]]++; 17 | int ans=1; 18 | while(1){ 19 | if(j==n-1) break; 20 | if(cnt[s[j+1]] == 0) j++, cnt[s[j]]++, ans=max(ans,j-i+1); 21 | else { 22 | cnt[s[i++]]--; 23 | } 24 | } 25 | cout << ans << endl; 26 | } 27 | return 0; 28 | } -------------------------------------------------------------------------------- /string/PermutationOfString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | //code 6 | int t; 7 | cin >> t; 8 | while(t--){ 9 | string str; 10 | cin >> str; 11 | sort(str.begin(), str.end()); 12 | do{ 13 | cout << str << " "; 14 | }while(next_permutation(str.begin(), str.end())); 15 | cout << endl; 16 | } 17 | return 0; 18 | } -------------------------------------------------------------------------------- /string/RemoveDuplicates.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | //User function template for C++ 10 | class Solution{ 11 | public: 12 | 13 | string removeDups(string S) 14 | { 15 | // Your code goes here 16 | map m; 17 | string ans; 18 | for(int i=0; i> t; 41 | while(t--) 42 | { 43 | string s; 44 | cin >> s; 45 | 46 | 47 | Solution ob; 48 | cout << ob.removeDups(s) << "\n"; 49 | 50 | } 51 | 52 | return 0; 53 | } // } Driver Code Ends -------------------------------------------------------------------------------- /string/ReverseWordInString.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | string reverseWords(string s); 5 | int main() 6 | { 7 | int t; 8 | cin >> t; 9 | while (t--) 10 | { 11 | string s; 12 | cin >> s; 13 | cout< 6 | using namespace std; 7 | 8 | // Returns decimal value of roman numaral 9 | int romanToDecimal(string &); 10 | 11 | int main() { 12 | int t; 13 | cin >> t; 14 | while (t--) { 15 | string s; 16 | cin >> s; 17 | cout << romanToDecimal(s) << endl; 18 | } 19 | }// } Driver Code Ends 20 | 21 | 22 | // User fuunction teemplate for C++ 23 | 24 | // str given roman number string 25 | // Returns decimal value of roman numaral 26 | int romanToDecimal(string &str) { 27 | // code here 28 | if(!str.size()){ 29 | return 0; 30 | } 31 | map m; 32 | m.insert(pair('I', 1)); 33 | m.insert(pair('V', 5)); 34 | m.insert(pair('X', 10)); 35 | m.insert(pair('L', 50)); 36 | m.insert(pair('C', 100)); 37 | m.insert(pair('D', 500)); 38 | m.insert(pair('M', 1000)); 39 | int ans = 0, p = 0; 40 | for(int i=0; i m[str[i-1]] && (i-1 >= 0)){ 42 | ans += (m[str[i]] - 2*m[str[i-1]]); 43 | }else{ 44 | ans += m[str[i]]; 45 | } 46 | } 47 | return ans; 48 | } -------------------------------------------------------------------------------- /string/RotateStringByTwoPlace.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | /* Function to check if str1 can be formed from 10 | * str2 after rotation by 2 places 11 | */ 12 | bool isRotated(string str1, string str2) 13 | { 14 | // Your code here 15 | int l1=str1.length(), l2=str2.length(), f=0; 16 | if(l1==1 && l2==1){ 17 | if(str1==str2){ 18 | f=1; 19 | } 20 | } 21 | string left = str2, right=str2; 22 | 23 | rotate(left.begin(), left.begin()+2, left.end()); 24 | rotate(right.begin(), right.end()-2, right.end()); 25 | 26 | if(left==str1 || right==str1 ||f==1) return 1; 27 | else return 0; 28 | } 29 | 30 | 31 | // { Driver Code Starts. 32 | 33 | int main() { 34 | 35 | int t; 36 | cin>>t; 37 | while(t--) 38 | { 39 | string s; 40 | string b; 41 | cin>>s>>b; 42 | cout< 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *left; 9 | struct Node *right; 10 | }; 11 | Node* newNode(int val) 12 | { 13 | Node* temp = new Node; 14 | temp->data = val; 15 | temp->left = NULL; 16 | temp->right = NULL; 17 | 18 | return temp; 19 | } 20 | Node* buildTree(string str) 21 | { 22 | // Corner Case 23 | if(str.length() == 0 || str[0] == 'N') 24 | return NULL; 25 | 26 | // Creating vector of strings from input 27 | // string after spliting by space 28 | vector ip; 29 | 30 | istringstream iss(str); 31 | for(string str; iss >> str; ) 32 | ip.push_back(str); 33 | 34 | // Create the root of the tree 35 | Node* root = newNode(stoi(ip[0])); 36 | 37 | // Push the root to the queue 38 | queue queue; 39 | queue.push(root); 40 | 41 | // Starting from the second element 42 | int i = 1; 43 | while(!queue.empty() && i < ip.size()) { 44 | 45 | // Get and remove the front of the queue 46 | Node* currNode = queue.front(); 47 | queue.pop(); 48 | 49 | // Get the current node's value from the string 50 | string currVal = ip[i]; 51 | 52 | // If the left child is not null 53 | if(currVal != "N") { 54 | 55 | // Create the left child for the current node 56 | currNode->left = newNode(stoi(currVal)); 57 | 58 | // Push it to the queue 59 | queue.push(currNode->left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.size()) 65 | break; 66 | currVal = ip[i]; 67 | 68 | // If the right child is not null 69 | if(currVal != "N") { 70 | 71 | // Create the right child for the current node 72 | currNode->right = newNode(stoi(currVal)); 73 | 74 | // Push it to the queue 75 | queue.push(currNode->right); 76 | } 77 | i++; 78 | } 79 | 80 | return root; 81 | } 82 | int countLeaves(struct Node* root); 83 | 84 | int main() 85 | { 86 | int t; 87 | scanf("%d ",&t); 88 | while(t--) 89 | { 90 | string s; 91 | getline(cin,s); 92 | Node* root = buildTree(s); 93 | cout<< countLeaves(root)< q; 123 | int ans = 0; 124 | int count = 0; 125 | q.push(root); 126 | while(!q.empty()){ 127 | count = q.size(); 128 | while(count--){ 129 | Node* temp = q.front(); 130 | q.pop(); 131 | if(!temp->left && !temp->right){ 132 | ans++; 133 | }if(temp->left){ 134 | q.push(temp->left); 135 | }if(temp->right){ 136 | q.push(temp->right); 137 | } 138 | } 139 | } 140 | return ans; 141 | } 142 | -------------------------------------------------------------------------------- /tree and bst/HeightOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | struct Node 8 | { 9 | int data; 10 | struct Node *left; 11 | struct Node *right; 12 | 13 | Node(int val) { 14 | data = val; 15 | left = right = NULL; 16 | } 17 | }; 18 | 19 | // Function to Build Tree 20 | Node* buildTree(string str) 21 | { 22 | // Corner Case 23 | if(str.length() == 0 || str[0] == 'N') 24 | return NULL; 25 | 26 | // Creating vector of strings from input 27 | // string after spliting by space 28 | vector ip; 29 | 30 | istringstream iss(str); 31 | for(string str; iss >> str; ) 32 | ip.push_back(str); 33 | 34 | // Create the root of the tree 35 | Node *root = new Node(stoi(ip[0])); 36 | 37 | // Push the root to the queue 38 | queue queue; 39 | queue.push(root); 40 | 41 | // Starting from the second element 42 | int i = 1; 43 | while(!queue.empty() && i < ip.size()) { 44 | 45 | // Get and remove the front of the queue 46 | Node* currNode = queue.front(); 47 | queue.pop(); 48 | 49 | // Get the current node's value from the string 50 | string currVal = ip[i]; 51 | 52 | // If the left child is not null 53 | if(currVal != "N") { 54 | 55 | // Create the left child for the current Node 56 | currNode->left = new Node(stoi(currVal)); 57 | 58 | // Push it to the queue 59 | queue.push(currNode->left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.size()) 65 | break; 66 | currVal = ip[i]; 67 | 68 | // If the right child is not null 69 | if(currVal != "N") { 70 | 71 | // Create the right child for the current node 72 | currNode->right = new Node(stoi(currVal)); 73 | 74 | // Push it to the queue 75 | queue.push(currNode->right); 76 | } 77 | i++; 78 | } 79 | 80 | return root; 81 | } 82 | 83 | // } Driver Code Ends 84 | 85 | 86 | //User function template for C++ 87 | 88 | /* 89 | struct Node 90 | { 91 | int data; 92 | struct Node* left; 93 | struct Node* right; 94 | 95 | Node(int x){ 96 | data = x; 97 | left = right = NULL; 98 | } 99 | }; 100 | */ 101 | class Solution{ 102 | public: 103 | int height(struct Node* node){ 104 | // code here 105 | if(!node){ 106 | return 0; 107 | } 108 | queue q; 109 | int ans = 0; 110 | int count = 0; 111 | q.push(node); 112 | while(!q.empty()){ 113 | count = q.size(); 114 | ans++; 115 | while(count--){ 116 | Node* temp = q.front(); 117 | q.pop(); 118 | if(temp->left){ 119 | q.push(temp->left); 120 | }if(temp->right){ 121 | q.push(temp->right); 122 | } 123 | } 124 | } 125 | return ans; 126 | } 127 | }; 128 | 129 | // { Driver Code Starts. 130 | int main() 131 | { 132 | int t; 133 | scanf("%d ",&t); 134 | while(t--) 135 | { 136 | string treeString; 137 | getline(cin,treeString); 138 | Node* root = buildTree(treeString); 139 | Solution ob; 140 | cout< 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | Node *left; 8 | Node *right; 9 | 10 | Node(int val) { 11 | data = val; 12 | left = right = NULL; 13 | } 14 | }; 15 | // Function to Build Tree 16 | Node* buildTree(string str) 17 | { 18 | // Corner Case 19 | if(str.length() == 0 || str[0] == 'N') 20 | return NULL; 21 | 22 | // Creating vector of strings from input 23 | // string after spliting by space 24 | vector ip; 25 | 26 | istringstream iss(str); 27 | for(string str; iss >> str; ) 28 | ip.push_back(str); 29 | 30 | // Create the root of the tree 31 | Node* root = new Node(stoi(ip[0])); 32 | 33 | // Push the root to the queue 34 | queue queue; 35 | queue.push(root); 36 | 37 | // Starting from the second element 38 | int i = 1; 39 | while(!queue.empty() && i < ip.size()) { 40 | 41 | // Get and remove the front of the queue 42 | Node* currNode = queue.front(); 43 | queue.pop(); 44 | 45 | // Get the current node's value from the string 46 | string currVal = ip[i]; 47 | 48 | // If the left child is not null 49 | if(currVal != "N") { 50 | 51 | // Create the left child for the current node 52 | currNode->left = new Node(stoi(currVal)); 53 | 54 | // Push it to the queue 55 | queue.push(currNode->left); 56 | } 57 | 58 | // For the right child 59 | i++; 60 | if(i >= ip.size()) 61 | break; 62 | currVal = ip[i]; 63 | 64 | // If the right child is not null 65 | if(currVal != "N") { 66 | 67 | // Create the right child for the current node 68 | currNode->right = new Node(stoi(currVal)); 69 | 70 | // Push it to the queue 71 | queue.push(currNode->right); 72 | } 73 | i++; 74 | } 75 | 76 | return root; 77 | } 78 | 79 | Node* LCA(Node * root , int l , int h); 80 | 81 | int main() 82 | { 83 | 84 | int t; 85 | scanf("%d ",&t); 86 | while(t--) 87 | { 88 | string s; 89 | int l , h; 90 | getline(cin,s); 91 | scanf("%d ",&l); 92 | scanf("%d ",&h); 93 | Node* root = buildTree(s); 94 | cout<data<data == n1 || root->data == n2){ 123 | return root; 124 | } 125 | Node* l = LCA(root->left, n1, n2); 126 | Node* r = LCA(root->right, n1, n2); 127 | 128 | if(l && r){ 129 | return root; 130 | }else if(l){ 131 | return l; 132 | }else if(r){ 133 | return r; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /tree and bst/MaximumSumBSTBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | int maxs=0; 14 | pair> h(TreeNode* root){ 15 | if(root==NULL){ 16 | return make_pair(0,make_pair(INT_MAX,INT_MIN)); 17 | } 18 | pair> p1=h(root->right); 19 | pair> p2=h(root->left); 20 | if((p1.second.first) > (root->val) && (p2.second.second) < (root->val)){ 21 | maxs = max(root->val + p1.first + p2.first, maxs); 22 | return make_pair(root->val + p1.first + p2.first, make_pair(min((root->val), (p2.second.first)), max((root->val), (p1.second.second)))); 23 | } 24 | return make_pair(max(p1.first, p2.first), make_pair(INT_MIN,INT_MAX)); 25 | } 26 | public: 27 | int maxSumBST(TreeNode* root) { 28 | return max(h(root).first, maxs); 29 | } 30 | }; -------------------------------------------------------------------------------- /tree and bst/RecursivelyRemoveAllAdjacentDuplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int t; 6 | cin>>t; 7 | string s; 8 | 9 | while(t--) 10 | { 11 | cin>>s; 12 | string s2; 13 | 14 | while(1){ 15 | int flg=1; 16 | s2=""; 17 | for(int i=0;i0&&s[i]==s[i-1]){ 21 | flg=0; 22 | 23 | }else{ 24 | s2+=s[i]; 25 | } 26 | } 27 | s=s2; 28 | if(flg==1) 29 | break; 30 | } 31 | cout< 3 | using namespace std; 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 | Node* buildTree(string str) 15 | { 16 | // Corner Case 17 | if(str.length() == 0 || str[0] == 'N') 18 | return NULL; 19 | 20 | // Creating vector of strings from input 21 | // string after spliting by space 22 | vector ip; 23 | 24 | istringstream iss(str); 25 | for(string str; iss >> str; ) 26 | ip.push_back(str); 27 | 28 | // Create the root of the tree 29 | Node* root = new Node(stoi(ip[0])); 30 | 31 | // Push the root to the queue 32 | queue queue; 33 | queue.push(root); 34 | 35 | // Starting from the second element 36 | int i = 1; 37 | while(!queue.empty() && i < ip.size()) { 38 | 39 | // Get and remove the front of the queue 40 | Node* currNode = queue.front(); 41 | queue.pop(); 42 | 43 | // Get the current node's value from the string 44 | string currVal = ip[i]; 45 | 46 | // If the left child is not null 47 | if(currVal != "N") { 48 | 49 | // Create the left child for the current node 50 | currNode->left = new Node(stoi(currVal)); 51 | 52 | // Push it to the queue 53 | queue.push(currNode->left); 54 | } 55 | 56 | // For the right child 57 | i++; 58 | if(i >= ip.size()) 59 | break; 60 | currVal = ip[i]; 61 | 62 | // If the right child is not null 63 | if(currVal != "N") { 64 | 65 | // Create the right child for the current node 66 | currNode->right = new Node(stoi(currVal)); 67 | 68 | // Push it to the queue 69 | queue.push(currNode->right); 70 | } 71 | i++; 72 | } 73 | 74 | return root; 75 | } 76 | bool isSymmetric(struct Node* root); 77 | 78 | int main() 79 | { 80 | int t; 81 | scanf("%d ",&t); 82 | while(t--) 83 | { 84 | string s; 85 | getline(cin,s); 86 | Node* root = buildTree(s); 87 | if(isSymmetric(root)) 88 | cout<<"True"<data == r->data){ 119 | return comp(l->left, r->right) && comp(l->right, r->left); 120 | }else{ 121 | return false; 122 | } 123 | 124 | } 125 | bool isSymmetric(struct Node* root) 126 | { 127 | // Code here 128 | if(!root){ 129 | return true; 130 | } 131 | if(root->right && root->left){ 132 | return comp(root->left, root->right); 133 | }else if(root->right || root->left){ 134 | return false; 135 | }else{ 136 | return true; 137 | } 138 | 139 | } -------------------------------------------------------------------------------- /tree and bst/check_for_bst.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | #define MAX_HEIGHT 100000 5 | 6 | // Tree Node 7 | struct Node { 8 | int data; 9 | Node *left; 10 | Node *right; 11 | 12 | Node(int val) { 13 | data = val; 14 | left = right = NULL; 15 | } 16 | }; 17 | 18 | 19 | 20 | bool isBST(struct Node* node); 21 | int isBSTUtil(struct Node* node, int min, int max); 22 | 23 | // Function to Build Tree 24 | Node* buildTree(string str) 25 | { 26 | // Corner Case 27 | if(str.length() == 0 || str[0] == 'N') 28 | return NULL; 29 | 30 | // Creating vector of strings from input 31 | // string after spliting by space 32 | vector ip; 33 | 34 | istringstream iss(str); 35 | for(string str; iss >> str; ) 36 | ip.push_back(str); 37 | 38 | // Create the root of the tree 39 | Node* root = new Node(stoi(ip[0])); 40 | 41 | // Push the root to the queue 42 | queue queue; 43 | queue.push(root); 44 | 45 | // Starting from the second element 46 | int i = 1; 47 | while(!queue.empty() && i < ip.size()) { 48 | 49 | // Get and remove the front of the queue 50 | Node* currNode = queue.front(); 51 | queue.pop(); 52 | 53 | // Get the current node's value from the string 54 | string currVal = ip[i]; 55 | 56 | // If the left child is not null 57 | if(currVal != "N") { 58 | 59 | // Create the left child for the current node 60 | currNode->left = new Node(stoi(currVal)); 61 | 62 | // Push it to the queue 63 | queue.push(currNode->left); 64 | } 65 | 66 | // For the right child 67 | i++; 68 | if(i >= ip.size()) 69 | break; 70 | currVal = ip[i]; 71 | 72 | // If the right child is not null 73 | if(currVal != "N") { 74 | 75 | // Create the right child for the current node 76 | currNode->right = new Node(stoi(currVal)); 77 | 78 | // Push it to the queue 79 | queue.push(currNode->right); 80 | } 81 | i++; 82 | } 83 | 84 | return root; 85 | } 86 | 87 | void inorder(Node *root, vector &v) 88 | { 89 | if(root==NULL) 90 | return; 91 | 92 | inorder(root->left, v); 93 | v.push_back(root->data); 94 | inorder(root->right, v); 95 | } 96 | 97 | int main() { 98 | 99 | int t; 100 | string tc; 101 | getline(cin, tc); 102 | t=stoi(tc); 103 | while(t--) 104 | { 105 | string s; 106 | getline(cin, s); 107 | Node* root = buildTree(s); 108 | cout << isBST(root) << endl; 109 | } 110 | return 0; 111 | } 112 | 113 | 114 | 115 | // } Driver Code Ends 116 | 117 | 118 | /* A binary tree node has data, pointer to left child 119 | and a pointer to right child 120 | struct Node { 121 | int data; 122 | Node *left; 123 | Node *right; 124 | 125 | Node(int val) { 126 | data = val; 127 | left = right = NULL; 128 | } 129 | }; 130 | */ 131 | 132 | // return true if the given tree is a BST, else return false 133 | bool isBST(Node* root) { 134 | // Your code here 135 | vector v; 136 | inorder(root, v); 137 | 138 | int ans = 1; 139 | for(int i=1; i= v[i]){ 141 | ans = 0; 142 | break; 143 | } 144 | } 145 | if(ans == 0){ 146 | return 0; 147 | }else{ 148 | return 1; 149 | } 150 | 151 | } --------------------------------------------------------------------------------