├── AlgorithmCPP └── Brian_Kernighan’s_algorithm.cpp ├── Algorithms ├── BFS_Algorithm.cpp ├── Backtracking ├── Bellman-Ford-Algorithm.cpp ├── CPU Scheduling │ ├── RoundRobinScheduling.cpp │ ├── first-come-first-serve-with-diff-arrival-time_C++.cpp │ ├── first-come-first-serve_C++.cpp │ ├── priority-scheduling_C++.cpp │ └── shortest-job-first_C++.cpp ├── DFS_Algorithm.cpp ├── Dynamic Programming │ ├── Coin_Exchange.cpp │ ├── Gold_Mine.cpp │ ├── Subset_Sum.cpp │ └── TrappingRainWater.java ├── Eculidean-Algorithm.cpp ├── Floyd-Warshall-Algorithm.cpp ├── Graphics │ ├── Bresenhams-Line_C.C │ └── Liang-Barsky_C.C ├── Graphs │ ├── Dijkstra-Algorithm.cpp │ ├── Rat_in_a_Maze.cpp │ └── dijkstraProb.cpp ├── Kadanes-Algorithm.cpp ├── Matrix Multiplication ├── N-queen-problem_c++.cpp ├── README.md ├── Searching │ ├── Binary-search.cpp │ ├── Binary_Search_recc.cpp │ ├── Jump-Search.cpp │ ├── Linear-search.cpp │ ├── Quick_Sort_Rec.cpp │ └── interpolation_search.cpp ├── Shortest_path_backtracking_c++.cpp ├── Sorting │ ├── Bubble Sort using Recursion.cpp │ ├── Bubble-sort.cpp │ ├── Counting-Sort.cpp │ ├── Heap_sortc++.cpp │ ├── Insertion-sort.cpp │ ├── Merge_sort.cpp │ ├── Merge_sort_recc.cpp │ ├── Quick Sort.cpp │ ├── Quick-sort.cpp │ ├── Radix-sort.cpp │ ├── Selection Sort using Recursion.cpp │ ├── Selection-sort.cpp │ ├── Wave-Sort.cpp │ ├── bucket_sort.cpp │ ├── comb-sort.cpp │ ├── counting_sort.cpp │ └── template-sorting-c++.cpp ├── StackUsingLL.cpp ├── String-Algorithm.cpp ├── kadane's.py ├── mergeSort.c ├── optimal_merge_pattern.cpp └── prims_algorithm.cpp ├── Bit-tricks ├── Addition-without-arithmetic_C++.cpp ├── Odd-occuring_C++.cpp └── Swapping-two-no_C++.cpp ├── Bitwise-Hacks ├── Codeforces_1421A_XORwice.cpp └── bits.cpp ├── CSES-Solutions ├── Company Queries 1.cpp ├── Company Queries II.cpp ├── Distance Queries.cpp ├── Distinct Colors.cpp ├── Increasing-Array.cpp ├── Missing-Number.cpp ├── Number-Spiral.cpp ├── Path Queries.cpp ├── Repetitions.cpp ├── Subordinates.cpp ├── Subtree Queries.cpp ├── Trailing Zeros.cpp ├── Tree Distances I ├── Tree Distances II.cpp ├── TreeDiameter.cpp └── Weird-Algorithm.cpp ├── Complexity_Cheatsheet.pdf ├── Contest ├── Codechef │ ├── Codechef-Sep-Cookoff-Div2 │ │ ├── Codechef-sep-coofoff-1.cpp │ │ └── Codechef-sep-coofoff-2.cpp │ └── Codechef-Sep-Lunchtime-Div2 │ │ ├── Codechef-lunchtime-div2-1.cpp │ │ ├── FLIPCARDS_LTIME112C │ │ └── Ltime112b-Incadd └── Codeforces │ ├── Codeforces-605-Div3 │ └── Codeforces-605-div3-D.cpp │ ├── Codeforces-613-Div2 │ └── Codeforces-613-div2-C.cpp │ ├── Codeforces-633-Div1 │ └── Codeforces-633-div1-A.cpp │ ├── Codeforces-670-Div2 │ └── Codeforces-670-div2-A.cpp │ ├── Codeforces-82-Div2 │ └── Codeforces-82-div2-B.cpp │ └── Codeforces-TestingRound-16 │ └── Codeforces-16-Div2.cpp ├── Data-structures-in-Kotlin ├── LinkedList.kt ├── Node.kt ├── Queue.kt ├── Stack.kt └── main.kt ├── Data-structures ├── Arrays │ ├── ArrayOperations.cpp │ ├── DynamicAllocation2DArrays.cpp │ ├── Find-n-unique-integers-sum-up-to-zero.cpp │ ├── Median_of_two_sorted_arrays_of_different_sizes.cpp │ ├── ReverseArray.cpp │ └── removingDuplicates.cpp ├── Binary_Search.cpp ├── Graphs │ └── Graphsvs.java ├── Linked_List.cpp ├── List │ ├── Linkedlist.cpp │ ├── doublyll.cpp │ └── phone directory.cpp ├── Queue │ ├── Circular Queue Using Circular Linked List │ ├── Circular_Queue.cpp │ ├── Deque.cpp │ ├── Queue-using-linked-list.cpp │ └── Queue.cpp ├── README.md ├── Stack │ ├── Stack.cpp │ ├── Stack_using_2_queues.cpp │ ├── Stack_v2.cpp │ ├── balanced_parenthesis_stack.cpp │ ├── implementation_of_stack_using_two_queues.cpp │ └── stack_operations.cpp ├── TRIE │ ├── StreamOfCharactersLeetCode_Java.java │ ├── Tclient_Java.java │ └── TrieCode_Java.java ├── Threaded binary tree example.cpp ├── Tree │ ├── 226-invert-binary-tree.cpp │ ├── Binary-tree-traversal.cpp │ ├── LCA-of-Binary-Tree.cpp │ └── heap_sort.cpp ├── bst_operations.cpp ├── morris.cpp ├── no_of_provinces.cpp ├── nqueen_rec2.cpp ├── ser_der.cpp ├── sud_rec3.cpp └── vertical_trav.cpp ├── Games └── Tic_tac_toe.py ├── HackerRank-Solutions ├── Algorithms │ ├── Dynamic-programming │ │ ├── Fibonacci-modified.java │ │ └── Maximum-subarray.java │ ├── Greedy │ │ └── Priyanka-and-toys.java │ └── Search │ │ └── Ice-cream-parlor.java ├── Arrays │ └── Big-sorting.java └── Practice Problems │ ├── Athlete Sort.py │ ├── any_or_all.py │ ├── arrays.py │ └── maximize_it.py ├── Important-Interview-Questions ├── Stack-balanced-paranthesis.cpp ├── Unique-number-from-pairs-by-XOR.cpp └── max_occurrences.cpp ├── Insertion Sort ├── Insertion Sort.cbp ├── Insertion Sort.depend ├── Insertion Sort.layout ├── bin │ └── Debug │ │ └── Insertion Sort.exe ├── main.cpp └── obj │ └── Debug │ └── main.o ├── InterviewBit-Solutions └── Heaps │ ├── Distinct-numbers-in-window.cpp │ ├── LRU-cache.cpp │ ├── Merge-K-sorted-lists.cpp │ └── N-max-pair-combinations.cpp ├── LICENSE ├── Leetcode-Solutions ├── Arrays │ ├── Best-time-to-buy-and-sell-stock.java │ ├── Cells-with-odd-values-in-a-matrix.cpp │ ├── Kids-with-the-greatest-number-of-candies.cpp │ ├── Largest-rectangle-in-histogram.java │ ├── Longest Valid Parentheses.cpp │ ├── Majority-Element.java │ ├── Maximum-Subarray.py │ ├── Maximum-product-subarray.java │ ├── Median_of_two_sorted_arrays.py │ ├── Minimum-Number-of-Arrows-to-Burst-Balloons.java │ ├── Minimum-time-visiting-all-points.cpp │ ├── Regular Expression Matching.cpp │ ├── Remove covered intervals.cpp │ ├── Roman-to-Integer.cpp │ ├── Rotate-image.java │ ├── Subarray-sum-equals-k.java │ ├── TrappingRainwater.java │ ├── TwoSum.py │ ├── TwoSumProb.cpp │ ├── find_first_and_last_position_of_element_in_sorted_array.py │ ├── majority_element.py │ └── minimum-time-to-make-rope-colorful.py ├── DP │ ├── 10-Regular-Expression-Matching.cpp │ ├── 118-Pascal-triangle.cpp │ ├── 32-Longest-valid-parantheses.cpp │ ├── 5-Longest-Palindromic-Substring.cpp │ ├── 72-Edit-Distance.cpp │ ├── Coin_Change_DP.cpp │ ├── HOUSE ROBBER PROBLEM II AND III.cpp │ ├── climbing_stairs.py │ ├── house_robber.cpp │ ├── number-of-dice-rolls-with-target-sum.py │ └── ugly-Number-II.java ├── Graph │ ├── Biparte.cpp │ ├── CourseI.cpp │ ├── RottenOranges.cpp │ ├── Routes.cpp │ ├── Sliding.cpp │ └── ladder.cpp ├── Greedy │ ├── Find Valid Matrix Given Row and Column Sums.cpp │ ├── Minimum Add to Make Parentheses Valid.cpp │ ├── Reduce Array Size to The Half.cpp │ └── Split-a-string-in-balanced-strings.cpp ├── Linked-List │ ├── 141-Linked-List-Cycle.cpp │ ├── 19-Remove-Nth-Node-From-End-of-List.cpp │ ├── 206-Reverse-Linked-List.cpp │ ├── 21-Merge-Two-Sorted-Lists.cpp │ ├── 237-Delete-Node-in-a-Linked-List.cpp │ ├── 24-Swap-Nodes-in-Pairs.cpp │ ├── 61-Rotate-List.cpp │ ├── 83-Remove-Duplicates-from-Sorted-List.cpp │ ├── 86-Partition-List.cpp │ ├── 876-Middle-of-the-Linked-List.cpp │ ├── Copy-List-With-Random-Pointer.cpp │ ├── Linked-List-Cycle-II.cpp │ ├── Merge-Sorted-Lists_C++.cpp │ ├── Odd-Even-Linked-List.cpp │ ├── Palindrome-Linked-List.cpp │ ├── Remove_Linked_List_Elements.cpp │ ├── Reorder-List.cpp │ ├── intersection-of-two-linked-lists_C++.cpp │ ├── linked-list-cycle_C++.cpp │ └── palindrome-linked-list.cpp ├── LinkedList │ ├── CopyListWithRandomPointers1_Java.java │ ├── CopyListWithRandomPointers2_Java.java │ ├── FlattenMultilevelLinklist.java │ ├── IntersectionOfTwoLinkedLists.java │ ├── LRUCache.java │ ├── MergeKSortedLists_Java.java │ ├── OddEvenLinkedLists_Java.java │ ├── RemoveDuplicatesFromSortedList_Java.java │ ├── RemoveNthNodeFromEndOfList_Java.java │ ├── ReorderList_Java.java │ ├── ReorderORfold.java │ ├── ReverseLinkedList2.java │ ├── ReverseNodesInK-Groups_Java.java │ └── RotateLinkedLists.java ├── Matrix │ ├── Rotate each ring of matrix anticlockwise by K elements.cpp │ └── spiral-matrix.cpp ├── Queue │ ├── 622-Design-Circular-Queue.cpp │ └── 641-Design-Circular-Deque.cpp ├── Strings │ ├── Defanging-an-ip-address.cpp │ ├── Detect-Capital.java │ ├── Detect-Captital.cpp │ ├── Longest_Substring_Length.cpp │ ├── Remove-Duplicate-Characters.java │ ├── To-lower-case_C ++.cpp │ ├── Valid-Palindrome.cpp │ ├── longestCommonPrefix.java │ ├── longest_palindromic_substring.py │ ├── maxOccurrence.cpp │ ├── romantointeger.py │ ├── split-array-into-fibonacci-sequence_java.java │ └── subsequence.cpp └── Tree │ ├── 257-binary-tree-paths.cpp │ ├── 96-Unique-Binary-Search-Trees.cpp │ ├── Path-Sum3.cpp │ ├── Path_Sum3.cpp │ ├── Serialize-deserialize-binary-tree.java │ ├── Vertical-Order-traversal.cpp │ ├── all-nodes-distance-k-in-binary-tree.java │ └── equal-tree-partition.java ├── Logarithmic-tricks ├── Count-digits-of-number.cpp └── Power-of-two.cpp ├── Longest Subsequence from a numeric String divisible by K ├── Pepcoding-level-1-list ├── GettingStarted │ ├── Countdigitsinanumber.cpp │ ├── Digits-of-a-number.cpp │ ├── Inverse-a-number.cpp │ ├── Prime-factorization-of-a-number.cpp │ ├── PrintAllPrimesTillN.cpp │ ├── PrintFabonacciNumbersTillN.cpp │ ├── Pythagorean-triplet.cpp │ ├── Reverse-number.cpp │ ├── Rotate-a-number.cpp │ ├── The-curious-case-of-benjamin-bulbs.cpp │ ├── gcd-and-lcm.cpp │ └── printZ.cpp └── Stack-and-queues │ ├── Histogram.cpp │ ├── Infix-conversion.cpp │ ├── Postfix-evaluation-and-conversions.cpp │ ├── Sliding-window.cpp │ └── Stock-span.cpp ├── Practice-codechef-solutions ├── Arrays │ ├── AMR15A.cpp │ ├── ARRPROB.cpp │ ├── CHGM1.cpp │ ├── CPAIRS.cpp │ ├── CSUM.cpp │ ├── FLOW017 .cpp │ ├── MARM.cpp │ ├── POGOSTCK.cpp │ ├── ReplaceforX.cpp │ ├── SNTEMPLE.cpp │ ├── STRLS1.cpp │ ├── TLG.cpp │ └── TWTCLOSE.cpp ├── Codechef Problem-Covid_Pandemic_and_Long_Queue.cpp └── Math │ ├── BITOBYT.java │ ├── CARVANS.cpp │ ├── CHOPRT.cpp │ ├── CHSERVE.cpp │ ├── FLOW008 .cpp │ ├── FLOW013.cpp │ ├── FLOW018 .cpp │ ├── HMAPPY2.cpp │ ├── ICL1902.cpp │ ├── MUFFINS3.cpp │ └── REMISS .cpp ├── Python-Pygame └── follow_cursor.py ├── README.md ├── Scramble_string_problem.cpp ├── Willam fiset DSA c++ translated code ├── Arrays │ ├── Array.cpp │ └── GenericArray.cpp ├── Balanced Binary Search Tree │ └── AVL Tree │ │ └── AvlTreeRecursive.cpp ├── Binary Search Tree │ └── bst.cpp ├── Fenwick Tree │ ├── FenwickTreeRangeQueryPointUpdate.cpp │ └── FenwickTreeRangeUpdatePointQuery.cpp ├── Hash Table │ ├── HashTableSeperateChaining.cpp │ ├── OpenAdressingDoubleHashing.cpp │ ├── OpenAdressingLinearProbing.cpp │ └── OpenAdressingQuadraticProbing.cpp ├── Linked List │ ├── Doubly_Linked_list.cpp │ └── Single_Linked_List.cpp ├── Priority Queues │ ├── max_heap.cpp │ ├── max_priority_queue.cpp │ ├── min_index_priority_queue.cpp │ ├── min_priority_queue.cpp │ └── min_priority_stack.cpp ├── Queues & Deques │ ├── ArrayQueue.cpp │ ├── Dequeue.cpp │ └── SingleLinkedListQueue.cpp ├── Stack │ ├── ArrayStack.cpp │ └── SingleLinkedListStack.cpp ├── Suffix Array │ ├── SuffixArrayFast.cpp │ ├── SuffixArraySlow.cpp │ └── SuffixArraymed.cpp ├── Tree │ └── tree.cpp ├── Union find │ └── dsu.cpp └── readme.txt ├── atcoder-dp-contest-solutions ├── A-frog.cpp ├── B-frog2.cpp ├── C-vacation.cpp ├── D-knapsack-1.cpp ├── F-lcs.cpp ├── G-longest-path.cpp ├── H-grid-1.cpp ├── I-coins.cpp └── subset_sum_k.cpp ├── hacktober.webp ├── multidimarraydynamicallocation ├── bin │ └── Debug │ │ └── multidimarraydynamicallocation.exe ├── main.cpp ├── multidimarraydynamicallocation.cbp ├── multidimarraydynamicallocation.layout └── obj │ └── Debug │ └── main.o └── standard-template-library ├── Forward-List.cpp ├── Vector.cpp ├── deque.cpp ├── list.cpp ├── priority_queue.cpp ├── queue.cpp ├── set.cpp └── stack.cpp /Algorithms/Backtracking: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Algorithms/CPU Scheduling/first-come-first-serve-with-diff-arrival-time_C++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void wt(int p[], int n, int b[],int w[], int a[]) 4 | { 5 | int s[n]; 6 | s[0] = 0; 7 | w[0] = 0; 8 | 9 | for (int i = 1; i < n ; i++) 10 | { 11 | s[i] = s[i-1] + b[i-1]; 12 | 13 | w[i] = s[i] - a[i]; 14 | 15 | if (w[i] < 0) 16 | w[i] = 0; 17 | } 18 | } 19 | 20 | void tat(int p[], int n, int b[],int w[], int t[]) 21 | { 22 | for (int i = 0; i < n ; i++) 23 | t[i] = b[i] + w[i]; 24 | } 25 | 26 | void avg(int p[], int n, int b[], int a[]) 27 | { 28 | int w[n], t[n]; 29 | 30 | wt(p, n, b, w, a); 31 | 32 | tat(p, n, b, w, t); 33 | 34 | cout << "Process \t\tBurst Time\tArrival Time\tWaiting Time\tTurn-Around Time\tCompletion Time"; 35 | float avg1 = 0, avg2 = 0; 36 | for (int i = 0 ; i < n ; i++) 37 | { 38 | avg1 = avg1 + w[i]; 39 | avg2 = avg2 + t[i]; 40 | int c = t[i] + a[i]; 41 | cout<<"\t\t"< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n,b[20],w[20],a[20],i,j; 8 | float avg1=0,avg2=0; 9 | cout<<"Enter total number of processes: "; 10 | cin>>n; 11 | 12 | cout<<"\nEnter the Burst Time with respective process number\n"; 13 | for(i=0;i>b[i]; 17 | } 18 | 19 | w[0]=0; 20 | 21 | for(i=1;i 2 | using namespace std; 3 | int main() 4 | { 5 | int a[10],b[10],x[10],pr[10]={0}; 6 | int w[10],tat[10],c[10]; 7 | int i,j,s,cnt=0,t,n; 8 | double avg=0,tt=0,e; 9 | cout<<"\nEnter number of processes: "; 10 | cin>>n; 11 | cout<>a[i]; 16 | } 17 | cout<>b[i]; 22 | } 23 | cout<>pr[i]; 28 | } 29 | for(i=0;ipr[s] && b[i]>0 ) 39 | s=i; 40 | } 41 | t=t+b[s]-1; 42 | b[s]=-1; 43 | cnt++; 44 | e=t+1; 45 | c[s] = e; 46 | w[s] = e - a[s] - x[s]; 47 | tat[s] = e - a[s]; 48 | } 49 | cout<<"Process\t\tBurst time\tArrival time\tWaiting time\tTurnaround time\tCompletion time\tPriority"; 50 | for(i=0;i 4 | using namespace std; 5 | 6 | // Graph class represents a directed graph 7 | // using adjacency list representation 8 | class Graph 9 | { 10 | public: 11 | map visited; 12 | map> adj; 13 | 14 | // function to add an edge to graph 15 | void addEdge(int v, int w); 16 | 17 | // DFS traversal of the vertices 18 | // reachable from v 19 | void DFS(int v); 20 | }; 21 | 22 | void Graph::addEdge(int v, int w) 23 | { 24 | adj[v].push_back(w); // Add w to v’s list. 25 | } 26 | 27 | void Graph::DFS(int v) 28 | { 29 | // Mark the current node as visited and 30 | // print it 31 | visited[v] = true; 32 | cout << v << " "; 33 | 34 | // Recur for all the vertices adjacent 35 | // to this vertex 36 | list::iterator i; 37 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 38 | if (!visited[*i]) 39 | DFS(*i); 40 | } 41 | 42 | // Driver code 43 | int main() 44 | { 45 | // Create a graph given in the above diagram 46 | Graph g; 47 | g.addEdge(0, 1); 48 | g.addEdge(0, 2); 49 | g.addEdge(1, 2); 50 | g.addEdge(2, 0); 51 | g.addEdge(2, 3); 52 | g.addEdge(3, 3); 53 | 54 | cout << "Following is Depth First Traversal" 55 | " (starting from vertex 2) \n"; 56 | g.DFS(2); 57 | 58 | return 0; 59 | } 60 | 61 | // improved by Vishnudev C 62 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/Subset_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool subsetSum(int arr[], int n, int sum){ 7 | bool t[n+1][sum+1]; 8 | 9 | for(int i=0; i>sum; 36 | cout<>n; 40 | cout<>arr[i]; 47 | } 48 | 49 | bool ans = obj.subsetSum(arr, n, sum); 50 | string ok = ans == true ? "Yes" : "No"; 51 | cout<<"Answer is: "<= 1; i--) { 21 | right = Integer.max(right, bars[i + 1]); 22 | if (Integer.min(left[i], right) > bars[i]) { 23 | // check if it is possible to store water in the current bar 24 | water += Integer.min(left[i], right) - bars[i]; 25 | } 26 | } 27 | return water; 28 | } 29 | 30 | // Driver method 31 | public static void main(String args[]) { 32 | int[] heights = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; 33 | // print the amount of water trapped 34 | System.out.println("The maximum amount of water that can be trapped is " + 35 | trap(heights)); 36 | } 37 | } -------------------------------------------------------------------------------- /Algorithms/Eculidean-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int gcdFunction(int x, int y) // recursive function 6 | { 7 | if (x == 0) 8 | return y; 9 | else 10 | return gcdFunction(y % x, x); 11 | } 12 | 13 | int gcdFunction2(int x, int y) 14 | { 15 | // Since at the end of the algorithm, the two numbers should be the GCD and 0 16 | // so we can simply return x+y without comparing x and y 17 | while ((x %= y) && (y %= x)); 18 | return x + y; 19 | } 20 | 21 | int main() 22 | { 23 | int x, y; // 2 nos. whose gcd we've to find 24 | x = 228, y = 548; 25 | cout << "GCD of numbers " << x << " and " << y << " is " << gcdFunction(x, y) << endl; 26 | 27 | cout << "Another amazing implementation of GCD : " << gcdFunction2(x, y) << endl; 28 | 29 | return 0; 30 | } 31 | 32 | /* Output 33 | GCD of numbers 228 and 548 is 4 34 | Another amazing implementation of GCD : 4 35 | */ -------------------------------------------------------------------------------- /Algorithms/Floyd-Warshall-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define V 4 5 | #define INF 99999 6 | 7 | void printShortest(int dist[][V]); 8 | 9 | void floydWarshall(int graph[][V]) 10 | { 11 | //dist will store shortest distances between the vertices 12 | int dist[V][V]; 13 | 14 | for(int i=0; i>graph[i][j]; 54 | cout<<"\n"; 55 | } 56 | floydWarshall(graph); 57 | } -------------------------------------------------------------------------------- /Algorithms/Graphics/Bresenhams-Line_C.C: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int sign(int a) 5 | { 6 | if(a>0) 7 | return 1; 8 | else if (a<0) 9 | return -1; 10 | else 11 | return 0; 12 | } 13 | void bresham(int x1,int y1,int x2,int y2) 14 | { 15 | int i,x,dx,y,dy,pk,flag,s1,s2,temp,inc1,inc2; 16 | dx=abs(x2-x1); 17 | dy=abs(y2-y1); 18 | pk=2*dy-dx; 19 | s1=sign(x2-x1); 20 | s2=sign(y2-y1); 21 | if(dx>dy) 22 | { 23 | temp=dx; 24 | dx=dy; 25 | dy=temp; 26 | flag=1; 27 | } 28 | else 29 | flag=0; 30 | 31 | inc1=2*dy; 32 | inc2=2*(dy-dx); 33 | x=x1; 34 | y=y1; 35 | for(i=1;i<=dx;i++) 36 | { 37 | if(pk<0) 38 | { 39 | if(flag==1) 40 | y=y+s2; 41 | else 42 | x=x+s1; 43 | pk=pk+inc1; 44 | } 45 | else 46 | { 47 | x=x+s1; 48 | y=y+s2; 49 | pk=pk+inc2; 50 | } 51 | putpixel(x,y,7); 52 | } 53 | } 54 | void main() 55 | { 56 | int gd=DETECT,gm; 57 | initgraph(&gd,&gm,"C:\\tc\\bgi"); 58 | bresham(75,375,175,375); 59 | bresham(75,425,100,425); 60 | bresham(100,575,100,425); 61 | bresham(100,575,150,575); 62 | bresham(150,575,150,425); 63 | bresham(150,425,175,425); 64 | bresham(175,375,175,375); 65 | bresham(175,375,150,375); 66 | bresham(150,75,150,375); 67 | bresham(150,75,125,25); 68 | bresham(100,75,100,375); 69 | bresham(100,75,125,25); 70 | getch(); 71 | closegraph(); 72 | } 73 | -------------------------------------------------------------------------------- /Algorithms/Kadanes-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | //Contributed By : Rishabh Jain 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | int maxsum(int arr[],int n) 8 | { 9 | int currsum=arr[0]; 10 | int maxsum=arr[0]; 11 | for(int i=1;i>t; 25 | while(t--) 26 | { 27 | int n; 28 | cin>>n; 29 | int arr[n]; 30 | for(int i=0;i>arr[i]; 33 | } 34 | cout< 2 | using namespace std; 3 | int main() { 4 | int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k; 5 | int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} }; 6 | int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} }; 7 | if (c1 != r2) { 8 | cout<<"Column of first matrix should be equal to row of second matrix"; 9 | } else { 10 | cout<<"The first matrix is:"< 2 | #define N 8 3 | using namespace std; 4 | 5 | bool isSafe(int chess[][N],int row,int col) 6 | { 7 | for(int i=0;i=0&&j>=0;i--,j--) 13 | { 14 | if(chess[i][j]==1) 15 | return false; 16 | } 17 | for(int i=row,j=col;j>=0&&i 2 | using namespace std; 3 | int main() 4 | { 5 | #ifdef ONLINE_JUDGE 6 | freopen("inputtest.txt","r",stdin); 7 | freopen("outputtest.txt","w",stdout); 8 | #endif 9 | vector A; 10 | int n; 11 | cin>>n; 12 | for(int i=0;i>x; 15 | A.push_back(x); 16 | } 17 | cout<<"Enter the item to be searched \n"; 18 | int item,f=0; 19 | cin>>item; 20 | int begin=0,end=n,mid=0; 21 | while(begin<=end){ 22 | mid=begin+(end-begin)/2; 23 | if(A[mid]==item){ 24 | cout<<"Found the item at "<item){ 28 | end=mid-1; 29 | }else{ 30 | begin=mid+1; 31 | } 32 | 33 | } 34 | if(f==0){ 35 | cout<<"Item not found"< 2 | using namespace std; 3 | 4 | int BinarySearch(int arr[], int num, int beg, int end) 5 | { 6 | int mid; 7 | 8 | if (beg > end){ 9 | 10 | cout << "Number is not found"; 11 | return 0; 12 | 13 | } else { 14 | 15 | mid = (beg + end) / 2; 16 | 17 | if(arr[mid] == num){ 18 | 19 | cout << "Number is found at " << mid << " index \n"; 20 | return 0; 21 | 22 | } else if (num > arr[mid]) { 23 | 24 | BinarySearch (arr, num, mid+1, end); 25 | 26 | } else if (num < arr[mid]) { 27 | 28 | BinarySearch (arr, num, beg , mid-1); 29 | } 30 | } 31 | 32 | 33 | } 34 | 35 | int main() { 36 | 37 | int arr[100], num, i, n, beg, end; 38 | 39 | cout <<"Enter the size of an array (Max 100) \n"; 40 | cin >> n; 41 | 42 | cout <<"Enter the sorted values \n"; 43 | 44 | for(i=0; i> arr[i]; 47 | } 48 | 49 | cout <<"Enter a value to be search \n"; 50 | cin >> num; 51 | 52 | beg = 0; 53 | end = n-1; 54 | 55 | BinarySearch (arr, num, beg, end); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Algorithms/Searching/Jump-Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int jumpSearch(int arr[], int n, int element) 5 | { 6 | //determining block size to be jumped 7 | int step = sqrt(n); 8 | 9 | //finding the block where element is present(iff it is present else return -1) 10 | int previous = 0; 11 | 12 | while(arr[min(step, n)-1] < element) 13 | { 14 | previous = step; 15 | step += sqrt(n); 16 | if(previous >= n) //implies element isn't available in either block 17 | return -1; 18 | } 19 | 20 | while(arr[previous] < element) 21 | { 22 | previous++; 23 | 24 | //implies element is not present in this particular block as end of block has been reached 25 | if(previous == min(step, n)) 26 | return -1; 27 | } 28 | //Element found at index previous 29 | if(arr[previous] == element) 30 | return previous; 31 | 32 | return -1; 33 | } 34 | 35 | int main(void) 36 | { 37 | cout<<"Enter array size: "<<"\n"; 38 | int n; cin>>n; 39 | int arr[n], element; 40 | for(int i=0; i>arr[i]; 42 | //For sorting array(if user entered unsorted array) 43 | sort(arr, arr+n); 44 | cout<<"Enter element to be searched: "<<"\n"; 45 | cin>>element; 46 | 47 | //storing returned index in variable called index 48 | int index = jumpSearch(arr, n, element); 49 | //printing the returned value from jumpSearch function 50 | cout<<"Element "< 2 | using namespace std; 3 | int main() 4 | { 5 | #ifdef ONLINE_JUDGE 6 | freopen("inputtest.txt","r",stdin); 7 | freopen("outputtest.txt","w",stdout); 8 | #endif 9 | vector A; 10 | int n; 11 | cin>>n; 12 | for(int i=0;i>x; 15 | A.push_back(x); 16 | } 17 | cout<<"Enter the item to be searched \n"; 18 | int item,f=0,pos=-1; 19 | cin>>item; 20 | for(int i=0;i 2 | #include "Solution.h" 3 | using namespace std; 4 | 5 | int partition(int arr[], int si, int ei){ 6 | int pivot = arr[si]; 7 | int count = 0; 8 | for (int i=si+1; i<=ei; i++){ 9 | if(arr[i] < arr[si]){ 10 | count ++; 11 | } 12 | } 13 | int pi = count + si; 14 | 15 | 16 | 17 | int temp = arr[si]; 18 | arr[si] = arr[pi]; 19 | arr[pi] = temp; 20 | 21 | int i = si, j = ei; 22 | 23 | while(ipi){ 24 | if(arr[i]=pivot){ 28 | j--; 29 | } 30 | else{ 31 | int temp = arr[i]; 32 | arr[i] = arr[j]; 33 | arr[j] = temp; 34 | i++; 35 | j--; 36 | } 37 | } 38 | return pi; 39 | } 40 | void sort(int arr[], int si, int ei){ 41 | if(si>=ei){ 42 | return; 43 | } 44 | int pivotindex = partition(arr, si, ei); 45 | 46 | sort(arr, si, pivotindex-1); 47 | sort(arr, pivotindex+1, ei); 48 | 49 | } 50 | void quickSort(int arr[], int n) { 51 | sort(arr, 0, n-1); 52 | 53 | } 54 | 55 | int main(){ 56 | int n; 57 | cin >> n; 58 | 59 | int *input = new int[n]; 60 | 61 | for(int i = 0; i < n; i++) { 62 | cin >> input[i]; 63 | } 64 | 65 | quickSort(input, n); 66 | for(int i = 0; i < n; i++) { 67 | cout << input[i] << " "; 68 | } 69 | 70 | delete [] input; 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Bubble Sort using Recursion.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void bubbleSort(int arr[], int n) 6 | { 7 | 8 | if (n == 1) 9 | return; 10 | 11 | int count = 0; 12 | 13 | for (int i=0; i arr[i+1]){ 15 | swap(arr[i], arr[i+1]); 16 | count++; 17 | } 18 | 19 | if (count==0) 20 | return; 21 | 22 | bubbleSort(arr, n-1); 23 | } 24 | 25 | void printArray(int arr[], int n) 26 | { 27 | for (int i=0; i < n; i++) 28 | printf("%d ", arr[i]); 29 | printf("\n"); 30 | } 31 | 32 | int main() 33 | { 34 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 35 | int n = sizeof(arr)/sizeof(arr[0]); 36 | bubbleSort(arr, n); 37 | printf("Sorted array : \n"); 38 | printArray(arr, n); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Counting-Sort.cpp: -------------------------------------------------------------------------------- 1 | //Contributed By : Rishabh Jain 2 | 3 | #include 4 | #define ll long long int 5 | using namespace std; 6 | 7 | 8 | int main() 9 | { 10 | ll n; 11 | cin>>n; 12 | ll arr[n]; 13 | for(ll i=0;i>arr[i]; 16 | } 17 | ll maxm=arr[0]; 18 | for(ll i=1;i 2 | using namespace std; 3 | void heapify(int arr[], int n, int i) { 4 | int temp; 5 | int largest = i; 6 | int l = 2 * i + 1; 7 | int r = 2 * i + 2; 8 | if (l < n && arr[l] > arr[largest]) 9 | largest = l; 10 | if (r < n && arr[r] > arr[largest]) 11 | largest = r; 12 | if (largest != i) { 13 | temp = arr[i]; 14 | arr[i] = arr[largest]; 15 | arr[largest] = temp; 16 | heapify(arr, n, largest); 17 | } 18 | } 19 | void heapSort(int arr[], int n) { 20 | int temp; 21 | for (int i = n / 2 - 1; i >= 0; i--) 22 | heapify(arr, n, i); 23 | for (int i = n - 1; i >= 0; i--) { 24 | temp = arr[0]; 25 | arr[0] = arr[i]; 26 | arr[i] = temp; 27 | heapify(arr, i, 0); 28 | } 29 | } 30 | int main() { 31 | int arr[] = { 20, 7, 1, 54, 10, 15, 90, 23, 77, 25}; 32 | int n = 10; 33 | i nt i; 34 | cout<<"Given array is: "< 2 | using namespace std; 3 | 4 | void InsertionSort(int a[],int n) 5 | { 6 | for(int i=1;i=0;j--) 11 | { 12 | if(element>n; 28 | int a[100000]; 29 | for(int i=0;i>a[i]; 32 | } 33 | InsertionSort(a,n); 34 | for(int j=0;j 2 | #include "solution.h" 3 | using namespace std; 4 | void merge(int input[],int si,int mid,int ei) 5 | { 6 | int i=si; 7 | int j=mid+1; 8 | int k=0; 9 | int arr[ei+1]; 10 | while(iinput[j]) 13 | { 14 | arr[k]=input[j]; 15 | j++; 16 | k++; 17 | } 18 | else 19 | { 20 | arr[k]=input[i]; 21 | i++; 22 | k++; 23 | } 24 | } 25 | while(i=ei) 48 | { 49 | return; 50 | } 51 | int mid=(si+ei)/2; 52 | merge_sort(input,si,mid); 53 | merge_sort(input,mid+1,ei); 54 | merge(input,si,mid,ei); 55 | } 56 | void mergeSort(int input[], int size){ 57 | // Write your code here 58 | 59 | int si=0; 60 | int ei= size-1; 61 | merge_sort(input,si,ei); 62 | } 63 | 64 | int main() { 65 | int length; 66 | cin >> length; 67 | int* input = new int[length]; 68 | for(int i=0; i < length; i++) 69 | cin >> input[i]; 70 | mergeSort(input, length); 71 | for(int i = 0; i < length; i++) { 72 | cout << input[i] << " "; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Quick-sort.cpp: -------------------------------------------------------------------------------- 1 | //Author - Shadman Afzal 2 | //Quicksort 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int Partitioning(vector &arr,int p,int r) // Partitioning of the arr 9 | { 10 | int i = p - 1,pivot = r; 11 | for(int j=p;j<=r;j++) 12 | { 13 | if(arr[j]<=arr[pivot]) 14 | { 15 | i++; 16 | swap(arr[i],arr[j]); 17 | } 18 | } 19 | return i; 20 | } 21 | 22 | void quicksort(vector &arr,int p,int r) 23 | { 24 | if(p arr; 35 | int n; 36 | cout<<"Enter the size of the Array"<>n; 38 | cout<<"Enter elements"<>temp; 43 | arr.push_back(temp); 44 | } 45 | cout<<"\nUNSORTED ARRAY"< 3 | using namespace std; 4 | 5 | int minIndex(int a[], int i, int j) 6 | { 7 | if (i == j) 8 | return i; 9 | 10 | int k = minIndex(a, i + 1, j); 11 | 12 | return (a[i] < a[k])? i : k; 13 | } 14 | 15 | void recurSelectionSort(int a[], int n, int index = 0) 16 | { 17 | 18 | if (index == n) 19 | return; 20 | 21 | int k = minIndex(a, index, n-1); 22 | 23 | if (k != index) 24 | swap(a[k], a[index]); 25 | 26 | recurSelectionSort(a, n, index + 1); 27 | } 28 | 29 | int main() 30 | { 31 | int arr[] = {3, 1, 5, 2, 7, 0}; 32 | int n = sizeof(arr)/sizeof(arr[0]); 33 | 34 | recurSelectionSort(arr, n); 35 | 36 | for (int i = 0; i 2 | using namespace std; 3 | int main(){ 4 | #ifndef ONLINE_JUDGE 5 | freopen("inputtest.txt","r",stdin); 6 | freopen("outputtest.txt","w",stdout); 7 | #endif 8 | 9 | vector arr; 10 | int n; 11 | cin>>n; 12 | for(int i=0;i>x; 15 | arr.push_back(x); 16 | } 17 | 18 | for(int i=0;iarr[j]){ 21 | int temp=arr[i]; 22 | arr[i]=arr[j]; 23 | arr[j]=temp; 24 | } 25 | } 26 | } 27 | cout<<"The sorted array is\n"; 28 | for(int i=0;i 2 | using namespace std; 3 | 4 | // Function to swap the number 5 | void swap(int a[],int i,int j) 6 | { int temp=a[i]; 7 | 8 | a[i]=a[j]; 9 | 10 | a[j]=temp; 11 | } 12 | void wavesort(int a[],int n) 13 | { 14 | for(int i=1;ia[i-1]) 17 | 18 | swap(a,i,i-1); 19 | 20 | if(a[i]>a[i+1] && i<=n-2) 21 | 22 | swap(a,i,i+1); 23 | } 24 | } 25 | int main() { 26 | 27 | int a[]={10, 90, 49, 2, 1, 5, 23}; 28 | 29 | int n=sizeof(a)/sizeof(a[0]); 30 | 31 | wavesort(a,n); 32 | 33 | for(int i=0;i Create n empty buckets (Or lists). 4 | --> Do following for every array element arr[i]. 5 | --> Insert arr[i] into bucket[n*array[i]] 6 | --> Sort individual buckets using insertion sort. 7 | --> Concatenate all sorted buckets. 8 | */ 9 | 10 | 11 | #include 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | 17 | void bucketSort(float arr[], int n) 18 | { 19 | 20 | // 1) Create n empty buckets 21 | vector b[n]; 22 | 23 | // 2) Put array elements in different buckets 24 | for (int i = 0; i < n; i++) { 25 | int bi = n * arr[i]; 26 | b[bi].push_back(arr[i]); 27 | } 28 | 29 | // 3) Sort individual buckets 30 | for (int i = 0; i < n; i++) 31 | sort(b[i].begin(), b[i].end()); 32 | 33 | // 4) Concatenate all buckets into arr[] 34 | int index = 0; 35 | for (int i = 0; i < n; i++) 36 | for (int j = 0; j < b[i].size(); j++) 37 | arr[index++] = b[i][j]; 38 | } 39 | 40 | 41 | int main() 42 | { 43 | float arr[] 44 | = { 0.356, 0.56, 0.856, 0.1584, 0.535, 0.3484 }; 45 | int n = sizeof(arr) / sizeof(arr[0]); 46 | bucketSort(arr, n); 47 | 48 | cout << "Sorted array is \n"; 49 | for (int i = 0; i < n; i++) 50 | cout << arr[i] << " "; 51 | return 0; 52 | } -------------------------------------------------------------------------------- /Algorithms/Sorting/comb-sort.cpp: -------------------------------------------------------------------------------- 1 | //Ishita Karandikar 2 | // C++ implementation of Comb Sort 3 | #include 4 | using namespace std; 5 | 6 | // To find gap between elements 7 | int getNextGap(int gap) 8 | { 9 | // Shrink gap by Shrink factor 10 | gap = (gap*10)/13; 11 | 12 | if (gap < 1) 13 | return 1; 14 | return gap; 15 | } 16 | 17 | // Function to sort a[0..n-1] using Comb Sort 18 | void combSort(int a[], int n) 19 | { 20 | // Initialize gap 21 | int gap = n; 22 | 23 | // Initialize swapped as true to make sure that 24 | // loop runs 25 | bool swapped = true; 26 | 27 | // Keep running while gap is more than 1 and last 28 | // iteration caused a swap 29 | while (gap != 1 || swapped == true) 30 | { 31 | // Find next gap 32 | gap = getNextGap(gap); 33 | 34 | // Initialize swapped as false so that we can 35 | // check if swap happened or not 36 | swapped = false; 37 | 38 | // Compare all elements with current gap 39 | for (int i=0; i a[i+gap]) 42 | { 43 | swap(a[i], a[i+gap]); 44 | swapped = true; 45 | } 46 | } 47 | } 48 | } 49 | 50 | // Driver program 51 | int main() 52 | { 53 | int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 54 | int n = sizeof(a)/sizeof(a[0]); 55 | 56 | combSort(a, n); 57 | 58 | printf("Sorted array: \n"); 59 | for (int i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | // Declarations 9 | int n,i,j,min=INT_MIN,max=INT_MAX,range,temp; 10 | vector arr,output,count; 11 | 12 | // Array length 13 | cout<<"Enter array length\n"; 14 | cin>>n; 15 | 16 | // Array Input 17 | for(i=0;i>temp; 19 | arr.push_back(temp); 20 | if(arr[i]max){ 24 | max=arr[i]; 25 | } 26 | } 27 | 28 | range = max - min + 1; 29 | 30 | // Counting Sort Algo Start 31 | for(i=0;i=0;i--){ 44 | output[count[arr[i]-min]-1]=arr[i]; 45 | count[arr[i]-min]--; 46 | } 47 | 48 | for(i=0;imaxSum): 18 | maxSum = curSum 19 | 20 | if(curSum<0): 21 | curSum=0 22 | 23 | return(maxSum) 24 | 25 | print(maxSumSubArray([-1,-8,-3,-4,-100])) -------------------------------------------------------------------------------- /Algorithms/mergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void mergesort(int a[],int i,int j); 4 | void merge(int a[],int i1,int j1,int i2,int j2); 5 | int main() 6 | { 7 | time_t start, end; 8 | double tc; 9 | 10 | int a[50],n,i; 11 | printf("Enter no of elements you want to sort:"); 12 | scanf("%d",&n); 13 | printf("Enter elements:"); 14 | 15 | for(i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int first, second; 7 | cout<<"Enter first number: \n"; cin>>first; 8 | cout<<"Enter second number: \n"; cin>>second; 9 | while(second != 0) 10 | { 11 | int carry = first & second; 12 | 13 | first = first ^ second; 14 | 15 | second = carry << 1; 16 | } 17 | cout<<"Sum of first and second is: "< 4 | using namespace std; 5 | 6 | #define fo(i, n) for(int i=0; i>n; 12 | int arr[n]; 13 | 14 | cout<<"Enter array elements: \n"; 15 | fo(i, n) 16 | cin>>arr[i]; 17 | fo(i ,n) 18 | result ^= arr[i]; 19 | 20 | if(result == 0) 21 | cout<<"Every number has even frequency. \n"; 22 | else 23 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int first, second; 7 | cout<<"Enter first number: \n"; cin>>first; 8 | cout<<"Enter second number: \n"; cin>>second; 9 | 10 | first = first ^ second; 11 | second = first ^ second; 12 | first = first ^ second; 13 | 14 | cout<<"Swapped variables: "< 2 | using namespace std; 3 | int main() 4 | {int t; 5 | cin>>t; 6 | while(t--) 7 | {int a,b; 8 | cin>>a>>b; 9 | int x=a&b; 10 | cout<<(a^x)+(b^x)< 2 | #define pb push_back 3 | #define ll long long 4 | #define llu unsigned long long 5 | #define endl "\n" 6 | 7 | using namespace std; 8 | 9 | int main(void) 10 | { 11 | ios::sync_with_stdio(false); 12 | cin.tie(0); 13 | cout.tie(0); 14 | int n; 15 | cin >> n; 16 | vector arr(n); 17 | for(int i = 0; i < n; ++i) cin >> arr[i]; 18 | vector diff; 19 | int prev = arr[0]; 20 | for(int i = 1; i < n; ++i) { 21 | if(prev > arr[i]) 22 | diff.pb(prev-arr[i]); 23 | else 24 | prev = arr[i]; 25 | } 26 | llu sum = 0; 27 | for(int i: diff) 28 | sum += i; 29 | cout << sum << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /CSES-Solutions/Missing-Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | #define llu unsigned long long 4 | 5 | using namespace std; 6 | 7 | int main(void) 8 | { 9 | ios::sync_with_stdio(false); 10 | cin.tie(0); 11 | cout.tie(0); 12 | int n; 13 | cin >> n; 14 | llu x = 1; 15 | for(int i = 2; i <= n; ++i) x ^= i; 16 | for(int i = 0; i < n-1; ++i) { 17 | llu b; 18 | cin >> b; 19 | x ^= b; 20 | } 21 | cout << x << "\n"; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /CSES-Solutions/Number-Spiral.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define forn(i, n) for(int k = i; i> t; 16 | while(t--) { 17 | llu r, c; 18 | cin >> r >> c; 19 | llu max = r>c?r:c; 20 | llu diag = max*(max-1) + 1; 21 | if(max&1) 22 | cout << diag - r + c << nl; 23 | else 24 | cout << diag + r - c << nl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /CSES-Solutions/Repetitions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | #define llu unsigned long long 4 | 5 | using namespace std; 6 | 7 | int main(void) 8 | { 9 | ios::sync_with_stdio(false); 10 | cin.tie(0); 11 | cout.tie(0); 12 | string s; 13 | cin >> s; 14 | char prev = 'A'; 15 | int count = 0; 16 | int ans = 0; 17 | for(char d: s) { 18 | if(prev == d) { 19 | ++count; 20 | ans = max(ans, count); 21 | } 22 | else { 23 | count = 1; 24 | prev = d; 25 | } 26 | } 27 | cout << ans << "\n"; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /CSES-Solutions/Subordinates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | typedef long long ll; 3 | #define pb push_back 4 | const int mod=1e9+7; 5 | const int N=2e5+7; 6 | using namespace std; 7 | 8 | vector adj[N]; 9 | bool vis[N]; 10 | int ans[N]; 11 | 12 | int dfs(int node) 13 | { 14 | if(vis[node]) 15 | return ans[node]; 16 | vis[node]=true; 17 | int juniors=1; 18 | for(auto junior:adj[node]) 19 | juniors+=dfs(junior); 20 | ans[node]+=juniors; 21 | return juniors; 22 | } 23 | int main() 24 | { 25 | ios_base::sync_with_stdio(false); 26 | cin.tie(NULL); 27 | 28 | int n; 29 | cin>>n; 30 | for(int i=0;i>ex; 34 | adj[ex].pb(i+2); 35 | } 36 | 37 | memset(vis , false , sizeof(vis) ); 38 | memset(ans , 0 , sizeof(ans) ); 39 | ans[1]=dfs(1); 40 | 41 | for(int i=1;i<=n;i++) 42 | cout< 2 | using namespace std; 3 | typedef long long int ll; 4 | int main(){ 5 | ll n; 6 | cin >> n; 7 | ll cnt=0; 8 | for(ll i=1;i 2 | #define ll long long 3 | #define llu unsigned long long 4 | 5 | using namespace std; 6 | 7 | int main(void) 8 | { 9 | ios::sync_with_stdio(false); 10 | cin.tie(0); 11 | cout.tie(0); 12 | llu n; 13 | cin >> n; 14 | cout << n << " "; 15 | while(n != 1) { 16 | if(n & 1) 17 | n = 3*n + 1; 18 | else 19 | n >>= 1; 20 | cout << " " << n; 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Complexity_Cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cp-geeks-adgitm/Hacktoberfest/857a682cf67d4ad698498edab1fdc8d128e13b6b/Complexity_Cheatsheet.pdf -------------------------------------------------------------------------------- /Contest/Codechef/Codechef-Sep-Cookoff-Div2/Codechef-sep-coofoff-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("inputtest.txt","r",stdin); 7 | freopen("outputtest.txt","w",stdout); 8 | #endif 9 | // int s; 10 | // cin>>s; 11 | int t; 12 | 13 | cin>>t; 14 | 15 | while(t--){ 16 | int n,k,l; 17 | cin>>n>>k>>l; 18 | if(k==1&&n>1){ 19 | cout<<"-1"<(l*k)){ 24 | cout<<"-1"<k){ 30 | x=1; 31 | } 32 | 33 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("inputtest.txt","r",stdin); 7 | freopen("outputtest.txt","w",stdout); 8 | #endif 9 | // int s; 10 | // cin>>s; 11 | int t; 12 | 13 | cin>>t; 14 | 15 | while(t--){ 16 | int n,k; 17 | cin>>n>>k; 18 | string s; 19 | vector a; 20 | cin>>s; 21 | int x=0,c=0; 22 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | 6 | 7 | 8 | int main() { 9 | #ifndef ONLINE_JUDGE 10 | freopen("inputtest.txt","r",stdin); 11 | freopen("outputtest.txt","w",stdout); 12 | #endif 13 | int t; 14 | cin>>t; 15 | while(t--){ 16 | int n; 17 | cin>>n; 18 | int A[n+1]; 19 | for(int i=1;i<=n;i++){ 20 | cin>>A[i]; 21 | } 22 | int d=0; 23 | for(int i=1;i<=n;i++){ 24 | int f=0; 25 | if(A[i]==i){ 26 | continue; 27 | } 28 | else{ 29 | for(int j=i-1;j>=1;j--){ 30 | if(__gcd(i,j)==A[i]){ 31 | f=1; 32 | break; 33 | } 34 | } 35 | if(f==0){ 36 | cout<<"NO"< 2 | using namespace std; 3 | 4 | int main() { 5 | int T, n, x; 6 | cin >> T; 7 | while(T --){ 8 | cin >> n >> x; 9 | int ans = x; 10 | if(ans > n - x) ans = n - x; 11 | cout << ans << endl; 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Contest/Codeforces/Codeforces-605-Div3/Codeforces-605-div3-D.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | typedef long long ll; 5 | int main() { 6 | 7 | 8 | int n; 9 | cin >> n; 10 | vector a(n); 11 | for (int i = 0; i < n; ++i) { 12 | cin >> a[i]; 13 | } 14 | int ans = 1; 15 | 16 | vector rg(n, 1); 17 | for (int i = n - 2; i >= 0; --i) { 18 | if (a[i + 1] > a[i]) rg[i] = rg[i + 1] + 1; 19 | ans = max(ans, rg[i]); 20 | } 21 | 22 | vector lf(n, 1); 23 | for (int i = 1; i < n; ++i) { 24 | if (a[i - 1] < a[i]) lf[i] = lf[i - 1] + 1; 25 | ans = max(ans, lf[i]); 26 | } 27 | 28 | for (int i = 0; i < n - 2; ++i) { 29 | if (a[i] < a[i + 2]) ans = max(ans, lf[i] + rg[i + 2]); 30 | } 31 | 32 | cout << ans << endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Contest/Codeforces/Codeforces-670-Div2/Codeforces-670-div2-A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | #ifndef ONLINE_JUDGE 6 | freopen("inputtest.txt","r",stdin); 7 | freopen("outputtest.txt","w",stdout); 8 | #endif 9 | int t; 10 | cin>>t; 11 | while(t--){ 12 | int n; 13 | cin>>n; 14 | vector v(n); 15 | int a[101]={0}; 16 | 17 | for(int i=0;i>v[i]; 19 | } 20 | int miss=0,min1=INT_MAX,min2=INT_MAX; 21 | sort(v.begin(),v.end()); 22 | if(v[0]==0){ 23 | miss++; 24 | } 25 | for(int i=0;i 2 | using namespace std; 3 | int main(){ 4 | 5 | ios_base::sync_with_stdio(false); 6 | long t; cin >> t; 7 | while(t--){ 8 | string s; 9 | cin >> s; 10 | set, pair > > vis; 11 | pair cur(make_pair(0,0)); 12 | long cnt(0); 13 | for(long p = 0; p < s.size(); p++) 14 | { 15 | pair next = cur; 16 | if(s[p] == 'S'){--next.second;} 17 | else if(s[p] == 'N'){++next.second;} 18 | else if(s[p] == 'W'){--next.first;} 19 | else if(s[p] == 'E'){++next.first;} 20 | cnt += 5 - 4 * vis.count(make_pair(cur, next)); 21 | vis.insert(make_pair(cur, next)); 22 | vis.insert(make_pair(next, cur)); 23 | cur = next; 24 | } 25 | 26 | cout<(var data: T, var next: Node? = null) -------------------------------------------------------------------------------- /Data-structures-in-Kotlin/Queue.kt: -------------------------------------------------------------------------------- 1 | class Queue { 2 | 3 | private var queue : LinkedList = LinkedList() 4 | 5 | fun enqueue(data: T) = queue.addLast(data) 6 | fun dequeue(): T? = queue.removeFirst() 7 | fun peek() : T? = queue.get(0) 8 | fun display() = queue.display() 9 | fun size() : Int = queue.size() 10 | } -------------------------------------------------------------------------------- /Data-structures-in-Kotlin/Stack.kt: -------------------------------------------------------------------------------- 1 | class Stack { 2 | var stack: LinkedList = LinkedList() 3 | 4 | fun pop() : T? = stack.removeFirst() 5 | fun push(data: T) = stack.addFirst(data) 6 | fun display() = stack.display() 7 | fun size() = stack.size() 8 | fun peek() = stack.get(0) 9 | } -------------------------------------------------------------------------------- /Data-structures-in-Kotlin/main.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | var myList : List = listOf("Tomato", "Potato", "Cabbage") 3 | 4 | var myQueue : Queue = Queue(); 5 | 6 | var myStack : Stack = Stack() 7 | 8 | for(x:String in myList) { 9 | myQueue.enqueue(x) 10 | myStack.push(x) 11 | } 12 | 13 | println("My Queue : ") 14 | myQueue.display() 15 | 16 | println("======================================") 17 | 18 | println("My Stack : ") 19 | myStack.display() 20 | 21 | } -------------------------------------------------------------------------------- /Data-structures/Arrays/DynamicAllocation2DArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int m; 8 | int n; 9 | cout<<"Enter Number of Rows"<>m; 11 | cout<<"Enter Number of Columns"<>n; 13 | int **p=new int*[m]; 14 | for(int i=0;i>p[i][j]; 20 | } 21 | } 22 | for(int i=0;i sumZero(int n) { 4 | vector x; 5 | int i; 6 | if(n==1){ 7 | x.push_back(0); 8 | return x; 9 | } 10 | if(n%2==0){ 11 | i=1; 12 | } 13 | else{ 14 | i=0; 15 | x.push_back(i); 16 | i++; 17 | } 18 | while(i<=n/2){ 19 | x.push_back(i); 20 | x.push_back(-i); 21 | i++; 22 | } 23 | return x; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Data-structures/Arrays/Median_of_two_sorted_arrays_of_different_sizes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int Solution(int arr[], int n) 5 | { 6 | 7 | if (n % 2 == 0) 8 | { 9 | int z = n / 2; 10 | int e = arr[z]; 11 | int q = arr[z - 1]; 12 | int ans = (e + q) / 2; 13 | return ans; 14 | } 15 | 16 | else 17 | { 18 | int z = round(n / 2); 19 | return arr[z]; 20 | } 21 | } 22 | 23 | int main() { 24 | 25 | int arr1[] = { -5, 3, 6, 12, 15 }; 26 | int arr2[] = { -12, -10, -6, -3, 4, 10 }; 27 | 28 | int i = sizeof(arr1) / sizeof(arr1[0]); 29 | int j = sizeof(arr2) / sizeof(arr2[0]); 30 | 31 | int arr3[i+j]; 32 | int l = i+j; 33 | 34 | for(int k=0;k>n; 30 | int a[100000]; 31 | //problem- this funtion will take input till 1000 and not stop until then 32 | for(int i=0;i>a[i]; 35 | } 36 | reversearray(a,n); 37 | printarray(a,n); 38 | } 39 | getch(); 40 | -------------------------------------------------------------------------------- /Data-structures/Arrays/removingDuplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int removeDuplicates(int a[] , int n) 4 | { 5 | if(n==1||n==0) 6 | return n; 7 | int temp[n]; 8 | int j=0; 9 | for(int i=0;i>n; 26 | int arr[n]; 27 | for(int i=0;i>arr[i]; 29 | 30 | int N=removeDuplicates(arr,n); 31 | for(int i=0;i 3 | using namespace std; 4 | 5 | //Function for Binary Search 6 | int BinarySearch (int arr[], int size, int element) 7 | { int start=0, end=size-1; 8 | int mid=(size+end)/2; 9 | while(start<=end) 10 | { 11 | if(arr[mid] == element) 12 | { 13 | return mid; 14 | } 15 | else if(arr[mid]>element) 16 | { 17 | end=mid-1; 18 | } 19 | else 20 | { 21 | start=mid+1; 22 | } 23 | mid=(start+end)/2; 24 | 25 | } 26 | return -1; 27 | 28 | } 29 | 30 | int main() 31 | { int size,element; 32 | cout<<"Enter the size of an array:"; 33 | cin>>size; 34 | int arr[size]; 35 | cout<< "Enter the elements of array in increasing order:"; 36 | 37 | for(int i=0;i>arr[i]; 40 | } 41 | cout<< "Enter the element:"; 42 | cin>> element; 43 | int found = BinarySearch (arr,size, element); 44 | if(found == -1) 45 | { 46 | cout<< element <<" is not found in the array\n"; 47 | 48 | } 49 | else 50 | { 51 | cout << element <<" is found in the array at position "<< found+1 << endl; 52 | } 53 | return 0; 54 | } 55 | OUTPUT: 56 | //Enter the size of an array:5 57 | //Enter the elements of array in increasing order:11 22 33 44 55 58 | //Enter the element:44 59 | 44 is found in the array at position 4 60 | -------------------------------------------------------------------------------- /Data-structures/Linked_List.cpp: -------------------------------------------------------------------------------- 1 | //Program to insert a node at beginning in linked list 2 | #include 3 | #include 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *next; 9 | }; 10 | 11 | 12 | void addFirst(struct node **head, int val) 13 | { 14 | //create a new node 15 | struct node *newNode = malloc(sizeof(struct node)); 16 | newNode->data = val; 17 | 18 | newNode->next = *head; 19 | 20 | *head = newNode; 21 | } 22 | 23 | void printList(struct node *head) 24 | { 25 | struct node *temp = head; 26 | 27 | //iterate the entire linked list and print the data 28 | while(temp != NULL) 29 | { 30 | printf("%d->", temp->data); 31 | temp = temp->next; 32 | } 33 | printf("NULL\n"); 34 | } 35 | //Driver code 36 | int main() 37 | { 38 | struct node *head = NULL; 39 | 40 | addFirst(&head,10); 41 | addFirst(&head,20); 42 | addFirst(&head,30); 43 | 44 | printList(head); 45 | 46 | return 0; 47 | } 48 | //OUTPUT: 49 | //30->20->10->NULL 50 | -------------------------------------------------------------------------------- /Data-structures/Queue/Circular_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int N = 5; 4 | 5 | 6 | class Queue { 7 | private: 8 | int a[N], first, last, cnt; 9 | public: 10 | Queue() { 11 | first = 0; 12 | last = -1; 13 | cnt = 0; 14 | } 15 | 16 | void push(int val) { 17 | if (isfull()) return ; 18 | cnt++; 19 | last++; 20 | last %= N; 21 | a[last] = val; 22 | } 23 | 24 | int pop() { 25 | if (isempty()) return -1; 26 | cnt--; 27 | int temp = first; 28 | first++; 29 | first %= N; 30 | return a[temp]; 31 | } 32 | 33 | bool isempty() { 34 | return cnt == 0; 35 | } 36 | 37 | bool isfull() { 38 | return cnt == N; 39 | } 40 | 41 | 42 | }; 43 | 44 | 45 | 46 | 47 | int main() 48 | { 49 | Queue Q; 50 | if (Q.isempty()) { 51 | cout << "Hey this is empty"; 52 | } 53 | 54 | 55 | Q.push(1); 56 | Q.push(2); 57 | Q.push(3); 58 | Q.push(4); 59 | Q.push(5); 60 | if (Q.isfull()) { 61 | cout << "Hey this is full"; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Data-structures/README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest 2020 2 | 3 | ![Banner](https://embed-fastly.wistia.com/deliveries/49bd387c40e2c5aada92abdf973bc46d.webp?image_crop_resized=960x540) 4 | 5 | We have created different folders for different data structures , just add the code or programs relevant to data structures specified. 6 | If anyone contribute inside any folder , just add the name to contributor list. 7 | 8 | ### For Contribution guidelines checkout this [README.md](../README.md) -------------------------------------------------------------------------------- /Data-structures/Stack/Stack.cpp: -------------------------------------------------------------------------------- 1 | # include 2 | 3 | using namespace std; 4 | 5 | class Stack 6 | { 7 | int top; 8 | public: 9 | int a[10]; //Maximum size of Stack 10 | Stack() 11 | { 12 | top = -1; 13 | } 14 | 15 | // declaring all the function 16 | void push(int x); 17 | int pop(); 18 | void isEmpty(); 19 | }; 20 | 21 | // function to insert data into stack 22 | void Stack::push(int x) 23 | { 24 | if(top >= 10) 25 | { 26 | cout << "Stack Overflow \n"; 27 | } 28 | else 29 | { 30 | a[++top] = x; 31 | cout << "Element Inserted \n"; 32 | } 33 | } 34 | 35 | // function to remove data from the top of the stack 36 | int Stack::pop() 37 | { 38 | if(top < 0) 39 | { 40 | cout << "Stack Underflow \n"; 41 | return 0; 42 | } 43 | else 44 | { 45 | int d = a[top--]; 46 | return d; 47 | } 48 | } 49 | 50 | // function to check if stack is empty 51 | void Stack::isEmpty() 52 | { 53 | if(top < 0) 54 | { 55 | cout << "Stack is empty \n"; 56 | } 57 | else 58 | { 59 | cout << "Stack is not empty \n"; 60 | } 61 | } 62 | 63 | // main function 64 | int main() { 65 | 66 | Stack s1; 67 | s1.push(10); 68 | s1.push(100); 69 | /* 70 | preform whatever operation you want on the stack 71 | */ 72 | } 73 | -------------------------------------------------------------------------------- /Data-structures/Stack/Stack_using_2_queues.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Stack { 6 | public: 7 | queue Q1, Qr; 8 | bool empty_stack() { 9 | return Q1.empty(); 10 | } 11 | void push(int x) { 12 | Q1.push(x); 13 | } 14 | void pop() { 15 | stack St; 16 | while (!Q1.empty()) { 17 | St.push(Q1.front()); 18 | Q1.pop(); 19 | } 20 | while (!St.empty()) { 21 | Qr.push(St.top()); 22 | St.pop(); 23 | } 24 | Qr.pop(); 25 | while (!Qr.empty()) { 26 | St.push(Qr.front()); 27 | Qr.pop(); 28 | } 29 | while (!St.empty()) { 30 | Q1.push(St.top()); 31 | St.pop(); 32 | } 33 | } 34 | int top() { 35 | if (empty_stack()) return -1; 36 | else return Q1.front(); 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | Stack St; 43 | St.push(5); 44 | St.push(6); 45 | St.pop(); 46 | cout << St.top(); 47 | } 48 | -------------------------------------------------------------------------------- /Data-structures/TRIE/Tclient_Java.java: -------------------------------------------------------------------------------- 1 | package TRIE; 2 | 3 | public class Tclient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | TrieCode t=new TrieCode(); 9 | t.insert("bad"); 10 | t.insert("mad"); 11 | t.insert("sad"); 12 | // System.out.println(t.search1(".ad")); 13 | 14 | char[][] board= {{'o','a','a','n'}, 15 | {'e','t','a','e'}, 16 | {'i','h','k','r'}, 17 | {'i','f','l','v'}}; 18 | String[] words={"oath","pea","eat","rain"}; 19 | System.out.println(t.findWords(board, words)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Data-structures/Tree/226-invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* invertTree(TreeNode* root) { 4 | if(root==NULL) 5 | return NULL; 6 | 7 | swap(root->left,root->right); 8 | invertTree(root->left); 9 | invertTree(root->right); 10 | 11 | return root; 12 | } 13 | }; -------------------------------------------------------------------------------- /Data-structures/Tree/Binary-tree-traversal.cpp: -------------------------------------------------------------------------------- 1 | //Author- Shadman Afzal 2 | #include 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *left,*right; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | left = right = NULL; 13 | } 14 | }; 15 | 16 | void postorder(struct Node* node) 17 | { 18 | if(node==NULL) 19 | return; 20 | postorder(node->left); 21 | postorder(node->right); 22 | cout<data<<" "; 23 | } 24 | 25 | void inorder(struct Node* node) 26 | { 27 | 28 | if(node==NULL) 29 | return; 30 | inorder(node->left); 31 | cout<data<<" "; 32 | inorder(node->right); 33 | } 34 | 35 | void preorder(struct Node* node) 36 | { 37 | if(node==NULL) 38 | return; 39 | cout<data<<" "; 40 | preorder(node->left); 41 | preorder(node->right); 42 | } 43 | 44 | int main() 45 | { 46 | struct Node* root = new Node(1); 47 | root->left = new Node(2); 48 | root->right = new Node(3); 49 | root->left->left = new Node(4); 50 | root->left->right = new Node(5); 51 | 52 | cout<<"\nPreorder traversal of binary tree is\n"; 53 | preorder(root); 54 | 55 | cout<<"\nPostorder traversal of binary tree is\n"; 56 | postorder(root); 57 | 58 | cout<<"\nInorder traversal of binary tree is\n"; 59 | inorder(root); 60 | } 61 | -------------------------------------------------------------------------------- /Data-structures/morris.cpp: -------------------------------------------------------------------------------- 1 | /* Tree Node 2 | struct Node { 3 | int data; 4 | Node* left; 5 | Node* right; 6 | };*/ 7 | #include 8 | using namespace std; 9 | class Solution { 10 | public: 11 | vector inOrder(Node* root) 12 | { 13 | Node*cur=root; 14 | vectorv; 15 | //code here 16 | while(cur){ 17 | if(!cur->left) {v.push_back(cur->data); cur=cur->right;} 18 | else{ 19 | Node*pred=cur->left; 20 | while(pred->right and pred->right!=cur) pred=pred->right; 21 | if(!pred->right){ 22 | pred->right=cur; 23 | cur=cur->left; 24 | } 25 | else{ 26 | pred->right=NULL; 27 | v.push_back(cur->data); 28 | cur=cur->right; 29 | } 30 | 31 | } 32 | } 33 | return v; 34 | } 35 | }; -------------------------------------------------------------------------------- /Data-structures/no_of_provinces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | // finding nod1->par equaility with nod2->par; 6 | // to check whether their same component or not; 7 | // if they are same locality then we count both as 1, 8 | // else both are unique 9 | void dsu(int x,int y,vector&par){ 10 | int p1=find(x,par),p2=find(y,par); 11 | if(p1==p2) return; 12 | else par[p1]=p2; 13 | } 14 | // checking their nodes vs parents 15 | int find(int v,vector&par){ 16 | if(par[v]==-1) return v; 17 | return par[v]=find(par[v],par); 18 | } 19 | int findCircleNum(vector>& mat) { 20 | int n=mat.size(); 21 | vectorpar(n,-1); 22 | for(int i=0;i 13 | using namespace std; 14 | class Solution { 15 | public: 16 | vector> verticalTraversal(TreeNode* root) { 17 | // map> 18 | map>>mp; 19 | queue>>q; // node val, vert level; 20 | q.push({root,{0,0}}); 21 | while(!q.empty()){ 22 | auto a=q.front(); // 3,0,0 23 | q.pop(); 24 | TreeNode*ptr=a.first; 25 | int vert=a.second.first,lev=a.second.second; 26 | mp[vert][lev].insert(ptr->val); 27 | if(ptr->left) q.push({ptr->left,{vert-1,lev+1}}); 28 | if(ptr->right) q.push({ptr->right,{vert+1,lev+1}}); 29 | } 30 | vector>ans; 31 | for(auto i:mp){ 32 | vectorv; 33 | for(auto p:i.second){ // here i.second is int,multiset 34 | // insert(pos,start and begin of another ds) 35 | v.insert(v.end(),p.second.begin(),p.second.end()); 36 | } 37 | ans.push_back(v); 38 | } 39 | return ans; 40 | } 41 | }; -------------------------------------------------------------------------------- /HackerRank-Solutions/Algorithms/Dynamic-programming/Fibonacci-modified.java: -------------------------------------------------------------------------------- 1 | //Code is provided by Shrey Singh 2 | /** 3 | * 4 | * Problem Statement- 5 | * [Fibonacci Modified](https://www.hackerrank.com/challenges/fibonacci-modified/problem) 6 | * 7 | */ 8 | 9 | import java.math.BigDecimal; 10 | import java.util.Scanner; 11 | 12 | public class FibonacciModified { 13 | public static void main(String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | BigDecimal t1 = new BigDecimal(sc.nextInt()); 16 | BigDecimal t2 = new BigDecimal(sc.nextInt()); 17 | int n = sc.nextInt(); 18 | 19 | BigDecimal sum = new BigDecimal(0); 20 | for (int i = 3; i <= n; i++) { 21 | sum = t1.add(t2.multiply(t2)); 22 | t1 = t2; 23 | t2 = sum; 24 | } 25 | System.out.println(sum); 26 | sc.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank-Solutions/Algorithms/Dynamic-programming/Maximum-subarray.java: -------------------------------------------------------------------------------- 1 | //Code provided by Shrey Singh 2 | /** 3 | * 4 | * Problem Statement- 5 | * [The Maximum Subarray](https://www.hackerrank.com/challenges/maxsubarray/problem) 6 | * 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class TheMaximumSubarray { 12 | 13 | static int[] maxSubarray(int[] arr) { 14 | int max_so_far = Integer.MIN_VALUE, max_end_here = 0, maxSum = 0; 15 | int ans[] = new int[2]; 16 | for (int i = 0; i < arr.length; i++) { 17 | if (arr[i] > 0) 18 | maxSum += arr[i]; 19 | max_end_here += arr[i]; 20 | max_end_here = Math.max(max_end_here, arr[i]); 21 | max_so_far = Math.max(max_so_far, max_end_here); 22 | } 23 | ans[0] = max_so_far; 24 | ans[1] = max_so_far < 0 ? max_so_far : maxSum; 25 | return ans; 26 | 27 | } 28 | public static void main(String[] args) { 29 | Scanner in = new Scanner(System.in); 30 | int t = in.nextInt(); 31 | for (int a0 = 0; a0 < t; a0++) { 32 | int n = in.nextInt(); 33 | int[] arr = new int[n]; 34 | for (int arr_i = 0; arr_i < n; arr_i++) { 35 | arr[arr_i] = in.nextInt(); 36 | } 37 | int[] result = maxSubarray(arr); 38 | for (int i = 0; i < result.length; i++) { 39 | System.out.print(result[i] + (i != result.length - 1 ? " " : "")); 40 | } 41 | System.out.println(""); 42 | 43 | } 44 | in.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /HackerRank-Solutions/Algorithms/Greedy/Priyanka-and-toys.java: -------------------------------------------------------------------------------- 1 | // Code provided by Shrey Singh 2 | /** 3 | * 4 | * Problem Statement- 5 | * [Priyanka and Toys](https://www.hackerrank.com/challenges/priyanka-and-toys/problem) 6 | * 7 | */ 8 | 9 | import java.util.Arrays; 10 | import java.util.Scanner; 11 | 12 | public class PriyankaAndToys { 13 | static int toys(int[] w) { 14 | Arrays.sort(w); 15 | int containerCouter = 1, weightLimit = w[0]; 16 | for (int i = 0; i < w.length; i++) { 17 | if (w[i] > weightLimit + 4) { 18 | weightLimit = w[i]; 19 | containerCouter++; 20 | } 21 | } 22 | return containerCouter; 23 | } 24 | 25 | public static void main(String[] args) { 26 | Scanner in = new Scanner(System.in); 27 | int n = in.nextInt(); 28 | int[] w = new int[n]; 29 | for (int w_i = 0; w_i < n; w_i++) { 30 | w[w_i] = in.nextInt(); 31 | } 32 | int result = toys(w); 33 | System.out.println(result); 34 | in.close(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /HackerRank-Solutions/Arrays/Big-sorting.java: -------------------------------------------------------------------------------- 1 | // Code provided by Shrey Singh 2 | /** 3 | * 4 | * Problem Statement- 5 | * [Big Sorting](https://www.hackerrank.com/challenges/big-sorting/problem) 6 | * 7 | */ 8 | 9 | import java.util.Arrays; 10 | import java.util.Comparator; 11 | import java.util.Scanner; 12 | 13 | public class BigSorting { 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | int n = in.nextInt(); 17 | String[] unsorted = new String[n]; 18 | for (int unsorted_i = 0; unsorted_i < n; unsorted_i++) { 19 | unsorted[unsorted_i] = in.next(); 20 | } 21 | 22 | Arrays.sort(unsorted, new Comparator() { 23 | 24 | public int compare(String s1, String s2) { 25 | return compareStrings(s1, s2); 26 | } 27 | }); 28 | printArray(unsorted); 29 | in.close(); 30 | } 31 | 32 | private static int compareStrings(String s1, String s2) { 33 | if (s1.length() < s2.length()) { 34 | return -1; 35 | } else if (s1.length() > s2.length()) { 36 | return 1; 37 | } 38 | for (int k = 0; k < s1.length(); k++) { 39 | if ((int) s1.charAt(k) < (int) s2.charAt(k)) 40 | return -1; 41 | if ((int) s1.charAt(k) > (int) s2.charAt(k)) 42 | return 1; 43 | 44 | } 45 | return 0; 46 | 47 | } 48 | 49 | private static void printArray(String[] unsorted) { 50 | 51 | for (String string : unsorted) { 52 | System.out.println(string); 53 | } 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /HackerRank-Solutions/Practice Problems/Athlete Sort.py: -------------------------------------------------------------------------------- 1 | N, M = map(int, input().split()) 2 | rows = [input() for _ in range(N)] 3 | K = int(input()) 4 | 5 | for row in sorted(rows, key=lambda row: int(row.split()[K])): 6 | print(row) -------------------------------------------------------------------------------- /HackerRank-Solutions/Practice Problems/any_or_all.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | elements = input().split() 3 | # i[::-1] reverse the string 4 | # any(i==i[::-1]) check palindrome by reversing and checking the element 5 | print(all(int(i) > 0 for i in elements) and any(i == i[::-1] for i in elements)) -------------------------------------------------------------------------------- /HackerRank-Solutions/Practice Problems/arrays.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | 4 | def arrays(arr): 5 | # arr[::-1] will reverse the list 6 | return numpy.array(arr[::-1], float) 7 | 8 | 9 | if __name__ == '__main__': 10 | arr = input().strip().split(' ') 11 | result = arrays(arr) 12 | print(result) -------------------------------------------------------------------------------- /HackerRank-Solutions/Practice Problems/maximize_it.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | 3 | K, M = map(int, input().split()) 4 | 5 | # [1:] in below command will skip the first value from the enter values 6 | N = (list(map(int, input().split()))[1:] for _ in range(K)) 7 | 8 | # It uses the lambda function which takes function as a first argument then applies to iterable item 9 | # *N is known as unpacking of items from the list 10 | results = map(lambda x: sum(i ** 2 for i in x) % M, product(*N)) 11 | print(max(results)) -------------------------------------------------------------------------------- /Important-Interview-Questions/Stack-balanced-paranthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool is_bal(string s) { 6 | int i, n = s.size(); 7 | stack St; 8 | for (i = 0; i < n; i++) { 9 | if (s[i] == '{') { 10 | St.push(s[i]); 11 | } 12 | else if (s[i] == '}') { 13 | if (St.empty()) return false; 14 | char on_top = St.top(); 15 | if (on_top == '{') { 16 | St.pop(); 17 | } 18 | else { 19 | return false; 20 | } 21 | } 22 | else if (s[i] == '(') { 23 | St.push(s[i]); 24 | 25 | } 26 | else if (s[i] == ')') { 27 | if (St.empty()) return false; 28 | char on_top = St.top(); 29 | if (on_top == '(') { 30 | St.pop(); 31 | } 32 | else { 33 | return false; 34 | } 35 | } 36 | else if (s[i] == '[') { 37 | St.push(s[i]); 38 | 39 | } 40 | else if (s[i] == ']') { 41 | if (St.empty()) return false; 42 | char on_top = St.top(); 43 | if (on_top == '[') { 44 | St.pop(); 45 | } 46 | else { 47 | return false; 48 | } 49 | } 50 | } 51 | if (St.empty()) { 52 | return true; 53 | } 54 | else { 55 | return false; 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | string s; 62 | cin >> s; 63 | if (is_bal(s)) { 64 | cout << "Yes"; 65 | } 66 | else { 67 | cout << "No"; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Important-Interview-Questions/Unique-number-from-pairs-by-XOR.cpp: -------------------------------------------------------------------------------- 1 | //Contributed By : Rishabh Jain 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | void uniqueno(int arr[],int n) 8 | { 9 | int xorno=0; 10 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int n; 7 | cin >> n; 8 | 9 | int arr[n],Count,Max_count=0; 10 | int a = 0; 11 | while(a> arr[a]; 13 | a++; 14 | } 15 | 16 | a=0; 17 | while(a Max_count) 26 | Max_count=Count; 27 | a++; 28 | } 29 | 30 | a=0; 31 | while(a 2 | 3 | 4 | 5 | 42 | 43 | -------------------------------------------------------------------------------- /Insertion Sort/Insertion Sort.depend: -------------------------------------------------------------------------------- 1 | # depslib dependency file v1.0 2 | 1598965057 source:d:\coding ninjas\codes\searching and sorting\insertion sort\main.cpp 3 | 4 | 5 | -------------------------------------------------------------------------------- /Insertion Sort/Insertion Sort.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Insertion Sort/bin/Debug/Insertion Sort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cp-geeks-adgitm/Hacktoberfest/857a682cf67d4ad698498edab1fdc8d128e13b6b/Insertion Sort/bin/Debug/Insertion Sort.exe -------------------------------------------------------------------------------- /Insertion Sort/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void InsertionSort(int a[],int n) 5 | { 6 | for(int i=1;i=0;j--) 11 | { 12 | if(element>n; 28 | int a[100000]; 29 | for(int i=0;i>a[i]; 32 | } 33 | InsertionSort(a,n); 34 | for(int j=0;j Solution::dNums(vector &A, int B) { 2 | map m; 3 | vector v; 4 | int count=0; 5 | for(int i=0;ival > b->val; 14 | } 15 | }; 16 | ListNode* Solution::mergeKLists(vector &A) { 17 | if(A.size()==0) 18 | return NULL; 19 | priority_queue,comp> q; 20 | ListNode* ans = new ListNode(0); 21 | 22 | ListNode* temp=ans; 23 | for(auto i=0;inext=q.top(); 32 | temp=temp->next; 33 | q.pop(); 34 | if(temp->next!=NULL) 35 | { 36 | q.push(temp->next); 37 | } 38 | 39 | 40 | } 41 | return ans->next; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /InterviewBit-Solutions/Heaps/N-max-pair-combinations.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A, vector &B) { 2 | int n=A.size(); 3 | sort(A.begin(),A.end()); 4 | sort(B.begin(),B.end()); 5 | 6 | priority_queue>> q; 7 | set> s; 8 | vector v; 9 | int i=n-1,j=n-1; 10 | q.push({A[i]+B[j],{i,j}}); 11 | s.insert({i, j}); 12 | int count=1; 13 | 14 | while(count<=n) 15 | { 16 | pair> p; 17 | p=q.top(); 18 | v.push_back(p.first); 19 | q.pop(); 20 | 21 | pair p1={p.second.first-1, p.second.second}; 22 | if(s.find(p1)==s.end()) 23 | { 24 | q.push({A[p1.first]+B[p1.second],{p1}}); 25 | s.insert(p1); 26 | } 27 | pair p2={p.second.first, p.second.second-1}; 28 | if(s.find(p2)==s.end()) 29 | { 30 | q.push({A[p2.first]+B[p2.second],{p2}}); 31 | s.insert(p2); 32 | } 33 | 34 | count++; 35 | } 36 | //reverse(v.begin(),v.end()); 37 | return v; 38 | 39 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int ans = 0, min = Integer.MAX_VALUE; 4 | for (int i = 0; i < prices.length; i++) { 5 | ans = Math.max(ans, prices[i] - min); 6 | min = Math.min(prices[i], min); 7 | } 8 | return ans; 9 | } 10 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Cells-with-odd-values-in-a-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int oddCells(int n, int m, vector>& indices) { 4 | int ans=0; 5 | vector>arr(n,vector(m,0)); 6 | for(int i=0;i kidsWithCandies(vector& candies, int extraCandies) { 4 | int max=0; 5 | vector x; 6 | for(int i=0;imax){ 8 | max=candies[i]; 9 | } 10 | } 11 | for(int i=0;i=max){ 13 | x.push_back(true); 14 | } 15 | else{ 16 | x.push_back(false); 17 | } 18 | } 19 | return x; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Largest-rectangle-in-histogram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestRectangleArea(int[] heights) { 3 | 4 | if (heights.length == 1) 5 | return heights[0]; 6 | 7 | int n = heights.length; 8 | int[] nsl = new int[n]; 9 | int[] nsr = new int[n]; 10 | 11 | Stack stack = new Stack<>(); 12 | 13 | for (int i = 0; i < n; i++) { 14 | while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) 15 | nsr[stack.pop()] = i; 16 | 17 | nsl[i] = stack.isEmpty() ? -1 : stack.peek(); 18 | stack.push(i); 19 | } 20 | 21 | while (!stack.isEmpty()) 22 | nsr[stack.pop()] = n; 23 | 24 | int ans = 0; 25 | 26 | for (int i = 0; i < n; i++) { 27 | int exl = nsr[i] - nsl[i] - 1; 28 | ans = Math.max(ans, exl * heights[i]); 29 | } 30 | 31 | return ans; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Longest Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string s) { 4 | stackstk; 5 | stk.push(-1); 6 | int large=0; 7 | for(int i=0;i int: 3 | maxSub = nums[0] 4 | curSum = 0 5 | 6 | for n in nums: 7 | if curSum<0: 8 | curSum=0 9 | 10 | curSum += n 11 | maxSub = max(maxSub, curSum) 12 | return maxSub -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Maximum-product-subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int cmax = 1, omax = Integer.MIN_VALUE; 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | if (nums[i] == 0) { 7 | cmax = 1; 8 | omax = Math.max(0, omax); 9 | } else { 10 | cmax *= nums[i]; 11 | omax = Math.max(cmax, omax); 12 | } 13 | } 14 | 15 | cmax = 1; 16 | for (int i = nums.length - 1; i >= 0; i--) { 17 | if (nums[i] == 0) { 18 | cmax = 1; 19 | omax = Math.max(0, omax); 20 | } else { 21 | cmax *= nums[i]; 22 | omax = Math.max(cmax, omax); 23 | } 24 | } 25 | 26 | return omax; 27 | } 28 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Median_of_two_sorted_arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1, nums2) -> float: 3 | median_index = ((len(nums1)+len(nums2))//2) 4 | is_series_odd = (len(nums1)+len(nums2))%2==1 5 | i=j=0 6 | item=[] 7 | for _ in range(median_index+1): 8 | if i< len(nums1) and j>& points) { 4 | 5 | int x,y,count=0; 6 | for(int i=0;i&A,vector&B) 2 | { 3 | if(A[0]==B[0]) 4 | { 5 | return A[1]>B[1]; 6 | } 7 | return A[0]>& intervals) { 16 | 17 | sort(intervals.begin(),intervals.end(),compare); 18 | 19 | 20 | int count=1,start=intervals[0][0],end=intervals[0][1]; 21 | 22 | for(int i=1;i=intervals[i][1]) 25 | { 26 | continue; 27 | } 28 | else 29 | { 30 | start=min(start,intervals[i][0]); 31 | end=max(end,intervals[i][1]); 32 | count++; 33 | } 34 | } 35 | return count; 36 | }}; 37 | 38 | // Solved using counting and sorting LeetCode1288 in C++ -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Roman-to-Integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int romanToDecimal(string& str) 4 | { 5 | map m; 6 | m.insert({ 'I', 1 }); 7 | m.insert({ 'V', 5 }); 8 | m.insert({ 'X', 10 }); 9 | m.insert({ 'L', 50 }); 10 | m.insert({ 'C', 100 }); 11 | m.insert({ 'D', 500 }); 12 | m.insert({ 'M', 1000 }); 13 | int sum = 0; 14 | for (int i = 0; i < str.length(); i++) 15 | { 16 | if (m[str[i]] < m[str[i + 1]]) 17 | { 18 | sum= sum + m [str[i+1]]-m[str[i]]; 19 | i++; 20 | continue; 21 | } 22 | sum += m[str[i]]; 23 | } 24 | return sum; 25 | } 26 | int main(){ 27 | string str = "MCMIV"; 28 | cout << "Integer form of Roman Numeral is " 29 | << romanToDecimal(str) << endl; 30 | 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Rotate-image.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | 4 | for (int i = 0; i < matrix.length; i++) { 5 | for (int j = 0; j < matrix[0].length; j++) { 6 | if (j > i) { 7 | int temp = matrix[i][j]; 8 | matrix[i][j] = matrix[j][i]; 9 | matrix[j][i] = temp; 10 | } 11 | } 12 | } 13 | 14 | for (int i = 0; i < matrix.length; i++) { 15 | int lo = 0, hi = matrix.length - 1; 16 | while (lo < hi) { 17 | int temp = matrix[i][lo]; 18 | matrix[i][lo] = matrix[i][hi]; 19 | matrix[i][hi] = temp; 20 | lo++; 21 | hi--; 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/Subarray-sum-equals-k.java: -------------------------------------------------------------------------------- 1 | // import java.util.HashMap; 2 | 3 | class Solution { 4 | public int subarraySum(int[] nums, int k) { 5 | 6 | int sum = 0, ans = 0; 7 | HashMap map = new HashMap<>(); 8 | map.put(0, 1); 9 | 10 | for (int i = 0; i < nums.length; i++) { 11 | sum += nums[i]; 12 | if (map.containsKey(sum - k)) 13 | ans += map.get(sum - k); 14 | map.put(sum, map.getOrDefault(sum, 0) + 1); 15 | } 16 | 17 | return ans; 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/TrappingRainwater.java: -------------------------------------------------------------------------------- 1 | public class TrappingRainwater { 2 | public static int trap(int[] a) { 3 | int res=0; 4 | int n=a.length; 5 | int l[]=new int[a.length]; 6 | int r[]=new int[a.length]; 7 | l[0]=a[0]; 8 | for(int i=1;i=0;i--){ 13 | r[i]=Math.max(a[i],r[i+1]); 14 | } 15 | for(int i=1;i List[int]: 3 | array = {} 4 | 5 | for i in range(len(nums)): 6 | result = target-nums[i] 7 | if result in array: 8 | return [i, array[result]] 9 | else: 10 | array[nums[i]] = i 11 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/TwoSumProb.cpp: -------------------------------------------------------------------------------- 1 | // Two Sum Problem 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // While we iterate and inserting elements into the table, 8 | // we also look back to check if current element's complement already exists in the table. 9 | // If it exists, we have found a solution and return immediately. 10 | 11 | vector twoSum(vector& nums, int target) { 12 | map map; 13 | vector pairs; 14 | for(int i = 0; i < nums.size(); i++) { 15 | int complement = target - nums[i]; 16 | if(map.find(complement) != map.end()) { 17 | pairs.push_back(map.find(complement)->second); 18 | pairs.push_back(i); 19 | break; 20 | } 21 | map.insert(pair(nums[i], i)); 22 | } 23 | return pairs; 24 | }; 25 | 26 | int main() { 27 | vectornums = {1,4,3,6,5,8}; 28 | vectorpair = twoSum(nums,4); 29 | cout << "pair indices are : " << pair[0] << " " << pair[1] << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/find_first_and_last_position_of_element_in_sorted_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums, target): 3 | # we are using the binary search to get the index in O(logN) time 4 | left,right = 0,len(nums)-1 5 | while right>=left: 6 | mid = left +(right-left)//2 7 | if nums[mid]>target: 8 | right = mid-1 9 | elif nums[mid]0 and nums[leftest_index]==nums[leftest_index-1]: 17 | leftest_index -=1 18 | 19 | # last item occurence 20 | while rightest_index int: 2 | 3 | """ 4 | The majority element is the element that appears more than ⌊n / 2⌋ times. 5 | You may assume that the majority element always exists in the array. 6 | """ 7 | 8 | ele = cnt = 0 9 | 10 | for i in nums: 11 | if cnt == 0: 12 | ele = i 13 | if ele == i: 14 | cnt += 1 15 | else: 16 | cnt -= 1 17 | 18 | return ele 19 | 20 | 21 | if __name__ == "__main__": 22 | print(majority_element([3, 2, 3])) 23 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Arrays/minimum-time-to-make-rope-colorful.py: -------------------------------------------------------------------------------- 1 | # Problem link - https://leetcode.com/problems/minimum-time-to-make-rope-colorful/description/ 2 | 3 | # Intuition :- 4 | # For a subarray of baloons with same color, 5 | # we need to remove all the baloons except the one which takes the minimum time. 6 | 7 | # Complexity 8 | # Time - O(N) 9 | # Space - O(1) 10 | 11 | class Solution: 12 | def minCost(self, colors: str, neededTime: List[int]) -> int: 13 | min_time = 0 14 | total_time = 0 15 | max_time = 0 16 | for i in range(len(colors)): 17 | if i > 0 and colors[i] != colors[i - 1]: 18 | # for each group, minimum time to make rope colorful again is 19 | # total time - max time 20 | min_time += total_time - max_time 21 | total_time = 0 22 | max_time = 0 23 | total_time += neededTime[i] 24 | max_time = max(max_time, neededTime[i]) 25 | min_time += total_time - max_time 26 | return min_time 27 | -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/10-Regular-Expression-Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map,bool>m; 4 | bool helper(string text,string pattern, int textindex, int patternindex) { 5 | if(textindex==text.length()&&patternindex==pattern.length()) 6 | m[{textindex,patternindex}]=true; 7 | else if(textindex==text.length()) { 8 | if(patternindex+1> generate(int numsRows) { 4 | 5 | vector> dp(numsRows,vector(numsRows,0)); 6 | vector> sol; 7 | 8 | for(int i=0;i temp; 22 | for(int i=0,j=g;j>=0;j--,i++) 23 | temp.push_back(dp[i][j]); 24 | sol.push_back(temp); 25 | } 26 | 27 | return sol; 28 | 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/32-Longest-valid-parantheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string str) 4 | { 5 | int n = str.length(); 6 | if(n==0) 7 | return 0; 8 | stack stk; 9 | stk.push(-1); 10 | 11 | int result = 0; 12 | 13 | for (int i=0; i=0&&highsi) 14 | { 15 | st=low; 16 | si=high-low+1; 17 | } 18 | low--; 19 | high++; 20 | } 21 | //even pailndrome 22 | low=i-1; 23 | high=i+1; 24 | while(low>=0&&highsi) 27 | { 28 | st=low; 29 | si=high-low+1; 30 | } 31 | low--; 32 | high++; 33 | } 34 | } 35 | return (s.substr(st,si)); 36 | } 37 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/72-Edit-Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string A, string B) { 4 | int i,j,m=A.length(),n=B.length(); 5 | int dp[m+1][n+1]; 6 | for(i=0;i<=m;i++) 7 | { 8 | for(j=0;j<=n;j++) 9 | { 10 | if (i == 0) 11 | dp[i][j] = j; 12 | else if (j == 0) 13 | dp[i][j] = i; 14 | 15 | else if(A[i-1]==B[j-1]) 16 | dp[i][j]=dp[i-1][j-1]; 17 | else 18 | dp[i][j]=min(dp[i-1][j-1],min(dp[i][j-1],dp[i-1][j]))+1; 19 | } 20 | } 21 | return dp[m][n]; 22 | 23 | } 24 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/Coin_Change_DP.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& c, int amount) { 4 | int n=c.size(); 5 | vector v(amount+1,0); 6 | for(int i=1;i<=amount;i++){ 7 | int temp=INT_MAX; 8 | for(int j=0;j=0){ 10 | if(v[i-c[j]]==-1){continue;} 11 | temp=min(temp,v[i-c[j]]); 12 | } 13 | } 14 | if(temp==INT_MAX){v[i]=-1;} 15 | else{v[i]=temp+1;} 16 | } 17 | return v[amount]; 18 | } 19 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | memo_table = {1:1,0:1} 4 | def calculate(k,memo_table): 5 | if k in memo_table: 6 | return memo_table[k] 7 | value = calculate(k-1,memo_table)+calculate(k-2,memo_table) 8 | memo_table[k]=value 9 | return value 10 | return calculate(n,memo_table) 11 | 12 | def climbStairs1(self, n: int) -> int: 13 | a = b = 1 14 | for _ in range(n): 15 | a, b = b, a + b 16 | return a 17 | item = Solution() 18 | print(item.climbStairs1(8)) -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/number-of-dice-rolls-with-target-sum.py: -------------------------------------------------------------------------------- 1 | # Problem link - https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/ 2 | 3 | # Intution :- 4 | # For each dice n, we need to consider k possible values 5 | # and include the ones that equal to target 6 | # We can avoid revisiting the same state by caching the results for tuple (n, target) 7 | 8 | class Solution: 9 | def numRollsToTarget(self, n: int, k: int, target: int) -> int: 10 | dp = defaultdict(int) 11 | def dfs(n, k, target): 12 | # checks if already visited 13 | if (n, target) in dp: return dp[(n, target)] 14 | # no need to continue if target can't be achieved 15 | if target < 0: return 0 16 | if n == 0: return 1 if target == 0 else 0 17 | ways = 0 18 | for i in range(1, k + 1): 19 | # for a given dice, check for all k possibilites 20 | ways += dfs(n - 1, k, target - i) 21 | # cache the result 22 | dp[(n, target)] = ways 23 | return ways % (10 ** 9 + 7) 24 | return dfs(n, k, target) 25 | -------------------------------------------------------------------------------- /Leetcode-Solutions/DP/ugly-Number-II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int nthUglyNumber(int n) { 3 | if (n <= 0){ 4 | return 0; 5 | } 6 | List uglyNums = new ArrayList(); 7 | uglyNums.add(1); 8 | 9 | int i2 = 0; 10 | int i3= 0; 11 | int i5= 0; 12 | 13 | while (uglyNums.size() < n) { 14 | int y2 = uglyNums.get(i2) * 2; 15 | int y3 = uglyNums.get(i3) * 3; 16 | int y5 = uglyNums.get(i5) * 5; 17 | 18 | int min = Math.min(y2, Math.min(y3, y5)); 19 | uglyNums.add(min); 20 | 21 | if (min == y2) 22 | i2++; 23 | if (min == y3) 24 | i3++; 25 | if (min == y5) 26 | i5++; 27 | } 28 | 29 | return uglyNums.get(uglyNums.size() - 1); 30 | } 31 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Graph/RottenOranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool valid(int x,int y,int n,int m){ 4 | if(x<0||y<0||x>=n||y>=m) 5 | return false; 6 | return true; 7 | } 8 | vector>dir={{0,1},{1,0},{0,-1},{-1,0}}; 9 | class dpair{ 10 | public: 11 | int x,y,t; 12 | dpair(int x,int y,int t){ 13 | this->x=x; 14 | this->y=y; 15 | this->t=t; 16 | } 17 | }; 18 | int orangesRotting(vector>& grid) { 19 | queueque; 20 | int n=grid.size(),m=grid[0].size(),count=0; 21 | for(int i=0;i0){ 31 | dpair* top=que.front(); 32 | que.pop(); 33 | ans=top->t; 34 | for(int d=0;d<4;d++){ 35 | int x=top->x+dir[d][0]; 36 | int y=top->y+dir[d][1]; 37 | if(valid(x,y,n,m) && grid[x][y]==1){ 38 | count--; 39 | grid[x][y]=2; 40 | que.push(new dpair(x,y,top->t+1)); 41 | } 42 | } 43 | } 44 | return count==0?ans:-1; 45 | } 46 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Graph/Routes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numBusesToDestination(vector>& routes, int S, int T) { 4 | int n=routes.size(); 5 | unordered_map>map; 6 | unordered_mapbus; 7 | vectorvis(n,false); 8 | for(int i=0;iarr; 12 | map[routes[i][j]]=arr; 13 | } 14 | map[routes[i][j]].push_back(i); 15 | bus[routes[i][j]]=false; 16 | } 17 | } 18 | queue>que; 19 | que.push({S,0}); 20 | bus[S]=true; 21 | while(que.size()>0){ 22 | pairtop=que.front(); 23 | que.pop(); 24 | if(top.first==T) 25 | return top.second; 26 | for(int i:map[top.first]){ 27 | if(!vis[i]){ 28 | vis[i]=true; 29 | for(int j=0;jset,set1; 4 | queue>que; 5 | void exists(string word,string endWord,int level){ 6 | for(int i=0;i& wordList) { 24 | if(wordList.size()==0) 25 | return 0; 26 | for(string s:wordList) 27 | set.insert(s); 28 | if(set.find(endWord)==set.end()) 29 | return 0; 30 | que.push({beginWord,1}); 31 | while(que.size()>0){ 32 | pairtop=que.front(); 33 | que.pop(); 34 | // cout<> restoreMatrix(vector& rowSum, vector& colSum) { 4 | int m = rowSum.size(), n = colSum.size(); 5 | vector> A(m, vector(n, 0)); 6 | for (int i = 0; i < m; ++i) { 7 | for (int j = 0 ; j < n; ++j) { 8 | A[i][j] = min(rowSum[i], colSum[j]); 9 | rowSum[i] -= A[i][j]; 10 | colSum[j] -= A[i][j]; 11 | } 12 | } 13 | return A; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Greedy/Minimum Add to Make Parentheses Valid.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minAddToMakeValid(string S) { 4 | if(S=="" || S==" ") return 0; 5 | int count=0; 6 | stack s; 7 | for(int i=0;i& arr) { 4 | int n=arr.size(); 5 | int count=0; 6 | map m; 7 | for(int i=0;i freq; 12 | map::iterator itr; 13 | for(itr=m.begin();itr!=m.end();itr++) 14 | { 15 | freq.push_back(itr->second); 16 | } 17 | sort(freq.begin(), freq.end(), greater()); 18 | int sum=0; 19 | while(sumnext==NULL){ 15 | return false; 16 | } 17 | ListNode *slow=head,*fast=head->next; 18 | while(slow!=fast){ 19 | if(fast==NULL or fast->next==NULL){ 20 | return false; 21 | } 22 | else{ 23 | slow=slow->next; 24 | fast=fast->next->next; 25 | } 26 | } 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/19-Remove-Nth-Node-From-End-of-List.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* removeNthFromEnd(ListNode* head, int n) { 16 | 17 | if(head==NULL or head->next==NULL){ 18 | head=NULL; 19 | return head; 20 | } 21 | int size=0; 22 | ListNode*temp=head; 23 | while(temp!=NULL){ 24 | temp=temp->next; 25 | size++; 26 | } 27 | if(size==n){ 28 | return head->next; 29 | } 30 | 31 | 32 | ListNode*last=head; 33 | while(n--){ 34 | if(last->next!=NULL){ 35 | last=last->next; 36 | } 37 | } 38 | ListNode*pre=head; 39 | while(last->next!=NULL){ 40 | if(pre->next!=NULL){ 41 | pre=pre->next; 42 | } 43 | 44 | last=last->next; 45 | } 46 | 47 | pre->next=pre->next->next; 48 | 49 | return head; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/206-Reverse-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* reverseList(ListNode* head) { 16 | // this one is iterative 17 | ListNode* pre=NULL; 18 | ListNode* curr=head; 19 | while(curr!=NULL){ 20 | ListNode* temp=curr->next; 21 | curr->next=pre; 22 | pre=curr;curr=temp; 23 | 24 | } 25 | 26 | return pre; 27 | 28 | // // this is recursive 29 | 30 | // if(head==NULL or head->next==NULL){ 31 | // return head; 32 | // } 33 | 34 | // ListNode* newhead=reverseList(head->next); 35 | 36 | // ListNode* curr= head; 37 | // curr->next->next=curr; 38 | // curr->next=NULL; 39 | // return newhead; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/21-Merge-Two-Sorted-Lists.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode() : val(0), next(nullptr) {} 8 | * ListNode(int x) : val(x), next(nullptr) {} 9 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 15 | if(l1==NULL){ 16 | return l2; 17 | } 18 | if(l2==NULL){ 19 | return l1; 20 | } 21 | ListNode* newnode; 22 | if(l1->valval){ 23 | newnode=l1; 24 | newnode->next=mergeTwoLists(l1->next,l2); 25 | }else{ 26 | newnode=l2; 27 | newnode->next=mergeTwoLists(l1,l2->next); 28 | } 29 | return newnode; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/237-Delete-Node-in-a-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void deleteNode(ListNode* node) { 14 | node->val=node->next->val; 15 | node->next=node->next->next; 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/24-Swap-Nodes-in-Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapPairs(ListNode* head) { 4 | if(head==NULL || head->next==NULL) 5 | return head; 6 | ListNode *curr=head->next->next,*prev=head,*next; 7 | head=head->next; 8 | head->next=prev; 9 | while(curr!=NULL && curr->next!=NULL) 10 | { 11 | prev->next=curr->next; 12 | prev=curr; 13 | next=curr->next->next; 14 | curr->next->next=curr; 15 | curr=next; 16 | } 17 | prev->next=curr; 18 | return head; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/61-Rotate-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if(head==NULL || head->next==NULL) 5 | return head; 6 | int len=0; 7 | ListNode* ptr=head,*temp=head; 8 | while(ptr!=NULL) 9 | { 10 | len++; 11 | ptr=ptr->next; 12 | } 13 | k%=len; 14 | if(k==0) 15 | return head; 16 | k=len-k; 17 | ptr=head; 18 | while(ptr!=NULL && ptr->next!=NULL) 19 | { 20 | k--; 21 | if(k==0) 22 | { 23 | temp=ptr->next; 24 | ptr->next=NULL; 25 | ptr=temp; 26 | } 27 | else 28 | ptr=ptr->next; 29 | } 30 | ptr->next=head; 31 | // head=temp; 32 | return temp; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/83-Remove-Duplicates-from-Sorted-List.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* deleteDuplicates(ListNode* head) { 16 | ListNode* curr=head; 17 | while(curr!=NULL and curr->next!=NULL){ 18 | if(curr->val==curr->next->val){ 19 | curr->next=curr->next->next; 20 | } 21 | else{ 22 | curr=curr->next; 23 | } 24 | 25 | } 26 | 27 | return head; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/86-Partition-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* partition(ListNode* head, int x) { 4 | if(head==NULL || head->next==NULL) 5 | return head; 6 | ListNode* first=NULL,*second=NULL,*ptr=head,*ans=NULL,*ans1=NULL; 7 | while(ptr!=NULL) 8 | { 9 | if(ptr->valnext=ptr; 19 | first=first->next; 20 | } 21 | } 22 | else 23 | { 24 | if(second==NULL) 25 | { 26 | second=ptr; 27 | ans1=second; 28 | } 29 | else 30 | { 31 | second->next=ptr; 32 | second=second->next; 33 | } 34 | } 35 | ptr=ptr->next; 36 | } 37 | if(first!=NULL) 38 | first->next=ans1; 39 | else 40 | ans=ans1; 41 | if(second!=NULL) 42 | second->next=NULL; 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/876-Middle-of-the-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* middleNode(ListNode* head) { 16 | ListNode* mid=head; 17 | ListNode* fast=head; 18 | while(fast->next!=NULL ){ 19 | mid=mid->next; 20 | if(fast->next->next!=NULL){ 21 | fast=fast->next->next; 22 | } 23 | else{ 24 | fast=fast->next; 25 | } 26 | 27 | } 28 | return mid; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Copy-List-With-Random-Pointer.cpp: -------------------------------------------------------------------------------- 1 | static auto x = []() {ios_base::sync_with_stdio(false); cin.tie(NULL); return NULL; }(); 2 | class Solution { 3 | public: 4 | Node* copyRandomList(Node* head) { 5 | if(head==NULL) return NULL; 6 | unordered_mapm; 7 | Node * temp; 8 | Node * newNode = new Node(head->val); 9 | temp = newNode; 10 | m[head] = newNode; 11 | Node * hd = temp; 12 | head = head->next; 13 | while(head!=NULL){ 14 | Node* newNode = new Node(head->val); 15 | temp->next = newNode; 16 | m[head] = newNode; 17 | head=head->next; 18 | temp=temp->next; 19 | } 20 | for(auto i : m){ 21 | if(i.first->random==NULL) i.second->random = NULL; 22 | else{ 23 | i.second->random = m[i.first->random]; 24 | } 25 | } 26 | return hd; 27 | } 28 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Linked-List-Cycle-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *detectCycle(ListNode *head) { 4 | if(!head) return NULL; 5 | if(head->next==NULL) return NULL; 6 | ListNode * fast = head; 7 | ListNode * slow = head; 8 | while(fast and fast->next){ 9 | fast = fast->next->next; 10 | slow = slow->next; 11 | if(fast==slow) break; 12 | } 13 | if(fast==NULL or fast->next==NULL) return NULL; 14 | slow = head; 15 | while(slow!=fast){ 16 | slow = slow->next; 17 | fast = fast->next; 18 | } 19 | return slow; 20 | } 21 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Odd-Even-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | if (head == NULL || head->next == NULL || head->next->next == NULL) return head; 5 | ListNode* odd = head, *evenHead = head->next, *even = head->next; 6 | while (even != NULL && even->next != NULL) { 7 | odd = odd->next = even->next; 8 | even = even->next = even->next->next; 9 | } 10 | odd->next = evenHead; 11 | return head; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Palindrome-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(ListNode* head) { 4 | ListNode* slowp = head; 5 | ListNode* fastp = head; 6 | ListNode* revp = NULL; 7 | while (fastp && fastp->next){ 8 | fastp = fastp->next->next; 9 | ListNode* tmp = slowp->next; 10 | slowp->next = revp; 11 | revp = slowp; 12 | slowp = tmp; 13 | } 14 | if (fastp) slowp = slowp->next; 15 | while (slowp && revp){ 16 | if (slowp->val != revp->val) return false; 17 | slowp = slowp->next; 18 | revp = revp->next; 19 | } 20 | return true; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Remove_Linked_List_Elements.cpp: -------------------------------------------------------------------------------- 1 | ListNode* removeElements(ListNode* head, int val) { 2 | if(!head) return head; 3 | 4 | ListNode* node = head; 5 | while(node && node -> next) 6 | { 7 | if(node -> next -> val == val) 8 | node -> next = node -> next -> next; 9 | else 10 | node = node -> next; 11 | } 12 | 13 | if(head -> val == val) 14 | head = head -> next; 15 | 16 | return head; 17 | } 18 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/Reorder-List.cpp: -------------------------------------------------------------------------------- 1 | static auto x = []() {ios_base::sync_with_stdio(false); cin.tie(NULL); return NULL; }(); 2 | class Solution { 3 | public: 4 | void reorderList(ListNode* head) { 5 | dequeq; 6 | while(head!=NULL){ 7 | q.push_back(head); 8 | head = head->next; 9 | } 10 | while(!q.empty()){ 11 | if(q.size()<=2) break; 12 | ListNode * front = q.front(); 13 | ListNode * back = q.back(); 14 | q.pop_front(); 15 | q.pop_back(); 16 | q.back()->next=NULL; 17 | ListNode * hm = front->next; 18 | front->next = back; 19 | back->next = hm; 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/linked-list-cycle_C++.cpp: -------------------------------------------------------------------------------- 1 | 141. Linked List Cycle 2 | 3 | Given head, the head of a linked list, determine if the linked list has a cycle in it. 4 | 5 | There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. 6 | 7 | Return true if there is a cycle in the linked list. Otherwise, return false. 8 | 9 | Follow up: 10 | 11 | Can you solve it using O(1) (i.e. constant) memory? 12 | 13 | 14 | 15 | Example 1: 16 | 17 | 18 | Input: head = [3,2,0,-4], pos = 1 19 | Output: true 20 | Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). 21 | Example 2: 22 | 23 | 24 | Input: head = [1,2], pos = 0 25 | Output: true 26 | Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. 27 | Example 3: 28 | 29 | 30 | Input: head = [1], pos = -1 31 | Output: false 32 | Explanation: There is no cycle in the linked list. 33 | 34 | 35 | Constraints: 36 | 37 | The number of the nodes in the list is in the range [0, 104]. 38 | -105 <= Node.val <= 105 39 | pos is -1 or a valid index in the linked-list. -------------------------------------------------------------------------------- /Leetcode-Solutions/Linked-List/palindrome-linked-list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(ListNode* head) { 4 | ListNode* slowp = head; 5 | ListNode* fastp = head; 6 | ListNode* revp = NULL; 7 | while (fastp && fastp->next){ 8 | fastp = fastp->next->next; 9 | ListNode* tmp = slowp->next; 10 | slowp->next = revp; 11 | revp = slowp; 12 | slowp = tmp; 13 | } 14 | if (fastp) slowp = slowp->next; 15 | while (slowp && revp){ 16 | if (slowp->val != revp->val) return false; 17 | slowp = slowp->next; 18 | revp = revp->next; 19 | } 20 | return true; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/CopyListWithRandomPointers1_Java.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class Clone { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | // using o(n) extra space 10 | Node copyList(Node head) { 11 | // your code here 12 | HashMap map=new HashMap<>(); 13 | Node t=head.next; 14 | Node clist=new Node(head.data); 15 | Node t2=clist; 16 | map.put(head,head.arb); 17 | while(t!=null){ 18 | Node temp=new Node(t.data); 19 | t2.next=temp; 20 | t2=t2.next; 21 | map.put(t,t.arb); 22 | t=t.next; 23 | } 24 | 25 | Node curr=clist; 26 | Node sh=head; 27 | while(curr!=null){ 28 | 29 | curr.arb=map.get(sh); 30 | 31 | sh=sh.next; 32 | curr=curr.next; 33 | } 34 | 35 | return clist; 36 | // without using any extra space 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/CopyListWithRandomPointers2_Java.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class CloneWithoutHM { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | public Node copyRandomList(Node head) { 10 | if(head==null) return head; 11 | // make 12 | 13 | Node tempo=head; 14 | while(tempo!=null){ 15 | Node curr=new Node(tempo.val); 16 | curr.next=tempo.next; 17 | tempo.next=curr; 18 | tempo=tempo.next.next; 19 | } 20 | 21 | //asign random pointers 22 | tempo=head; 23 | Node tempn=head.next; 24 | while(tempo!=null){ 25 | 26 | tempn.random=tempo.random==null?null:tempo.random.next; 27 | tempo=tempn.next; 28 | if(tempo!=null) 29 | tempn=tempo.next; 30 | } 31 | 32 | // break the links 33 | 34 | Node nhead=head.next; 35 | tempo=head; 36 | tempn=nhead; 37 | while(tempo!=null){ 38 | tempo.next=tempn.next; 39 | if(tempo.next!=null){ 40 | tempn.next=tempo.next.next; 41 | } 42 | tempo=tempo.next; 43 | tempn=tempn.next; 44 | } 45 | return nhead; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/IntersectionOfTwoLinkedLists.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class Intersection { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 10 | if(headA==null || headB==null){ 11 | return null; 12 | } 13 | ListNode a=headA; 14 | ListNode b=headB; 15 | int sa=1; 16 | int sb=1; 17 | while(a.next!=null){ 18 | sa++; 19 | a=a.next; 20 | } 21 | while(b.next!=null){ 22 | sb++; 23 | b=b.next; 24 | } 25 | 26 | //humesha a size ke diff se chlega 27 | int skip=Math.abs(sa-sb); 28 | if(sa>sb){ 29 | a=headA; 30 | b=headB; 31 | for(int i=1;i<=skip;i++){ 32 | a=a.next; 33 | } 34 | 35 | 36 | }else{ 37 | a=headB; 38 | b=headA; 39 | for(int i=1;i<=skip;i++){ 40 | a=a.next; 41 | } 42 | } 43 | while(a!=b){ 44 | a=a.next; 45 | b=b.next; 46 | } 47 | return a; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/OddEvenLinkedLists_Java.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class OddEven { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | public ListNode oddEvenList(ListNode head) { 10 | if(head==null) return null; 11 | 12 | int count=3; 13 | ListNode curr=head; 14 | ListNode ohead=head; 15 | ListNode otail=head; 16 | ListNode ehead=head.next; 17 | ListNode etail=head.next; 18 | if(etail==null ||etail.next==null){ 19 | return head; 20 | } 21 | curr=head.next.next; 22 | while(curr!=null){ 23 | if(count%2==0){ 24 | // case of even 25 | etail.next=curr; 26 | etail=etail.next; 27 | 28 | }else{ 29 | //case of odd 30 | otail.next=curr; 31 | otail=otail.next; 32 | } 33 | curr=curr.next; 34 | count++; 35 | } 36 | etail.next=null; 37 | otail.next=ehead; 38 | return ohead; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/RemoveDuplicatesFromSortedList_Java.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class DeleteDuplicates { 4 | 5 | public ListNode deleteDuplicates(ListNode head) { 6 | if(head==null || head.next==null){ 7 | return head; 8 | } 9 | ListNode dummy=new ListNode(-1); 10 | dummy.next=head; 11 | 12 | ListNode pprev=dummy; 13 | ListNode prev=head; 14 | ListNode curr=head.next; 15 | 16 | while(prev!=null && curr!=null){ 17 | 18 | if(curr.val==prev.val){ 19 | ListNode temp=curr.next; 20 | while(temp!=null && temp.val==curr.val){ 21 | temp=temp.next; 22 | } 23 | pprev.next=temp; 24 | prev=temp; 25 | if(temp!=null){ 26 | curr=temp.next; 27 | } 28 | 29 | }else{ 30 | pprev=prev; 31 | prev=curr; 32 | curr=curr.next; 33 | 34 | } 35 | } 36 | return dummy.next; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/RemoveNthNodeFromEndOfList_Java.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class removeNFromLast { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | // using 1 pass solution 10 | public ListNode removeNthFromEnd(ListNode head, int n) { 11 | if(head==null) return null; 12 | if(head.next==null) return null; 13 | 14 | 15 | ListNode first=head.next;// first node tell the distance .. when it is null,then second is at the deleted position 16 | ListNode second=head;// second node depicts the node which to be deleted 17 | ListNode prev=null; // prev is the prev node of the seconf node 18 | for(int i=1;its/2){ 24 | ListNode n=curr.next; 25 | curr.next=head; 26 | head.next=n; 27 | curr=n; 28 | }else if(size==ts/2){ 29 | curr.next=null; 30 | } 31 | 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/ReverseLinkedList2.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class ReverseMtoN { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | 10 | public ListNode reverseBetween(ListNode head, int m, int n) { 11 | if(head==null || head.next==null || m==n) return head; 12 | 13 | ListNode dummy=new ListNode(-1); 14 | dummy.next=head; 15 | int count=1; 16 | ListNode curr=head; 17 | ListNode prev=dummy; 18 | while(curr!=null && count 0) { 28 | temp = temp.next; 29 | } 30 | ListNode tempn = temp.next; 31 | temp.next = null; 32 | 33 | ListNode rec = reverse(tempn, count - k, k); 34 | 35 | // here there is a need rto reverse the linklist 36 | if (k > 1) { 37 | ListNode a = head; 38 | ListNode b = head.next; 39 | ListNode cn = head.next == null ? null : b.next; 40 | while (b != null) { 41 | b.next = a; 42 | a = b; 43 | b = cn; 44 | if (cn != null) 45 | cn = cn.next; 46 | } 47 | } 48 | // then make the necessary attachments 49 | head.next = rec; 50 | 51 | return temp; 52 | } 53 | 54 | public int size(ListNode head) { 55 | if (head == null) 56 | return 0; 57 | 58 | int si = 1; 59 | ListNode curr = head; 60 | while (curr.next != null) { 61 | si++; 62 | curr = curr.next; 63 | } 64 | return si; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Leetcode-Solutions/LinkedList/RotateLinkedLists.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | public class RotateLinkedLists { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | public ListNode rotateRight(ListNode head, int k) { 10 | if( head==null || head.next==null){ 11 | return head; 12 | } 13 | 14 | int size=0; 15 | 16 | ListNode curr=head; 17 | while(curr!=null){ 18 | size++; 19 | curr=curr.next; 20 | } 21 | k=k%size; 22 | if(k==0){ 23 | return head; 24 | } 25 | k=size-k; 26 | 27 | ListNode prev=null; 28 | curr=head; 29 | int i=1; 30 | while(curr.next!=null){ 31 | if(i<=k){ 32 | prev=curr; 33 | } 34 | i++; 35 | curr=curr.next; 36 | } 37 | ListNode nhead=prev.next; 38 | prev.next=null; 39 | 40 | curr.next=head; 41 | return nhead; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Matrix/spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question #54 3 | url - https://leetcode.com/problems/spiral-matrix/ 4 | Coded by - Shadman Afzal 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Solution 11 | { 12 | public: 13 | vector spiralOrder(vector> &matrix) 14 | { 15 | 16 | vector result; 17 | 18 | int a = 0, b = 0, c = matrix.size() - 1, d = matrix[0].size() - 1; 19 | 20 | while (a <= c and b <= d) 21 | { 22 | for (int i = b; i <= d; i++) 23 | { 24 | result.push_back(matrix[a][i]); 25 | } 26 | a++; 27 | 28 | for (int i = a; i <= c; i++) 29 | result.push_back(matrix[i][d]); 30 | d--; 31 | 32 | if (a <= c) 33 | { 34 | for (int i = d; i >= b; i--) 35 | result.push_back(matrix[c][i]); 36 | c--; 37 | } 38 | 39 | if (b <= d) 40 | { 41 | for (int i = c; i >= a; i--) 42 | result.push_back(matrix[i][b]); 43 | b++; 44 | } 45 | } 46 | 47 | return result; 48 | } 49 | }; 50 | 51 | int main() 52 | { 53 | Solution sol = Solution(); 54 | vector> matrix{ 55 | {1, 2, 3}, 56 | {4, 5, 6}, 57 | {7, 8, 9}, 58 | }; 59 | 60 | vector result = sol.spiralOrder(matrix); 61 | 62 | for (int i : result) 63 | { 64 | cout << i << " "; 65 | } 66 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/Defanging-an-ip-address.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string defangIPaddr(string address) { 4 | 5 | string s=""; 6 | for(int i=0;i= 'A' && word.charAt(i)<='Z') 7 | return false; 8 | } 9 | return true; 10 | } 11 | } -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/Detect-Captital.cpp: -------------------------------------------------------------------------------- 1 | /* Given a word, you need to judge whether the usage of capitals in it is right or not. 2 | 3 | We define the usage of capitals in a word to be right when one of the following cases holds: 4 | 5 | 1. All letters in this word are capitals, like "USA". 6 | 2. All letters in this word are not capitals, like "leetcode". 7 | 3. Only the first letter in this word is capital, like "Google". 8 | 9 | Otherwise, we define that this word doesn't use capitals in a right way. 10 | 11 | Example 1: 12 | 13 | Input: "USA" 14 | Output: True 15 | 16 | Example 2: 17 | 18 | Input: "FlaG" 19 | Output: False 20 | 21 | Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. */ 22 | 23 | //SOLUTION 24 | bool detectCapitalUse(string word) { 25 | int count=0; 26 | for(int i=0;i=0){ 28 | count++; 29 | } 30 | } 31 | if(count==word.length()||count==0||count==1 && word[0]-'A'<=27 && word[0]-'A'>=0) 32 | return true; 33 | return false; 34 | } 35 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/Longest_Substring_Length.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | int lengthOfLongestSubstring(string s) 5 | { 6 | int maxlen = 0; 7 | for(int i=0; i<=s.length(); i++) 8 | { 9 | bool repeated = 0; 10 | for(int j = 0; j+i<=s.length(); j++) 11 | { 12 | string substring = s.substr(i,j); 13 | repeated = is_non_repeated_string(substring); 14 | if (repeated) 15 | break; 16 | update(substring, maxlen); 17 | } 18 | } 19 | return maxlen; 20 | } 21 | bool is_non_repeated_string(string s) 22 | { 23 | map m; 24 | for(int i = 0; i <= s.length(); i++) 25 | { 26 | pair p(s[i], 1); 27 | auto search = m.find(s[i]); 28 | if (search != m.end()){ 29 | return 1; 30 | } 31 | m.insert(p); 32 | } 33 | return 0; 34 | } 35 | void update(string s, int& maxlen) 36 | { 37 | if(s.length() > maxlen) 38 | { 39 | maxlen = s.length(); 40 | } 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/To-lower-case_C ++.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string toLowerCase(string str) { 4 | for(int i=0;i='0' && s[i]<='9'||s[i]>='a' && s[i]<='z') 29 | str+=s[i]; 30 | } 31 | int i=0,j=str.length()-1; 32 | while(i<=j){ 33 | if(str[i++]!=str[j--]) 34 | return false; 35 | } 36 | return true; 37 | } 38 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/longestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestCommonPrefix(String[] strs) { 3 | 4 | // Declare a string, which will return the longest prefix 5 | String longestPrefix = ""; 6 | 7 | // Return null if the string is empty 8 | if (strs == null || strs.length == 0) { 9 | return longestPrefix; 10 | } 11 | 12 | for (int j = 0; j < strs[0].length(); j++) { 13 | 14 | /** 15 | * 16 | * Return from the function if: - we reach the end of a string or - in the event 17 | * of an incorrect match 18 | * 19 | */ 20 | 21 | for (int i = 1; i < strs.length; i++) { 22 | if (j >= strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)) { 23 | return longestPrefix; 24 | } 25 | } 26 | 27 | // Append the character to the longest prefix 28 | longestPrefix += strs[0].charAt(j); 29 | } 30 | 31 | // Return the longest prefix 32 | return longestPrefix; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/maxOccurrence.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to output the maximum occurring character 2 | // in a string 3 | 4 | #include 5 | #define ASCII_SIZE 256 6 | using namespace std; 7 | 8 | char getMaxOccuringChar(char* str) 9 | { 10 | // Create array to keep the count of individual 11 | // characters and initialize the array as 0 12 | int count[ASCII_SIZE] = {0}; 13 | 14 | // Construct character count array from the input 15 | // string. 16 | int len = strlen(str); 17 | int max = 0; // Initialize max count 18 | char result; // Initialize result 19 | 20 | // Traversing through the string and maintaining 21 | // the count of each character 22 | for (int i = 0; i < len; i++) { 23 | count[str[i]]++; 24 | if (max < count[str[i]]) { 25 | max = count[str[i]]; 26 | result = str[i]; 27 | } 28 | } 29 | 30 | return result; 31 | } 32 | 33 | // Driver program to test the above function 34 | int main() 35 | { 36 | char str[] = "sample string"; 37 | cout << "Max occurring character is " 38 | << getMaxOccuringChar(str); 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Strings/romantointeger.py: -------------------------------------------------------------------------------- 1 | #roman to integer 2 | 3 | class Solution: 4 | def romanToInt(self, s: str) -> int: 5 | s1={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000} 6 | s2=0 7 | for i in range (len(s)): 8 | if i+1 vs; 5 | 6 | void path(TreeNode* root, string s) 7 | { 8 | if(root==NULL) return; 9 | 10 | if(root->left or root->right) 11 | s += to_string(root->val) + "->"; 12 | else 13 | s += to_string(root->val); 14 | 15 | if(!root->left and !root->right) 16 | vs.push_back(s); 17 | 18 | path(root->left,s); 19 | path(root->right,s); 20 | } 21 | 22 | vector binaryTreePaths(TreeNode* root) { 23 | 24 | if(root==NULL) return {}; 25 | 26 | path(root,""); 27 | return vs; 28 | } 29 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Tree/96-Unique-Binary-Search-Trees.cpp: -------------------------------------------------------------------------------- 1 | //Contributed by: Rishabh Jain 2 | //this one is a pure dp soln. 3 | class Solution { 4 | public: 5 | int numTrees(int n) 6 | {int dp[n+1]; 7 | memset(dp,0,sizeof(dp)); 8 | dp[0]=1; 9 | dp[1]=1; 10 | dp[2]=2; 11 | dp[3]=5; 12 | 13 | for(int i=4;i<=n;i++) 14 | { 15 | for(int j=1;j<=i;j++) 16 | { 17 | dp[i]+=dp[j-1]*dp[i-j]; 18 | } 19 | } 20 | return dp[n]; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Tree/Path-Sum3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the number of paths that sum to a given value. 3 | 4 | The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). 5 | 6 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 7 | 8 | Example: 9 | 10 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 11 | 12 | 10 13 | / \ 14 | 5 -3 15 | / \ \ 16 | 3 2 11 17 | / \ \ 18 | 3 -2 1 19 | 20 | Return 3. The paths that sum to 8 are: 21 | 22 | 1. 5 -> 3 23 | 2. 5 -> 2 -> 1 24 | 3. -3 -> 11 25 | */ 26 | 27 | 28 | //SOLUTION 29 | class Solution { 30 | int pathSum_a(TreeNode* root, int sum){ 31 | if(root == nullptr) return 0; 32 | int res = 0; 33 | if(root->val == sum) res++; 34 | res += pathSum_a(root->left, sum-root->val); 35 | res += pathSum_a(root->right, sum-root->val); 36 | return res; 37 | } 38 | public: 39 | int pathSum(TreeNode* root, int sum) { 40 | if(root == nullptr) return 0; 41 | return pathSum(root->left, sum) + pathSum_a(root, sum) + pathSum(root->right, sum); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Leetcode-Solutions/Tree/Path_Sum3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the number of paths that sum to a given value. 3 | 4 | The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). 5 | 6 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 7 | 8 | Example: 9 | 10 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 11 | 12 | 10 13 | / \ 14 | 5 -3 15 | / \ \ 16 | 3 2 11 17 | / \ \ 18 | 3 -2 1 19 | 20 | Return 3. The paths that sum to 8 are: 21 | 22 | 1. 5 -> 3 23 | 2. 5 -> 2 -> 1 24 | 3. -3 -> 11 25 | */ 26 | 27 | 28 | //SOLUTION 29 | class Solution { 30 | int pathSum_a(TreeNode* root, int sum){ 31 | if(root == nullptr) return 0; 32 | int res = 0; 33 | if(root->val == sum) res++; 34 | res += pathSum_a(root->left, sum-root->val); 35 | res += pathSum_a(root->right, sum-root->val); 36 | return res; 37 | } 38 | public: 39 | int pathSum(TreeNode* root, int sum) { 40 | if(root == nullptr) return 0; 41 | return pathSum(root->left, sum) + pathSum_a(root, sum) + pathSum(root->right, sum); 42 | } 43 | }; -------------------------------------------------------------------------------- /Leetcode-Solutions/Tree/equal-tree-partition.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | /** 3 | * @param root: a TreeNode 4 | * @return: return a boolean 5 | */ 6 | public class pair{ 7 | 8 | boolean found=false; 9 | int sum=0; 10 | pair(int sum,boolean found){ 11 | this.sum=sum; 12 | this.found=found; 13 | } 14 | pair(){ 15 | 16 | } 17 | } 18 | public boolean checkEqualTree(TreeNode root){ 19 | // write your code here 20 | int tsum=sum(root); 21 | pair ans=findhalf(root,tsum,root); 22 | return ans.found; 23 | } 24 | 25 | public pair findhalf(TreeNode root,int tsum,TreeNode oroot){ 26 | if(root==null) return new pair(0,false); 27 | pair left=findhalf(root.left,tsum,oroot); 28 | pair right=findhalf(root.right,tsum,oroot); 29 | pair mypair=new pair(); 30 | mypair.sum=left.sum+right.sum+root.val; 31 | 32 | if(root!=oroot){ 33 | mypair.found=(left.found || right.found || mypair.sum*2==tsum); 34 | }else{ 35 | mypair.found=(left.found || right.found); 36 | } 37 | 38 | return mypair; 39 | } 40 | 41 | public int sum(TreeNode root){ 42 | if(root==null) return 0; 43 | return sum(root.left)+sum(root.right)+root.val; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Logarithmic-tricks/Count-digits-of-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define llu long long unsigned 5 | 6 | //Function to count digits of number entered by user 7 | llu countDigitsOfNumber(llu n){ 8 | return floor(log10(n) + 1); 9 | } 10 | 11 | //main function 12 | int main() 13 | { 14 | llu n; 15 | cout<<"Enter number: \n"; 16 | cin>>n; 17 | cout< 5 | using namespace std; 6 | 7 | #define llu long long unsigned 8 | 9 | //Function to check if a number is power of two or not 10 | bool numberIsPowerOfTwo(llu n){ 11 | return (ceil(log2(n)) == floor(log2(n))); 12 | } 13 | 14 | //main function 15 | int main() 16 | { 17 | cout<<"Enter number: \n"; 18 | llu n; 19 | cin>>n; 20 | if(numberIsPowerOfTwo(n)) 21 | cout<<"YES\n"; 22 | else 23 | cout<<"NO\n"; 24 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/Countdigitsinanumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char **argv){ 5 | int n; 6 | cin >> n; 7 | int c=0; 8 | while(n!=0){ 9 | c++; 10 | n/=10; 11 | } 12 | cout< 2 | using namespace std; 3 | 4 | int main(int argc, char **argv) 5 | { 6 | int n; 7 | cin >> n; 8 | int t = n, c = 0; 9 | while (t != 0) 10 | { 11 | t /= 10; 12 | c++; 13 | } 14 | long long int x = 1; 15 | while (c != 1) 16 | { 17 | x = x * 10; 18 | c--; 19 | } 20 | while (x != 0) 21 | { 22 | cout << n / x << endl; 23 | n = n % x; 24 | x /= 10; 25 | } 26 | 27 | //write your code here 28 | } 29 | -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/Inverse-a-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool sortcompare(pair& a,pair& b){ 6 | return a.second> n; 14 | long long int t = 10; 15 | int x = n, c = 0,m=0; 16 | while (x != 0) 17 | { 18 | c++; 19 | x /= 10; 20 | } 21 | x = 1; 22 | m=c; 23 | pair p[c+1]; 24 | c++; 25 | while (c--) 26 | { 27 | p[x].first=x; 28 | p[x].second=(n % t) * 10 / t; 29 | t *= 10; 30 | x++; 31 | } 32 | 33 | sort(p,p+m+1,sortcompare); 34 | for(int i=m;i>=1;i--){ 35 | cout< 2 | using namespace std; 3 | int main(int argc, char **argv) 4 | { 5 | int n; 6 | cin >> n; 7 | while (n % 2 == 0) 8 | { 9 | cout << 2 << " "; 10 | n /= 2; 11 | } 12 | for (int i = 3; n != 1; i += 2) 13 | { 14 | while (n % i == 0) 15 | { 16 | cout << i << " "; 17 | n /= i; 18 | } 19 | } 20 | //write your code here 21 | } 22 | -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/PrintAllPrimesTillN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int a[1000001]; 6 | memset(a, 0, sizeof(a)); 7 | for (int i = 2; i <= sqrt(1e6); i++) 8 | { 9 | if (a[i] == 0) 10 | { 11 | for (int j = i * i; j <= 1e6; j += i) 12 | { 13 | 14 | a[j] = 1; 15 | } 16 | } 17 | } 18 | int l, h; 19 | cin >> l >> h; 20 | for (int i = l; i <= h; i++) 21 | { 22 | if (!a[i]) 23 | { 24 | cout << i << endl; 25 | } 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/PrintFabonacciNumbersTillN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char **argv) 5 | { 6 | int n; 7 | cin >> n; 8 | int a=0,b=1; 9 | int c=a+b; 10 | cout< 2 | using namespace std; 3 | 4 | int main(int argc, char **argv) 5 | { 6 | int a, b, c; 7 | cin >> a >> b >> c; 8 | if ((a * a + b * b) == (c * c)) 9 | { 10 | cout << "true"; 11 | } 12 | else if ((c * c + b * b) == (a * a)) 13 | { 14 | cout << "true"; 15 | } 16 | else if ((a * a + c * c) == (b * b)) 17 | { 18 | cout << "true"; 19 | } 20 | else 21 | { 22 | cout << "false"; 23 | } 24 | //write your code here 25 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/Reverse-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char **argv) 5 | { 6 | int n; 7 | cin >> n; 8 | long long int t = 10; 9 | int x = n, c = 0; 10 | while (x != 0) 11 | { 12 | c++; 13 | x /= 10; 14 | } 15 | while (c--) 16 | { 17 | cout << ((n % t) * 10 / t) << endl; 18 | t *= 10; 19 | } 20 | //write your code here 21 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/Rotate-a-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int main() 6 | { 7 | long long int n, k; 8 | cin >> n >> k; 9 | if (k >= n) 10 | { 11 | k = k % n; 12 | } 13 | long long int x = n, c = 0; 14 | while (x != 0) 15 | { 16 | c++; 17 | x /= 10; 18 | } 19 | long long int t = 1; 20 | long long int m = c - 1; 21 | while (m--) 22 | { 23 | t *= 10; 24 | } 25 | if (k > 0) 26 | { 27 | while (k--) 28 | { 29 | long long int p = n % 10; 30 | n /= 10; 31 | n = p * t + n; 32 | } 33 | } 34 | else 35 | { 36 | while (k++) 37 | { 38 | long long int q = n / t; 39 | n = n % t; 40 | n = n * 10 + q; 41 | } 42 | } 43 | cout << n << endl; 44 | 45 | //write your code here 46 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/The-curious-case-of-benjamin-bulbs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(int argc, char **argv) 4 | { 5 | int n; 6 | cin >> n; 7 | int i = 1; 8 | while ((i * i) <= n) 9 | { 10 | cout << (i * i) << endl; 11 | i++; 12 | } 13 | //write your code here 14 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/gcd-and-lcm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int gcdfind(int num1, int num2) 4 | { 5 | if (b == 0) 6 | { 7 | return a; 8 | } 9 | return gcdfind(b, a % b); 10 | } 11 | int main(int argc, char **argv) 12 | { 13 | int num1, num2; 14 | cin >> num1 >> num2; 15 | int gcd = gcdfind(num1, num2); 16 | //write your code here 17 | cout << gcd << endl; 18 | int lcm = (num1 * num2) / gcd; 19 | 20 | cout << lcm << endl; 21 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/GettingStarted/printZ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(int argc, char **agrc) 4 | { 5 | //write your code here 6 | cout << "*****" << endl; 7 | cout << " * " << endl; 8 | cout << " * " << endl; 9 | cout << " * " << endl; 10 | cout << "*****" << endl; 11 | } -------------------------------------------------------------------------------- /Pepcoding-level-1-list/Stack-and-queues/Stock-span.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | vector v; 11 | for (int i = 0; i < n; i++) 12 | { 13 | int x; 14 | cin >> x; 15 | v.push_back(x); 16 | } 17 | vector res; 18 | stack> st; 19 | for (int i = 0; i < n; i++) 20 | { 21 | while (!st.empty() && st.top().first < v[i]) 22 | { 23 | st.pop(); 24 | } 25 | res.push_back(st.empty() ? i + 1 : i - st.top().second); 26 | st.push({v[i], i}); 27 | } 28 | for (int i = 0; i < n; i++) 29 | { 30 | cout << res[i] << endl; 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Practice-codechef-solutions/Arrays/AMR15A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | cin>>n; 7 | int arr[n]; 8 | int c=0; 9 | int d=0; 10 | for(int i=0;i>arr[i]; 12 | if(arr[i]%2==0) 13 | c++; 14 | else 15 | d++; 16 | } 17 | if(c>d) 18 | cout<<"READY FOR BATTLE"; 19 | else 20 | cout<<"NOT READY"; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Practice-codechef-solutions/Arrays/ARRPROB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | int t;cin>>t; 7 | while(t--){ 8 | int n;cin>>n; 9 | int a[n]; 10 | long long s1=0; 11 | for(int i=0;i>a[i]; 13 | s1+=a[i]; 14 | } 15 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int T; 7 | cin>>T; 8 | while(T--) 9 | { 10 | int N, S = 0, mx = INT_MIN; 11 | cin>>N; 12 | 13 | while(N--) 14 | { 15 | int a; 16 | cin>>a; 17 | S += a; 18 | mx = max(mx, S); 19 | if (S < 0) 20 | S = 0; 21 | } 22 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | long int n,t; 6 | cin>>n; 7 | while(n--) 8 | { int total=0,count=0; 9 | cin>>t; 10 | int a[t]; 11 | for(int i=0;i>a[i]; 13 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | int main() { 6 | int t,n,k; 7 | cin>>t; 8 | while(t--) 9 | { 10 | int c=0; 11 | cin>>n>>k; 12 | int a[n]; 13 | for(int i=0;i>a[i]; 16 | if(a[i]>k) 17 | { 18 | i=i-1; 19 | n=n-1; 20 | } 21 | 22 | } 23 | 24 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned long long t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | unsigned long long a[3]; 10 | for(int i=0;i<3;i++) 11 | cin>>a[i]; 12 | sort(a,a+3); 13 | cout< 2 | #define int long long 3 | using namespace std; 4 | signed main(signed argc, const char * argv[]) { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n,k; cin >> n >> k; 9 | int ar[n]; 10 | for (int i = 0; i < n; i++) cin >> ar[i]; 11 | 12 | if (k <= n){ 13 | for (int i = 0; i < k; i++) ar[i] ^= ar[n-i-1]; 14 | for (int i = 0; i < n; i++) cout << ar[i] << " "; 15 | cout << endl; 16 | continue; 17 | } 18 | int times[n]; 19 | for (int i = 0; i < n; i++){ 20 | times[i] = (k/n); 21 | if (i < (k%n)) times[i]++; 22 | } 23 | for (int i = 0; i < n/2; i++){ 24 | int j = (n-i-1); 25 | int timei = min(times[i], times[j]); 26 | int timej = timei; 27 | int tot = timei+timej; 28 | int temp[3] = {ar[i]^ar[j], ar[i], ar[j]}; 29 | tot--; 30 | ar[j] = temp[tot%3]; 31 | ar[i] = temp[(tot-1)%3]; 32 | if (times[i] == times[j]) continue; 33 | if (times[j] < times[i]){ 34 | int ll = times[i]-times[j]; 35 | if (ll & 1) ar[i] = ar[i]^ar[j]; 36 | } else { 37 | int ll = times[j]-times[i]; 38 | if (ll & 1) ar[j] = ar[j]^ar[i]; 39 | } 40 | } 41 | if (n & 1) ar[n/2] = 0; 42 | for (int i = 0; i < n; i++) cout << ar[i] << " "; 43 | 44 | cout << endl; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Practice-codechef-solutions/Arrays/POGOSTCK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t,n,i,j,k; 6 | cin>>t; 7 | for(i=0;i>n; 11 | cin>>k; 12 | int arr[n]; 13 | for(j=0;j>arr[j]; 15 | max=arr[n-1]; 16 | for(j=0;j=0) 21 | { 22 | sum=sum+arr[temp]; 23 | if(sum>max) 24 | max=sum; 25 | temp=temp-k; 26 | } 27 | } 28 | cout< 3 | using namespace std; 4 | 5 | void solve(){ 6 | int n; 7 | cin>>n; 8 | long long int ele[n],maxH; 9 | cin>>ele[0]; 10 | long long int sum = ele[0]; 11 | if(ele[0]>1) 12 | ele[0] = 1; 13 | for(int i=1;i>temp; 16 | sum+=temp; 17 | if(temp > ele[i-1]+1) 18 | ele[i] = ele[i-1]+1; 19 | else 20 | ele[i] = temp; 21 | } 22 | 23 | ele[n-1] = 1; 24 | for(int i=n-2;i>=0;i--){ 25 | if(ele[i] > ele[i+1]+1) 26 | ele[i] = ele[i+1]+1; 27 | maxH = max(ele[i],maxH); 28 | } 29 | 30 | cout<>t; 41 | while(t--){ 42 | solve(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Practice-codechef-solutions/Arrays/STRLS1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | int n; 7 | cin>>n; 8 | string s; 9 | cin>>s; 10 | char arr[n]; 11 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned long long t,w; 6 | cin>>t; 7 | int a[t],b[t],c[t],l,s1=0,s2=0; 8 | for(int i=0;i>a[i]>>b[i]; 11 | s1=s1+a[i]; 12 | s2=s2+b[i]; 13 | if(s1>s2) 14 | { 15 | c[i]=s1-s2; 16 | } 17 | if(s2>s1) 18 | { 19 | c[i]=s2-s1; 20 | } 21 | } 22 | 23 | for(int i=0;ib[i]) 37 | w=1; 38 | else 39 | w=2; 40 | } 41 | } 42 | cout< 2 | using namespace std; 3 | 4 | 5 | int main() 6 | { 7 | // your code goes here 8 | int tweet, click; 9 | cin >> tweet >> click; 10 | int a[tweet] = {0}; 11 | for (int i = 0; i < click; i++) 12 | { 13 | string s; 14 | int n; 15 | cin >> s; 16 | 17 | if (s == "CLOSEALL") 18 | { 19 | for (int k = 0; k < tweet; k++) 20 | a[k] = 0; 21 | } 22 | else 23 | { 24 | cin >> n; 25 | 26 | if (a[n - 1] == 0) 27 | a[n - 1] = 1; 28 | else 29 | a[n - 1] = 0; 30 | } 31 | 32 | int sum = 0; 33 | for (int k = 0; k < tweet; k++) 34 | { 35 | sum += a[k]; 36 | } 37 | cout << sum << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Practice-codechef-solutions/Codechef Problem-Covid_Pandemic_and_Long_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | // your code goes here 7 | int t; 8 | cin>>t; 9 | for(int i=1;i<=t;i++) 10 | 11 | {std::vector a; 12 | int c=0; 13 | int n; 14 | cin>>n; 15 | vector arr; 16 | for(int i=0;i>ar; 19 | arr.push_back(ar); 20 | } 21 | for(int i=0;i0){ 8 | int n=scan.nextInt(); 9 | n--; 10 | 11 | long bits=1,nibbles=0,bytes=0; 12 | while(n>1) 13 | { 14 | 15 | if(n>=2) 16 | { 17 | n=n-2; 18 | nibbles=bits; 19 | bits=0; 20 | 21 | } 22 | else 23 | { 24 | break; 25 | } 26 | if(n>=8) 27 | { 28 | n=n-8; 29 | bytes=nibbles; 30 | nibbles=0; 31 | 32 | } 33 | else{ 34 | break; 35 | } 36 | if(n>=16) 37 | { 38 | n=n-16; 39 | bits=2*bytes; 40 | bytes=0; 41 | } 42 | else 43 | break; 44 | } 45 | System.out.println(bits+" "+nibbles+" "+bytes); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Practice-codechef-solutions/Math/CARVANS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | int n; 12 | cin>>n; 13 | int arr[n]; 14 | for(int i=0;i>arr[i]; 16 | } 17 | int count=1; 18 | for(int i=0;i=arr[i+1]){ 20 | count++; 21 | } 22 | else{ 23 | arr[i+1]=arr[i]; 24 | } 25 | } 26 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned t; 6 | cin>>t; 7 | while(t--){ 8 | unsigned long long a,b; 9 | cin>>a>>b; 10 | if(a>b) 11 | cout<<">"< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | if(n<10){ 11 | cout<<"Thanks for helping Chef!"< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int a,b,c; 9 | cin>>a>>b>>c; 10 | if(a+b+c==180) 11 | cout<<"YES"< 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned long long t,n; 6 | cin>>t; 7 | while(t--) 8 | { 9 | unsigned long long p=1; 10 | cin>>n; 11 | for(int i=1;i<=n;i++) 12 | p=p*i; 13 | cout< 2 | using namespace std; 3 | 4 | 5 | unsigned long long hcf(unsigned long long a, unsigned long long b) 6 | { 7 | if(a%b==0) 8 | return b; 9 | else 10 | hcf(b,a%b); 11 | } 12 | 13 | unsigned long long lcm(unsigned long long a, unsigned long long b) 14 | { 15 | return (a*b)/hcf(a,b); 16 | 17 | } 18 | int main() 19 | { 20 | unsigned long long t; 21 | cin>>t; 22 | while(t--) 23 | { 24 | //cout<>n>>a>>b>>k; 27 | //cout<=k) 30 | cout<<"Win"< 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int t,d; 7 | cin>>t; 8 | while(t--) 9 | { int c=0; 10 | int n; 11 | cin>>n; 12 | while(n) 13 | { 14 | d=sqrt(n); 15 | c++; 16 | n=n-d*d; 17 | } 18 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned long long t; 6 | cin>>t; 7 | while(t--){ 8 | unsigned long long n; 9 | cin>>n; 10 | cout<<((n/2)+1)< 2 | using namespace std; 3 | 4 | int main() { 5 | unsigned long long t; 6 | cin>>t; 7 | while(t--){ 8 | unsigned long long a,b; 9 | cin>>a>>b; 10 | if(a>b) 11 | cout< 7 | #define ll long long 8 | using namespace std; 9 | 10 | int main() { 11 | ios::sync_with_stdio(0); 12 | cin.tie(0); 13 | 14 | 15 | } -------------------------------------------------------------------------------- /Willam fiset DSA c++ translated code/Priority Queues/min_index_priority_queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class MinIndexBinaryHeap { 5 | private: 6 | // current number of elments in the heap 7 | int sz; 8 | 9 | // maximum number of elements in the heap 10 | int N; 11 | 12 | int *child,*parent; 13 | int *pm,*im; 14 | int *values; 15 | 16 | Public: 17 | MinIndexBinaryHeap(int maxsize) { 18 | N = maxsize; 19 | im = new int[N]; 20 | pm = new int[N]; 21 | child = new int[N]; 22 | parent = new int[N]; 23 | values = new int[N]; 24 | 25 | for (int i = 0; i < N; ++i) { 26 | parent[i] = (i-1)/2; 27 | child[i] = 2 * i + 1; 28 | pm[i] = im[1] = -1; 29 | } 30 | } 31 | 32 | int size() { 33 | return sz; 34 | } 35 | 36 | bool isEmpty() { 37 | return sz == 0; 38 | } 39 | void insert(int ki,int value) { 40 | }; 41 | 42 | int main { 43 | ios_base::sync_with_stdio(false); 44 | cin.tie(0); 45 | } 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Willam fiset DSA c++ translated code/Stack/ArrayStack.cpp: -------------------------------------------------------------------------------- 1 | /* Implementation of stack using Arrays */ 2 | #include 3 | using namespace std; 4 | 5 | #define max_size 1000 6 | 7 | class Stack 8 | { 9 | private: 10 | int arr[max_size]; 11 | int top; 12 | 13 | public: 14 | Stack() 15 | { 16 | top = -1; 17 | } 18 | 19 | int Getsize() const { 20 | return top+1; 21 | } 22 | 23 | bool isEmpty() { 24 | return Getsize() == 0; 25 | } 26 | void push(int element) { 27 | if (top == max_size - 1) { 28 | throw invalid_argument("Stack Overflow"); 29 | } 30 | arr[++top] = element; 31 | } 32 | 33 | void pop() { 34 | if (isEmpty()) { 35 | throw invalid_argument("Stack Underflow"); 36 | } 37 | top--; 38 | } 39 | 40 | void show() { 41 | if (isEmpty()) { 42 | cout << "Stack is Empty !\n"; 43 | return; 44 | } 45 | for (int i = top; i >= 0; --i) { 46 | cout << arr[i] << "\n"; 47 | } 48 | } 49 | }; 50 | 51 | int main() { 52 | Stack s; 53 | s.push(5); 54 | s.push(10); 55 | s.push(15); 56 | s.push(20); 57 | s.push(25); 58 | s.push(30); 59 | // s.show(); 60 | s.pop(); 61 | s.pop(); 62 | s.pop(); 63 | s.pop(); 64 | // s.pop(); 65 | // s.pop(); 66 | s.show(); 67 | 68 | } -------------------------------------------------------------------------------- /Willam fiset DSA c++ translated code/Suffix Array/SuffixArraySlow.cpp: -------------------------------------------------------------------------------- 1 | // Naive algorithm for building suffix array of a given text O(n^2logn) 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct suffix 8 | { 9 | int index; 10 | char *suff; 11 | }; 12 | 13 | int cmp(struct suffix a, struct suffix b) 14 | { 15 | return strcmp(a.suff, b.suff) < 0? 1 : 0; 16 | } 17 | 18 | int *buildSuffixArray(char *txt, int n) 19 | { 20 | 21 | struct suffix suffixes[n]; 22 | for (int i = 0; i < n; i++) 23 | { 24 | suffixes[i].index = i; 25 | suffixes[i].suff = (txt+i); 26 | } 27 | 28 | sort(suffixes, suffixes+n, cmp); 29 | 30 | int *suffixArr = new int[n]; 31 | for (int i = 0; i < n; i++) 32 | suffixArr[i] = suffixes[i].index; 33 | 34 | return suffixArr; 35 | } 36 | 37 | void printArr(int arr[], int n) 38 | { 39 | for(int i = 0; i < n; i++) 40 | cout << arr[i] << " "; 41 | cout << endl; 42 | } 43 | 44 | int main() 45 | { 46 | char txt[] = "banana"; 47 | int n = strlen(txt); 48 | int *suffixArr = buildSuffixArray(txt, n); 49 | cout << "Following is suffix array for " << txt << endl; 50 | printArr(suffixArr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Willam fiset DSA c++ translated code/readme.txt: -------------------------------------------------------------------------------- 1 | # Data Structures by William fiset cpp code. 2 | 3 | This folder contains all the cpp code translated from java of the popular course of Data Structures and algorithm on youtube channel of freecodecamp taught by google engineer william fiset. 4 | you can check the video at : https://www.youtube.com/watch?v=RBSGKlAvoiM 5 | for original code in java : https://github.com/williamfiset/Algorithms#data-structures 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/A-frog.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define pb push_back 3 | #define mp make_pair 4 | #define fr first 5 | #define sc second 6 | #define MOD 1000000007 7 | #define len(x) x.size() 8 | #define min3(a, b, c) min(a, min(b, c)) 9 | #define max3(a, b, c) max(a, max(b, c)) 10 | #define all(v) v.begin(), v.end() 11 | #define alla(a,n) a, a + n 12 | 13 | using namespace std; 14 | 15 | typedef long long ll; 16 | typedef unsigned long long ull; 17 | typedef pair pll; 18 | typedef vector vll; 19 | typedef vector vpll; 20 | typedef vector vvll; 21 | typedef vector vs; 22 | const int MAX = 1e5+5; 23 | int h[MAX]; 24 | int dp[MAX]; 25 | 26 | ll frog(int n){ 27 | 28 | for( int i = 2; i < n; i++) 29 | dp[i] = min(dp[i-2]+abs(h[i-2]-h[i]), dp[i-1]+abs(h[i-1]-h[i]) ); 30 | return dp[n-1]; 31 | 32 | } 33 | int main() { 34 | 35 | // #ifndef ONLINE_JUDGE 36 | // freopen("input.txt", "r", stdin) ; 37 | // freopen("output.txt", "w", stdout) ; 38 | // #endif 39 | ios_base::sync_with_stdio(false); 40 | cin.tie(NULL) ; cout.tie(NULL) ; 41 | 42 | int n; 43 | cin >> n; 44 | for(int i = 0; i < n; i++){ 45 | cin >> h[i]; 46 | } 47 | dp[0] = 0; 48 | dp[1] = abs(h[1]-h[0]); 49 | ll a = frog(n); 50 | cout< 2 | #define pb push_back 3 | #define mp make_pair 4 | #define fr first 5 | #define sc second 6 | #define MOD 1000000007 7 | #define len(x) x.size() 8 | #define min3(a, b, c) min(a, min(b, c)) 9 | #define max3(a, b, c) max(a, max(b, c)) 10 | #define all(v) v.begin(), v.end() 11 | #define alla(a,n) a, a + n 12 | 13 | using namespace std; 14 | 15 | typedef long long ll; 16 | typedef unsigned long long ull; 17 | typedef pair pll; 18 | typedef vector vll; 19 | typedef vector vpll; 20 | typedef vector vvll; 21 | typedef vector vs; 22 | int main() 23 | { 24 | int no_of_stones, no_of_steps; 25 | cin >> no_of_stones >> no_of_steps; 26 | 27 | vector height(no_of_stones + 1, 0); 28 | for(int i = 1; i <= no_of_stones; i++) 29 | cin >> height[i]; 30 | 31 | const int oo = 1e9; 32 | vector minimum_cost(no_of_stones + 1, oo); 33 | minimum_cost[1] = 0; 34 | 35 | for(int i = 2; i <= no_of_stones; i++) 36 | { 37 | for(int j = i - 1; j >= max(1, i - no_of_steps); j--) 38 | { 39 | minimum_cost[i] = min(minimum_cost[i], minimum_cost[j] + abs(height[i] - height[j])); 40 | } 41 | } 42 | 43 | cout << minimum_cost[no_of_stones]; 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/C-vacation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | cin >> n; 7 | vectorv[n+1], dp[n+1]; 8 | for(int i = 0; i < n; i++){ 9 | int a, b, c; 10 | cin >> a >> b >> c; 11 | v[i].push_back(a); 12 | v[i].push_back(b); 13 | v[i].push_back(c); 14 | dp[i].push_back(0); 15 | dp[i].push_back(0); 16 | dp[i].push_back(0); 17 | } 18 | dp[0][0] = v[0][0]; 19 | dp[0][1] = v[0][1]; 20 | dp[0][2] = v[0][2]; 21 | for(int i = 1; i < n; i++){ 22 | dp[i][0] = v[i][0]+max(dp[i-1][1], dp[i-1][2]); 23 | dp[i][1] = v[i][1]+max(dp[i-1][0], dp[i-1][2]); 24 | dp[i][2] = v[i][2]+max(dp[i-1][0], dp[i-1][1]); 25 | 26 | } 27 | cout << *max_element(dp[n-1].begin(), dp[n-1].end()) << "\n"; 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/D-knapsack-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | long long int dp[105][100005]; 4 | long long int rec(vector& W, vector& V, int n, int w){ 5 | if(n == 0 or w == 0){ 6 | return 0; 7 | } 8 | if (dp[n][w] != -1) return dp[n][w]; 9 | else if(w >= W[n-1] ){ 10 | return dp[n][w] = max(V[n-1]+rec(W, V, n-1, w-W[n-1]), rec(W, V, n-1, w)); 11 | } 12 | else{ 13 | return dp[n][w] = rec(W, V, n-1, w); 14 | } 15 | } 16 | int main() { 17 | int n, w; 18 | cin >> n >> w; 19 | memset(dp, -1, sizeof(dp)); 20 | vector W(n), V(n); 21 | for(int i = 0; i < n; i++){ 22 | cin >> W[i]; 23 | cin >> V[i]; 24 | } 25 | cout << rec(W, V, n, w); 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/F-lcs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | string s, t; 6 | cin >> s >> t; 7 | int sl = s.size(); 8 | int tl = t.size(); 9 | int dp[sl+1][tl+1]; 10 | for(int i = 0; i <= sl; i++){ 11 | for(int j = 0; j <= tl; j++){ 12 | if(i == 0 or j == 0){ 13 | dp[i][j] = 0; 14 | } 15 | else if(s[i-1] == t[j-1]){ 16 | dp[i][j] = 1+dp[i-1][j-1]; 17 | } 18 | else{ 19 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 20 | } 21 | } 22 | } 23 | int i = sl, j = tl; 24 | vector str; 25 | while(i > 0 && j > 0){ 26 | if(s[i-1] == t[j-1]){ 27 | str.push_back(s[i-1]); 28 | i--; 29 | j--; 30 | } 31 | else{ 32 | if(dp[i][j-1] > dp[i-1][j]) j--; 33 | else i--; 34 | } 35 | 36 | } 37 | reverse(str.begin(), str.end()); 38 | for(int i = 0; i < str.size(); i++){ 39 | cout << str[i]; 40 | } 41 | cout << "\n"; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/G-longest-path.cpp: -------------------------------------------------------------------------------- 1 | /#include 2 | using namespace std; 3 | vector dp(100005); 4 | bool vis[100005]; 5 | int dfs(vector>& adj, int i){ 6 | if(vis[i]){ 7 | return dp[i]; 8 | } 9 | int ans = 0; 10 | vis[i] = 1; 11 | for(int j = 0; j < adj[i].size(); j++){ 12 | ans = max(ans, 1+dfs(adj, adj[i][j])); 13 | } 14 | return dp[i] = ans; 15 | } 16 | int main(){ 17 | int n, m; 18 | cin >> n >> m; 19 | memset(vis, 0, sizeof(dp)); 20 | fill(dp.begin(), dp.end(), 0); 21 | vector> adj(n+1); 22 | for(int i = 0; i < m; i++){ 23 | int x, y; 24 | cin >> x >> y; 25 | adj[x].push_back(y); 26 | 27 | } 28 | //dfs(adj, 1); 29 | for(int i = 1; i < n+1; i++){ 30 | if(!vis[i]){ 31 | dfs(adj, i); 32 | } 33 | } 34 | cout << *max_element(dp.begin(), dp.end()) << "\n"; 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/H-grid-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int dp[1002][1002]; 4 | const int mod = 1e9+7; 5 | int rec(vector&grid, int i, int j, int h, int w){ 6 | int ans = 0; 7 | if (i == h-1 and j == w-1){ 8 | return 1; 9 | } 10 | else if (i == h or j == w){ 11 | return 0; 12 | } 13 | else if (grid[i][j] == '.'){ 14 | if(dp[i][j] != -1){ 15 | return dp[i][j]; 16 | } 17 | ans += (rec(grid, i+1, j, h, w)+rec(grid, i, j+1, h, w))%mod; 18 | // cout << "y"; 19 | } 20 | return dp[i][j] = ans; 21 | } 22 | 23 | int main() { 24 | int h, w; 25 | cin >> h >> w; 26 | vectorgrid; 27 | memset(dp, -1, sizeof(dp)); 28 | for(int i = 0; i < h; i++){ 29 | string s; 30 | cin >> s; 31 | grid.push_back(s); 32 | } 33 | cout << rec(grid, 0, 0, h, w) << "\n"; 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/I-coins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | double probability_heads[3003][3003]; 5 | int main() 6 | { 7 | int no_of_coins; 8 | cin >> no_of_coins; 9 | double probability[no_of_coins]; 10 | for(int i = 1; i <= no_of_coins; i++) 11 | cin >> probability[i]; 12 | 13 | memset(probability_heads, 0, sizeof(probability_heads)); 14 | probability_heads[0][0] = 1; 15 | 16 | for(int i = 1; i <= no_of_coins; i++) 17 | { 18 | double head_event = probability[i], tail_event = 1 - probability[i]; 19 | 20 | probability_heads[0][i] = tail_event*probability_heads[0][i - 1]; 21 | 22 | for(int heads = 1; heads <= i; heads++) 23 | { 24 | probability_heads[heads][i] = head_event*probability_heads[heads - 1][i - 1] + tail_event*probability_heads[heads][i - 1]; 25 | } 26 | } 27 | 28 | double answer = 0; 29 | for(int i = no_of_coins/2 + 1; i <= no_of_coins; i++) 30 | answer += probability_heads[i][no_of_coins]; 31 | 32 | cout << setprecision(9) << answer; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /atcoder-dp-contest-solutions/subset_sum_k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool subsetSumK(vector &v, int k) 6 | { 7 | if(k > accumulate(v.begin(), v.end(), 0)) 8 | { 9 | return false; 10 | } 11 | int sum = k, n = v.size(); 12 | bool dp[n + 1][sum + 1]; 13 | for (int i = 0; i <= n; i++) 14 | { 15 | for (int j = 0; j <= sum; j++) 16 | { 17 | if (j == 0) 18 | { 19 | dp[i][j] = true; 20 | } 21 | else if (i == 0) 22 | { 23 | dp[i][j] = false; 24 | } 25 | else if (v[i - 1] <= j) 26 | { 27 | dp[i][j] = dp[i][j - v[i - 1]] || dp[i - 1][j]; 28 | } 29 | else 30 | { 31 | dp[i][j] = dp[i - 1][j]; 32 | } 33 | } 34 | } 35 | return dp[n][sum]; 36 | } 37 | int main() 38 | { 39 | freopen("input.txt", "r", stdin); 40 | freopen("output.txt", "w", stdout); 41 | int n, k; 42 | cin >> n; 43 | vector v(n); 44 | for (int i = 0; i < n; i++) 45 | { 46 | cin >> v[i]; 47 | } 48 | cin >> k; 49 | bool present = subsetSumK(v, k); 50 | if (present) 51 | { 52 | cout << "subset with sum " << k << " is present"; 53 | } 54 | else 55 | { 56 | cout << "subset with sum " << k << " is not present"; 57 | } 58 | } -------------------------------------------------------------------------------- /hacktober.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cp-geeks-adgitm/Hacktoberfest/857a682cf67d4ad698498edab1fdc8d128e13b6b/hacktober.webp -------------------------------------------------------------------------------- /multidimarraydynamicallocation/bin/Debug/multidimarraydynamicallocation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cp-geeks-adgitm/Hacktoberfest/857a682cf67d4ad698498edab1fdc8d128e13b6b/multidimarraydynamicallocation/bin/Debug/multidimarraydynamicallocation.exe -------------------------------------------------------------------------------- /multidimarraydynamicallocation/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int m; 8 | int n; 9 | cout<<"Enter Number of Rows"<>m; 11 | cout<<"Enter Number of Columns"<>n; 13 | int **p=new int*[m]; 14 | for(int i=0;i>p[i][j]; 20 | } 21 | } 22 | for(int i=0;i 2 | 3 | 4 | 5 | 42 | 43 | -------------------------------------------------------------------------------- /multidimarraydynamicallocation/multidimarraydynamicallocation.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /multidimarraydynamicallocation/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cp-geeks-adgitm/Hacktoberfest/857a682cf67d4ad698498edab1fdc8d128e13b6b/multidimarraydynamicallocation/obj/Debug/main.o -------------------------------------------------------------------------------- /standard-template-library/deque.cpp: -------------------------------------------------------------------------------- 1 | //Unlike vectors, contiguous storage allocation may not be 2 | //guaranteed. 3 | //Double Ended Queues are basically an implementation of the data structure double 4 | //ended queue. 5 | 6 | // Random access - constant O(1), operator[] for random accessing elements is available. 7 | // Insertion or removal of elements at the end or beginning - constant O(1) 8 | // Insertion or removal of elements - linear O(n) 9 | 10 | //Apart from push_front and pop_front, Deque use the same methods as of array. 11 | //So, we will see how to use push_front and pop_front only, for rest you can refer 12 | //to vector. 13 | 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | int main(){ 19 | freopen("input.txt", "r", stdin); 20 | freopen("output.txt", "w", stdout); 21 | deque deq(5, 0); //initialising deque with zeroes. 22 | cout << "deque: "; 23 | for (int i = 0; i < 5; i++){ 24 | cout << deq[i] << " "; 25 | } 26 | cout << endl; 27 | 28 | //push_front; 29 | deq.push_front(-1); 30 | deq.push_front(-2); 31 | 32 | //pop_front 33 | deq.pop_front(); 34 | 35 | cout << "deque: "; 36 | for (int i = 0; i < 5; i++) 37 | { 38 | cout << deq[i] << " "; 39 | } 40 | cout << endl; 41 | } -------------------------------------------------------------------------------- /standard-template-library/queue.cpp: -------------------------------------------------------------------------------- 1 | // The C++ Queue is a container adapter that gives the programmer a FIFO (first-in, first- 2 | // out) data structure 3 | //Queue methods are empty, push, pop, size, back, front 4 | //push, pop and front works differently rest have same functionality 5 | //as we have discussed earlier. 6 | //no support for operator[], begin and end, Hence you can't iterate or 7 | //print the queue without poping the elements. 8 | 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | template 15 | void print_it(T& pq){ 16 | while(!pq.empty()){ 17 | cout << pq.front() << " "; 18 | pq.pop(); 19 | } 20 | cout << endl; 21 | } 22 | 23 | int main(){ 24 | freopen("output.txt", "w", stdout); 25 | queueq; 26 | 27 | //push 28 | //push elements at the end of queue. 29 | //works in constant time. 30 | q.push(1); 31 | q.push(2); 32 | q.push(3); 33 | q.push(4); 34 | 35 | //pop 36 | //pop the element from the front of queue 37 | //works in constant time 38 | q.pop(); 39 | 40 | //front 41 | //return the front element of queue 42 | cout << "Front element: " << q.front() << "\n"; 43 | cout << "Queue :"; 44 | print_it(q); 45 | 46 | } -------------------------------------------------------------------------------- /standard-template-library/stack.cpp: -------------------------------------------------------------------------------- 1 | // The C++ Stack is a container adapter that gives the programmer the functionality of a 2 | // stack -- specifically, a FILO (first-in, last-out) data structure. 3 | //stack methods are empty, push, pop, size, top 4 | //push, pop and tops works differently, rest have same functionality 5 | //as we have discussed earlier. 6 | //no support for operator[], begin and end, Hence you can't iterate or 7 | //print the stack without poping the elements. 8 | 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | template 15 | void print_it(T& st){ 16 | while(!st.empty()){ 17 | cout << st.top() << " "; 18 | st.pop(); 19 | } 20 | cout << endl; 21 | } 22 | 23 | int main(){ 24 | freopen("output.txt", "w", stdout); 25 | stackst; 26 | 27 | //push 28 | //push element at the top of stack. 29 | //works in constant time. 30 | st.push(1); 31 | st.push(2); 32 | st.push(3); 33 | st.push(4); 34 | 35 | //pop 36 | //pop the element from the top of stack 37 | //works in constant time 38 | st.pop(); 39 | 40 | //front 41 | //return the front element of stueue 42 | cout << "top element: " << st.top() << "\n"; 43 | cout << "stack :"; 44 | print_it(st); 45 | 46 | } --------------------------------------------------------------------------------