├── .DS_Store ├── 2SumInHashing.cpp ├── 2sum.cpp ├── Armstrong.cpp ├── Array_list.cpp ├── BFS.cpp ├── BinarySearch1.cpp ├── BubbleSort.cpp ├── CONTRIBUTING.md ├── Container_With_Most_Water.java ├── Counting2.cpp ├── DataStructurePython ├── Addition Without Operator │ └── Addition.py ├── Anagram │ └── Anagram.py ├── Cache │ └── LRUCache.py ├── Graph │ ├── Directed_Acyclic_Graph.py │ └── Graph.py ├── Heap │ └── Heap.py ├── Implementing Stack │ └── stack.py ├── LinkedListDS │ ├── CycleFinding.py │ ├── linkedlist.py │ ├── linkedlist2.py │ ├── node.py │ └── testlinkedlist.py ├── Priority Queue DS │ └── PriorityQueue.py ├── Tree │ └── Trie.py └── TreeDS │ ├── RedBlackBST.py │ └── TreeDS.py ├── DupInArr.cpp ├── FibonacciSeries.java ├── First non-repeating character in a stream of characters.cpp ├── Flatten binary tree to linked list.cpp ├── FullPyramidOfStars.cpp ├── GCD.java ├── Heapsort.c ├── Insertion_Sort.cpp ├── Largest elements in an array.cpp ├── Leetcode - 1672_Richest_Customer_Wealth.cpp ├── Leetcode - 1812. Determine_Color_of_a_Chessboard_Square ├── Leetcode problem no. 2095 ├── Leetcode-Longest common prefix.cpp ├── LinearSearch.java ├── LinkedList.cpp ├── Longest_Substring.cpp ├── Matrix_Median.cpp ├── Max_and_SecondMax.cpp ├── Maximum Profit_Adarsh_Mohanty.cpp ├── Mergesort.c ├── Palindrome.cpp ├── PriorityCPUscheduling.c ├── Quicksort.c ├── README.md ├── ReverseNumber.java ├── ReverseOfNumber.cpp ├── Simplify_Path.cpp ├── Subsets 2 Leetcode ├── HeapSort.cpp ├── ProblemStmt.docx ├── RadixSort.cpp ├── RadixSort.exe └── Subsets2.cpp ├── SumOfEvenNumbers.cpp ├── SumOrProd.cpp ├── TermsOfAP.cpp ├── Train_and_Querues.cpp ├── TribonnaciUsingDp.cpp ├── Two Sum.cpp ├── Valid_BST_from_Preorder.cpp ├── backtrack-maxLexicographic.cpp ├── backtrack-nQueen.cpp ├── backtracking-permutations.cpp ├── backtracking-subset.cpp ├── bellmanford.cpp ├── binarySearch.cpp ├── binary_exponentiation.cpp ├── breadth-first-search.cpp ├── bubble_sort.py ├── climbing_stairs.cpp ├── codechefSolutions ├── .DS_Store ├── July Cookoff 2022 │ ├── PermutationAndMedian.cpp │ ├── SegmentationFault.cpp │ └── XorPermutation.cpp ├── long │ └── May1 │ │ ├── alternating_diameter.cpp │ │ ├── attackofqueen.cpp │ │ ├── footballCup.cpp │ │ ├── magicalStone.cpp │ │ ├── miamigp.cpp │ │ ├── pushpa.cpp │ │ └── sugarcane.cpp └── straters │ ├── 55 │ ├── SUBPREM.cpp │ ├── balls_and_boxes.cpp │ ├── brokenphones.cpp │ ├── fever.cpp │ └── permutation_clear │ ├── 56 │ ├── BINSTRING.cpp │ ├── Binary Substitution.cpp │ ├── Chefland Games.cpp │ ├── Four_Equidistant_point_Grid.cpp │ ├── Good_Program.cpp │ ├── LOCKDRAW.cpp │ ├── MaximizeColours.cpp │ ├── Nearest Exit.cpp │ ├── SUBPERM.cpp │ ├── colour.cpp │ ├── divsort.cpp │ ├── encode_easy.cpp │ ├── encode_hard.cpp │ ├── faraway.cpp │ ├── ksub.cpp │ ├── palswap.cpp │ └── subsbin.cpp │ ├── 57 │ ├── CHEFPROFIT.cpp │ ├── Delicious Queries.cpp │ ├── Parallel_Processing.cpp │ ├── SUBSTADD.cpp │ ├── aliceandmarks.cpp │ ├── evensplits.cpp │ ├── maximumexpression.cpp │ ├── nonnegative.cpp │ ├── sumneq.cpp │ └── twodiffpallindormes.cpp │ ├── 58 │ ├── EQPRFMAXSPLT.cpp │ ├── NOPAL.cpp │ ├── SUBMEX.cpp │ ├── Watching_Movies.cpp │ ├── addtosubsequence.cpp │ ├── breaktheelements.cpp │ ├── equivalentNumbers.cpp │ ├── pilesParity.cpp │ ├── rankthepages.cpp │ ├── reachthetarget.cpp │ └── removebadelements.cpp │ └── 59 │ ├── AudibleRange.cpp │ └── Speciality.cpp ├── count_num_of_subset_sum_k.cpp ├── cousins.cpp ├── dfs.cpp ├── diff_of_partition_of_two_sets_are_mini.cpp ├── edit_distance.cpp ├── fibonnaciUsingDp.cpp ├── firstAndLastposnofElementinSortedArray.cpp ├── first_missing_positive.cpp ├── inordertree_traversal.cpp ├── kadanes_algo.cpp ├── kthRowOfPascal'sTriangle.cpp ├── largest.cpp ├── linear-search.cpp ├── longest_common_subsequence.cpp ├── maximum-score-from-performing-multiplication-operations.cpp ├── mergeSort.cpp ├── minStep.cpp ├── mini_insertion_deletion_to_convert_string_a_to_b.cpp ├── mini_no_of_insertion_to_make_string_palindrome.exe ├── number- words.java ├── palindrome └── palindrome.cpp ├── paranthesis.cpp ├── prime.cpp ├── prime_find_using_sieve.cpp ├── primefactorisation.cpp ├── remove_duplicate_letters.cpp ├── reverse_linked_list.cpp ├── reverse_string_using_stack.cpp ├── robinround.cpp ├── seiveoferatosthenes.cpp ├── shortest-unsorted-continuous-subarray.cpp ├── shortest_comman_supersequence.cpp ├── simple sieve.cpp ├── single_number.cpp ├── sliding_window.cpp ├── sorting technique ├── counting_sort.cpp ├── counting_sort.exe ├── insertion_sort.cpp └── insertionsort.cpp ├── squares_diff_ascending.cpp ├── stack.cpp ├── subarraySum.cpp ├── subset sum k.cpp ├── subset_sum_prblm.cpp ├── sudoku solver ├── sudoku through pygame.py └── sum of all sub-arrays.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kritsid/competetive-programming/8920a76d8d08edf538f9db5289ed11ae74fa080d/.DS_Store -------------------------------------------------------------------------------- /2SumInHashing.cpp: -------------------------------------------------------------------------------- 1 | //2 Sum Problem in cpp 2 | Qn: Given an array of integers, find two numbers such that they add up to a specific target number. 3 | 4 | Soln: 5 | int find_index(int val, vectorA, int n){ 6 | for(int i=0;i Solution::twoSum(const vector &A, int B) { 14 | unordered_mapmap; 15 | int finalAns[2] = {-1,-1}; 16 | int target = B; 17 | int n = A.size(); 18 | for(int i=0;ipossAns[1] || (finalAns[1]==possAns[1] && finalAns[0]>possAns[0])){ 33 | finalAns[0] = possAns[0]; 34 | finalAns[1] = possAns[1]; 35 | } 36 | } 37 | else{ 38 | finalAns[0] = possAns[0]; 39 | finalAns[1] = possAns[1]; 40 | } 41 | 42 | } 43 | } 44 | vectorans; 45 | if(finalAns[0]!=-1){ 46 | ans.push_back(finalAns[0]+1); 47 | ans.push_back(finalAns[1]+1); 48 | } 49 | return ans; 50 | } 51 | -------------------------------------------------------------------------------- /2sum.cpp: -------------------------------------------------------------------------------- 1 | // Question 2 | // Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | // You can return the answer in any order. 5 | 6 | class Solution { 7 | public: 8 | vector twoSum(vector &numbers, int target) 9 | { 10 | //Key is the number and value is its index in the vector. 11 | unordered_map hash; 12 | vector result; 13 | for (int i = 0; i < numbers.size(); i++) { 14 | int numberToFind = target - numbers[i]; 15 | 16 | //if numberToFind is found in map, return them 17 | if (hash.find(numberToFind) != hash.end()) { 18 | return {hash[numberToFind], i}; 19 | } 20 | 21 | //number was not found. Put it in the map. 22 | hash[numbers[i]] = i; 23 | } 24 | return result; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Armstrong.cpp: -------------------------------------------------------------------------------- 1 | // Program created by Nirmal Shah 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int n, org, rem, answer = 0; 8 | cout << "Please input a Number: "; 9 | cin >> n; 10 | org = n; 11 | 12 | while (org != 0) { 13 | rem = org % 10; 14 | answer += rem * rem * rem; 15 | org /= 10; 16 | } 17 | if (answer == n) 18 | cout << n << " is an Armstrong value."; 19 | else 20 | cout << n << " is not an Armstrong value."; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Array_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void SelectionSort(int Array[],const int Size){ 7 | int i,j,smallest,temp; 8 | for(i=0;iArray[j]){ 12 | smallest=j; 13 | } 14 | } 15 | temp=Array[i]; 16 | Array[i]=Array[smallest]; 17 | Array[smallest]=temp; 18 | } 19 | for(int iii=0;iii<8;iii++) 20 | cout< 2 | using namespace std; 3 | 4 | void bfs(vector> &adjList,int source,int N){ 5 | vector visited(N,false); 6 | 7 | queue q; 8 | visited[source]=true; 9 | q.push(source); 10 | 11 | while(!q.empty()){ 12 | int currentNode=q.front(); 13 | cout<<"Visited: "<> adjList(N); 33 | 34 | adjList[0].push_back(1); 35 | adjList[0].push_back(2); 36 | adjList[0].push_back(4); 37 | 38 | adjList[1].push_back(3); 39 | adjList[2].push_back(3); 40 | adjList[3].push_back(4); 41 | adjList[3].push_back(5); 42 | 43 | bfs(adjList,0,N); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /BinarySearch1.cpp: -------------------------------------------------------------------------------- 1 | Problem: Given a matrix of integers A of size N x M and an integer B. Write an efficient algorithm that searches for integar B in matrix A. 2 | 3 | My SOln: 4 | int binary(vector >arr, int x,int row,int s,int e){ 5 | if(s<=e){ 6 | int mid = (s+e)/2; 7 | if(arr[row][mid]==x){ 8 | return 1; 9 | } 10 | else if(arr[row][mid]>x){ 11 | return binary(arr,x,row,s,mid-1); 12 | } 13 | else{ 14 | return binary(arr,x,row,mid+1,e); 15 | } 16 | } 17 | return 0; 18 | } 19 | int Solution::searchMatrix(vector > &arr, int b) { 20 | int row = arr.size(); 21 | int col = arr[0].size(); 22 | int poss_row; 23 | //find row containing range of b 24 | for(int i=0;ib){ 26 | poss_row = i; 27 | break; 28 | } 29 | if(arr[i][col-1]==b){ 30 | return 1; 31 | } 32 | } 33 | // apply binary search in poss_row 34 | return binary(arr,b,poss_row,0,col-1); 35 | } 36 | -------------------------------------------------------------------------------- /BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // CPP program for sorting the elements using Bubble sort 2 | 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n, i, arr[50], j, temp; 8 | //Taking input from user 9 | cout<<"Enter the Size (max. 50): "; 10 | cin>>n; 11 | cout<<"Enter "<>arr[i]; 14 | 15 | cout< 17 | for(i=0; i<(n-1); i++) 18 | //outer loop 19 | { 20 | for(j=0; j<(n-i-1); j++) 21 | //inner loop 22 | { 23 | if(arr[j]>arr[j+1]) 24 | { 25 | //swapping 26 | temp = arr[j]; 27 | arr[j] = arr[j+1]; 28 | arr[j+1] = temp; 29 | } 30 | 31 | } 32 | } 33 | cout<<"The New Array is: "; 34 | cout<= b) return a; 5 | return b; 6 | } 7 | 8 | static int min(int a, int b) { 9 | if (a <= b) return a; 10 | return b; 11 | } 12 | public int maxArea(int[] height) { 13 | int len = height.length; 14 | int i = 0, j = len - 1, area = 0, mx = 0; 15 | while (i != j) { 16 | area = min(height[i], height[j]) * (j - i); 17 | mx = max(area, mx); 18 | if (height[i] >= height[j]) { 19 | j--; 20 | } else { 21 | i++; 22 | } 23 | } 24 | return mx; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Counting2.cpp: -------------------------------------------------------------------------------- 1 | // Problem: C - Counting 2 2 | // Contest: AtCoder - Panasonic Programming Contest 2021(AtCoder Beginner Contest 231) 3 | // URL: https://atcoder.jp/contests/abc231/tasks/abc231_c 4 | // Memory Limit: 1024 MB 5 | // Time Limit: 2000 ms 6 | // 7 | // Powered by CP Editor (https://cpeditor.org) 8 | 9 | #include 10 | using namespace std; 11 | #define ll long long 12 | #define FAST1 ios_base::sync_with_stdio(false); 13 | #define FAST2 cin.tie(NULL); 14 | 15 | int main(){ 16 | FAST1; 17 | FAST2; 18 | ll n;ll q; 19 | 20 | cin>>n>>q; 21 | int arr[20000]; 22 | for(ll i=0;i>arr[i]; 24 | } 25 | while(q--){ 26 | ll m; 27 | cin>>m; 28 | ll cnt=0; 29 | for(ll i=0;i= m) cnt++; 31 | } 32 | 33 | cout< int: 40 | """ 41 | Access an item from the cache 42 | """ 43 | if len(self.hmap) == 0 or key not in self.hmap: 44 | return -1 45 | this_node = self.hmap[key] 46 | self.__moveToHead(this_node) 47 | return this_node.data 48 | 49 | def put(self, key: int, value: int) -> None: 50 | """ 51 | Add or Update an item in the cache 52 | """ 53 | if key in self.hmap: 54 | this_node = self.hmap[key] 55 | this_node.data = value 56 | self.__moveToHead(this_node) 57 | else: 58 | new_node = Node(key, value) 59 | self.hmap[key] = new_node 60 | self.__addFirst(new_node) 61 | self.size += 1 62 | 63 | if self.size > self.capacity: 64 | self.__removeLRUEntry() 65 | 66 | def __removeLRUEntry(self): 67 | """ 68 | Evicts the least recently used item from cache 69 | """ 70 | tail_node = self.__popTail() 71 | del self.hmap[tail_node.key] 72 | self.size -= 1 73 | 74 | def __addFirst(self, node): 75 | """ 76 | Adds a node at the beginning of the linked list 77 | """ 78 | node.prev = self.head 79 | node.next = self.head.next 80 | self.head.next.prev = node 81 | self.head.next = node 82 | 83 | def __removeNode(self, node): 84 | """ 85 | Removes a node from the doubly linked list 86 | """ 87 | oldprev, oldnext = node.prev, node.next 88 | oldprev.next = oldnext 89 | oldnext.prev = oldprev 90 | 91 | def __moveToHead(self, node): 92 | """ 93 | Removes the node and puts it at the beginning of the cache (list) 94 | """ 95 | self.__removeNode(node) 96 | self.__addFirst(node) 97 | 98 | def __popTail(self): 99 | """ 100 | Removes and returns the element pointed by the tail of the list 101 | """ 102 | rem = self.tail.prev 103 | self.__removeNode(rem) 104 | return rem 105 | 106 | def display(self): 107 | """ 108 | Prints the elements in the cache in order 109 | """ 110 | p = self.head.next 111 | while p.next: 112 | print("[Key:{0}, Value:{1}]".format(p.key, p.data), end=" ") 113 | p = p.next 114 | print("") 115 | 116 | # Your LRUCache object will be instantiated and called as such: 117 | # obj = LRUCache(capacity) 118 | # param_1 = obj.get(key) 119 | # obj.put(key,value) 120 | -------------------------------------------------------------------------------- /DataStructurePython/Graph/Directed_Acyclic_Graph.py: -------------------------------------------------------------------------------- 1 | 2 | import networkx as nx 3 | from matplotlib import pyplot as plt 4 | 5 | 6 | class DAG: 7 | 8 | def __init__(self): 9 | self.graph = nx.DiGraph() 10 | 11 | def addEdges(self, edges): 12 | """Function to add one edge at a time and 13 | check if the graph is acyclic post insertion""" 14 | self.graph.add_edge(edges) 15 | if nx.is_directed_acyclic_graph(self.graph): 16 | pass 17 | else: 18 | raise "Unable to insert " + str(edges) + "This is an Acyclic graph" 19 | self.graph.remove_edge(edges) 20 | 21 | def AddSetofEdges(self, listt): 22 | """Function to all a list of edges and 23 | check is the graph is an DAG for furthur details refer networkx""" 24 | self.graph.add_edges_from(listt) 25 | if nx.is_directed_acyclic_graph(self.graph): 26 | pass 27 | else: 28 | raise "This is an acyclic graph check your edges" 29 | self.graph.remove_edge(listt) 30 | 31 | def Visualise(self, location="home"): 32 | """It uses Matplotlib to visualise the DAG . 33 | The graph is stored in a PNG format . So name the file accourdingly 34 | eg 35 | >>> DAG.Visualise(home / img.png)""" 36 | if self.graph is None: 37 | return "There is no graph consider adding edges to visualise" 38 | plt.tight_layout() 39 | nx.draw_networkx(self.graph, arrows=True, node_size=800) 40 | plt.savefig(location, format="PNG") 41 | plt.clf() 42 | return "Graph generated" 43 | 44 | 45 | graph = DAG() 46 | 47 | 48 | graph.AddSetofEdges([("root", "a"), ("a", "b"), 49 | ("a", "e"), ("b", "c"), 50 | ("b", "d"), ("d", "e")]) 51 | 52 | graph.Visualise("Python/DataStructure/Graph/Dag.png") 53 | -------------------------------------------------------------------------------- /DataStructurePython/Graph/Graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple implementation of unweighted and weighted Graphs. 3 | 4 | Both are implemented using adjacency lists. 5 | The weighted graph implementation stores the target edges of a single 6 | starting node of the adjacency list using a list of tuples (index, weight). 7 | 8 | Example: 9 | >>> graph = WeightedGraph(5) # directed weighted graph 10 | >>> graph.add_edge(0, 1, weight=4) 11 | >>> graph.add_edge(0, 2, weight=3) 12 | >>> graph.add_edge(2, 3, weight=1) 13 | >>> graph.add_edge(3, 4, weight=5) 14 | >>> graph.add_edge(4, 1, weight=2) 15 | >>> print(graph) 16 | 0: 1 (weight: 4) 2 (weight: 3) 17 | 1: 18 | 2: 3 (weight: 1) 19 | 3: 4 (weight: 5) 20 | 4: 1 (weight: 2) 21 | 22 | This example input is equivalent to: 23 | >>> graph.edges = [ 24 | >>> [(1, 4), (2, 3)], 25 | >>> [], 26 | >>> [(3, 1)], 27 | >>> [(4, 5)], 28 | >>> [(1, 2)] 29 | >>> ] 30 | >>> 31 | """ 32 | 33 | 34 | class UnweightedGraph: 35 | def __init__(self, vertices, directed=True): 36 | self.vertices = vertices 37 | self.directed = directed 38 | self.edges = [[] for _ in range(vertices)] 39 | 40 | def __str__(self): 41 | output = "" 42 | 43 | for i in range(0, self.vertices): 44 | output += f"{i}: " 45 | 46 | for j in range(0, len(self.edges[i])): 47 | output += f"{self.edges[i][j]} " 48 | 49 | output += "\n" 50 | 51 | return output 52 | 53 | def has_vertex(self, vertex): 54 | return 0 <= vertex < self.vertices 55 | 56 | def has_edge(self, start, dest): 57 | if self.has_vertex(start) and self.has_vertex(dest): 58 | if dest in self.edges[start]: 59 | return True 60 | 61 | return False 62 | 63 | def add_edge(self, start, dest): 64 | if self.has_edge(start, dest): 65 | return False 66 | 67 | self.edges[start].append(dest) 68 | if not self.directed: 69 | self.edges[dest].append(start) 70 | 71 | return True 72 | 73 | 74 | class WeightedGraph: 75 | def __init__(self, vertices, directed=True): 76 | self.vertices = vertices 77 | self.directed = directed 78 | self.edges = [[] for _ in range(vertices)] 79 | 80 | def __str__(self): 81 | output = "" 82 | 83 | for i in range(0, self.vertices): 84 | output += f"{i}: " 85 | 86 | for j in range(0, len(self.edges[i])): 87 | output += f"{self.edges[i][j][0]} " 88 | output += f"(weight: {self.edges[i][j][1]}) " 89 | 90 | output += "\n" 91 | 92 | return output 93 | 94 | def has_vertex(self, vertex): 95 | return 0 <= vertex < self.vertices 96 | 97 | def has_edge(self, start, dest, weight): 98 | if self.has_vertex(start) and self.has_vertex(dest): 99 | if (dest, weight) in self.edges[start]: 100 | return True 101 | 102 | return False 103 | 104 | def add_edge(self, start, dest, weight): 105 | if self.has_edge(start, dest, weight): 106 | return False 107 | 108 | self.edges[start].append((dest, weight)) 109 | if not self.directed: 110 | self.edges[dest].append((start, weight)) 111 | 112 | return True 113 | 114 | 115 | def main(): 116 | 117 | # Basic driver code to demonstrate functionality 118 | 119 | ugraph = UnweightedGraph(5) 120 | ugraph.add_edge(0, 1) 121 | ugraph.add_edge(0, 2) 122 | ugraph.add_edge(0, 3) 123 | ugraph.add_edge(2, 4) 124 | ugraph.add_edge(1, 2) 125 | print(ugraph) 126 | 127 | wgraph = WeightedGraph(5) 128 | wgraph.add_edge(0, 2, weight=3) 129 | wgraph.add_edge(0, 3, weight=2) 130 | wgraph.add_edge(1, 3, weight=4) 131 | wgraph.add_edge(2, 1, weight=1) 132 | wgraph.add_edge(4, 3, weight=6) 133 | print(wgraph) 134 | 135 | 136 | if __name__ == "__main__": 137 | main() 138 | -------------------------------------------------------------------------------- /DataStructurePython/Heap/Heap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Heap 3 | 4 | The heap is an important data structure. It provides the following 5 | functionality: 6 | 7 | findMin: Find the minimum of all the current data. O(1) runtime. 8 | 9 | pop: Remove the minimum element from the current data and return it. O(log n) 10 | runtime. 11 | 12 | push: Add an element to the current data. O(log n) runtime. 13 | 14 | The provided runtimes assume that the heap currently has n elements and that 15 | checking less than on elements runs in O(1) time. 16 | 17 | Implementation: 18 | 19 | Our implementation of a heap will be done with arrays, and we will treat the 20 | array as a binary tree. Each index, i, in the array will have a left and right 21 | "child" indicies at 2i + 1 and 2i + 2 respectively. The heap operates under the 22 | assumption of an important invariant: 23 | 24 | For all indicies i, the value at index i is less than the values at either of 25 | its children (2i + 1 and 2i + 2). 26 | 27 | When we want to findMin we just return the value at index 0 in the array, the 28 | root of our tree. This must be the minimum due to the tree structure of the 29 | heap, and the transittivity of less than. 30 | 31 | When we add an element to the tree, we will add it to the end of the array, 32 | lets say at index i. We can calculate its parent index, p = (i - 1) // 2 since 33 | it will be either the left or right child of p. If the new value is less than 34 | the value at p, we can swap the values at p and i. We dont have to check down 35 | the other child of the parent, since less than is transitive. 36 | 37 | We then bubble up, and check that the parent of p satisfies the invariant as 38 | well, and we swap if it doesn't. At each step we half our index, so this 39 | bubble-up-ing runs in O(log n) time. 40 | 41 | When we remove the minimum from the heap, we record the current minimum to 42 | return later, and then replace it with the last value in the array. Then we 43 | perform another bubbling operation, but now in the opposite direction. 44 | 45 | We find the index of the minimum value out of the node itself and its two 46 | children. If the minimum is the node itself, we are done. If instead it is one 47 | of the children, we swap the parent and minimum values, and keep bubbling down 48 | from the child. 49 | """ 50 | 51 | 52 | def __up(arr, index): 53 | """ 54 | Bubbles the value arr[index] up to retain heap structure. 55 | """ 56 | while index > 0 and arr[index] < arr[(parent := (index - 1) // 2)]: 57 | arr[index], arr[parent] = arr[parent], arr[index] 58 | index = parent 59 | 60 | 61 | def __down(arr, index): 62 | """ 63 | Bubbles the value arr[index] down to retain heap structure. 64 | """ 65 | n = len(arr) 66 | while index < n: 67 | # The index of the minimum value will be kept in extreme 68 | extreme = index 69 | left = index * 2 + 1 70 | right = index * 2 + 2 71 | 72 | if left < n and arr[left] < arr[extreme]: 73 | extreme = left 74 | if right < n and arr[right] < arr[extreme]: 75 | extreme = right 76 | 77 | if extreme == index: 78 | break 79 | 80 | arr[index], arr[extreme] = arr[extreme], arr[index] 81 | index = extreme 82 | 83 | 84 | def heapify(arr): 85 | """ 86 | We can re-arrange any array to enforce the invariant. 87 | """ 88 | for i in range(len(arr) - 1, -1, -1): 89 | __down(arr, i) 90 | 91 | 92 | def findMin(heap): 93 | """ 94 | Returns the minimum element in the heap. 95 | """ 96 | if len(heap) == 0: 97 | raise IndexError("findmin on empty heap") 98 | return heap[0] 99 | 100 | 101 | def heappop(heap): 102 | """ 103 | Removes the head element from heap, and then rearranges the result to 104 | retain the heap invariant. 105 | """ 106 | if len(heap) == 0: 107 | raise IndexError("pop from empty heap") 108 | if len(heap) == 1: 109 | # We can return the only remaining value. 110 | return heap.pop() 111 | result = heap[0] 112 | heap[0] = heap.pop() 113 | __down(heap, 0) 114 | return result 115 | 116 | 117 | def heappush(heap, value): 118 | """ 119 | Adds a new element to the heap, then rearranges to retain the heap 120 | invariant. 121 | """ 122 | heap.append(value) 123 | __up(heap, len(heap) - 1) 124 | 125 | 126 | def heappushpop(heap, value): 127 | """ 128 | If we pop and push successively, we can simplify the process by only 129 | bubbling once. 130 | """ 131 | if len(heap) == 0: 132 | raise IndexError("pop from empty heap") 133 | result = heap[0] 134 | heap[0] = value 135 | __down(heap, 0) 136 | return result 137 | 138 | 139 | class Heap: 140 | """ 141 | This class is a wrapper for the individual methods implemented above. 142 | 143 | It might help to realise you don't have to implement it with a class, you 144 | can just implement it with an array and make sure to keep the heap 145 | invariant. 146 | """ 147 | 148 | def __init__(self): 149 | self.__arr = [] 150 | 151 | def findMin(self): 152 | return findMin(self.__arr) 153 | 154 | def push(self, value): 155 | heappush(self.__arr, value) 156 | 157 | def pop(self): 158 | return heappop(self.__arr) 159 | 160 | def pushpop(self, value): 161 | return heappushpop(self.__arr, value) 162 | -------------------------------------------------------------------------------- /DataStructurePython/Implementing Stack/stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | if self.items == []: 7 | return True 8 | else: 9 | return False 10 | 11 | def push(self, item): 12 | self.items.append(item) 13 | 14 | def pop(self): 15 | if len(self.items) != 0: 16 | return self.items.pop() 17 | else: 18 | print("Stack is empty") 19 | 20 | def peek(self): 21 | if len(self.items) != 0: 22 | return self.items[len(self.items) - 1] 23 | else: 24 | print("Stack is empty") 25 | 26 | def display(self): 27 | return (self.items) 28 | 29 | 30 | # __main__ 31 | s = Stack() 32 | c = 0 33 | while c != 5: 34 | print('\tSTACK OPERATIONS') 35 | print('1.Push') 36 | print('2.Pop') 37 | print('3.Peek') 38 | print('4.Display Stack') 39 | print('5.Exit') 40 | c = int(input('Enter your choice(1-5): ')) 41 | if c == 1: 42 | x = input("Enter the item: ") 43 | s.push(x) 44 | elif c == 2: 45 | s.pop() 46 | elif c == 3: 47 | s.peek() 48 | elif c == 4: 49 | print(s.display()) 50 | elif c != 5: 51 | print('Wrong Choice! Choose from 1 to 5 only') 52 | 53 | print('Bye') 54 | -------------------------------------------------------------------------------- /DataStructurePython/LinkedListDS/CycleFinding.py: -------------------------------------------------------------------------------- 1 | from .LinkedList import LinkedList 2 | 3 | 4 | def hasCycle(head): 5 | ''' 6 | returns the node where the cycle starts 7 | Or returns false if no cycle present 8 | ''' 9 | fastptr, slowptr = head, head 10 | if fastptr.nextNode is None or fastptr.nextNode.nextNode is None: 11 | return False 12 | while True: 13 | slowptr = slowptr.nextNode 14 | fastptr = fastptr.nextNode.nextNode 15 | if fastptr == slowptr: 16 | break 17 | 18 | slowptr = head 19 | 20 | while True: 21 | slowptr = slowptr.nextNode 22 | fastptr = fastptr.nextNode 23 | if fastptr == slowptr: 24 | break 25 | 26 | return fastptr 27 | 28 | 29 | # driver code for printing output 30 | ll = LinkedList() 31 | ll.insertEnd(1) 32 | ll.insertEnd(2) 33 | ll.insertEnd(3) 34 | ll.insertEnd(4) 35 | ll.insertEnd(5) 36 | ll.insertEnd(6) 37 | a = ll.head.nextNode.nextNode.nextNode.nextNode.nextNode 38 | a.nextNode = ll.head.nextNode.nextNode 39 | print(hasCycle(ll.head).data) 40 | -------------------------------------------------------------------------------- /DataStructurePython/LinkedListDS/linkedlist2.py: -------------------------------------------------------------------------------- 1 | # Date 1/5/2020. 2 | # __Author__ : CodePerfectPlus 3 | # __Package__ : Python 3 4 | # __GitHub__ : https://www.github.com/codeperfectplus 5 | # 6 | from node import Node 7 | 8 | 9 | class LinkedList: 10 | def __init__(self): 11 | self.head = None 12 | self.counter = 0 13 | self.tail = None 14 | 15 | def __iter__(self): 16 | current = self.head 17 | while current: 18 | yield current 19 | current = current.next 20 | 21 | def __str__(self): 22 | if self.head is None: 23 | return "[]" 24 | nodes = [str(node.data) for node in self] 25 | return f"[{', '.join(nodes)}]" 26 | 27 | # O(N) 28 | def traverse(self): 29 | nodes = [str(node.data) for node in self] 30 | return " -> ".join(nodes) 31 | 32 | # O(1) 33 | def insert_start(self, value): 34 | self.counter += 1 35 | node = Node(value) 36 | if not self.head: 37 | self.head = node 38 | self.tail = node 39 | else: 40 | node.next = self.head 41 | self.head = node 42 | 43 | # O(1) 44 | def size(self): 45 | return self.counter 46 | 47 | # O(1) 48 | def insert_end(self, value): 49 | self.counter += 1 50 | node = Node(value) 51 | if self.head is None: 52 | self.head = node 53 | else: 54 | self.tail.next = node 55 | self.tail = node 56 | 57 | # O(N) 58 | def remove(self, value): 59 | if self.head is None: 60 | raise ValueError( 61 | "LinkedList.remove(value): \ 62 | value not in LinkedList" 63 | ) 64 | current = self.head 65 | prev = self.head 66 | while current: 67 | if current.data == self.head.data and current.data == value: 68 | self.head = self.head.next 69 | self.counter -= 1 70 | return 71 | if current.data == value: 72 | prev.next = current.next 73 | self.counter -= 1 74 | return 75 | prev = current 76 | current = current.next 77 | raise ValueError( 78 | "LinkedLis.remove(value): \ 79 | value not in LinkedList" 80 | ) 81 | -------------------------------------------------------------------------------- /DataStructurePython/LinkedListDS/node.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title - Linked List implementation in Python 3 | The Node class is a supporting class for the 4 | implementation of the LinkedList class 5 | """ 6 | 7 | 8 | class Node: 9 | def __init__(self, data): 10 | self.data = data 11 | self.next = None 12 | -------------------------------------------------------------------------------- /DataStructurePython/LinkedListDS/testlinkedlist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title - Linked List implementation in Python 3 | This file provides a class implementation of the linked list 4 | data structure in Python 5 | """ 6 | 7 | 8 | import unittest 9 | 10 | 11 | from linkedlist import LinkedList 12 | 13 | 14 | class TestLinkedList(unittest.TestCase): 15 | def test_linked_list_empty(self): 16 | llist = LinkedList() 17 | self.assertEqual(str(llist), "[]") 18 | 19 | def test_linked_list_insert_start(self): 20 | llist = LinkedList() 21 | llist.insert_start(1) 22 | self.assertEqual(str(llist), "[1]") 23 | 24 | def test_linked_list_insert_start_twice(self): 25 | llist = LinkedList() 26 | llist.insert_start(1) 27 | llist.insert_start(2) 28 | self.assertEqual(str(llist), "[2, 1]") 29 | 30 | def test_linked_list_insert_end(self): 31 | llist = LinkedList() 32 | llist.insert_end(3) 33 | llist.insert_end(4) 34 | self.assertEqual(str(llist), "[3, 4]") 35 | 36 | def test_linked_list_insert_end_then_start(self): 37 | llist = LinkedList() 38 | llist.insert_end(3) 39 | llist.insert_start(4) 40 | self.assertEqual(str(llist), "[4, 3]") 41 | 42 | def test_linked_list_insert_start_then_end(self): 43 | llist = LinkedList() 44 | llist.insert_start(4) 45 | llist.insert_end(3) 46 | self.assertEqual(str(llist), "[4, 3]") 47 | 48 | def test_linked_list_traversing(self): 49 | llist = LinkedList() 50 | for i in range(10): 51 | llist.insert_end(i) 52 | self.assertEqual( 53 | llist.traverse(), "0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9" 54 | ) 55 | 56 | def test_linked_list_remove_error(self): 57 | llist = LinkedList() 58 | for i in range(10): 59 | llist.insert_end(i) 60 | with self.assertRaises(ValueError): 61 | llist.remove(60) 62 | 63 | def test_linked_list_remove(self): 64 | llist = LinkedList() 65 | for i in range(10): 66 | llist.insert_end(i) 67 | llist.remove(4) 68 | self.assertEqual(str(llist), "[0, 1, 2, 3, 5, 6, 7, 8, 9]") 69 | 70 | 71 | if __name__ == "__main__": 72 | unittest.main() 73 | -------------------------------------------------------------------------------- /DataStructurePython/Priority Queue DS/PriorityQueue.py: -------------------------------------------------------------------------------- 1 | 2 | class Node: 3 | 4 | def __init__(self, info, priority): 5 | self.info = info 6 | self.priority = priority 7 | 8 | 9 | class PriorityQueue: 10 | 11 | def __init__(self): 12 | self.queue = list() 13 | # if you want you can set a maximum size for the queue 14 | 15 | # O(n) insertion 16 | # Inserts new Node into the priority queue in increasing order of priority 17 | def insert(self, node): 18 | # if queue is empty 19 | if self.size() == 0: 20 | # add the new node 21 | self.queue.append(node) 22 | else: 23 | # traverse the queue to find the right place for new node 24 | for x in range(0, self.size()): 25 | # if the priority of new node is greater 26 | if node.priority >= self.queue[x].priority: 27 | # if we have traversed the complete queue 28 | if x == (self.size() - 1): 29 | # add new node at the end 30 | self.queue.insert(x + 1, node) 31 | else: 32 | continue 33 | else: 34 | self.queue.insert(x, node) 35 | return True 36 | 37 | # O(1) deletion 38 | def delete(self): 39 | # remove the first node from the queue 40 | return self.queue.pop(0) 41 | 42 | # Prints each element of the priority queue 43 | def show(self): 44 | for x in self.queue: 45 | print(str(x.info) + " - " + str(x.priority)) 46 | 47 | # Returns the size of the priority queue 48 | def size(self): 49 | return len(self.queue) 50 | -------------------------------------------------------------------------------- /DataStructurePython/Tree/Trie.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Trie(object): 4 | """ 5 | A class named Trie for the main tree 6 | """ 7 | 8 | def __init__(self): 9 | """ 10 | Function to initialize the class Trie 11 | """ 12 | self.words = {} 13 | 14 | def insert(self, word): 15 | """ 16 | Function to insert a given word to the tree from variable tree 17 | :param word:The word passed down to the function 18 | :type word:str 19 | :return:Prints "The word, was successfully added" 20 | :rtype:none 21 | """ 22 | current = self.words 23 | for alphabet in word: 24 | if alphabet not in current: 25 | current[alphabet] = {} 26 | current = current[alphabet] 27 | current['#'] = 1 28 | print("\nThe word,{} was successfully added \n".format(word)) 29 | 30 | def search(self, word): 31 | """ 32 | Function to search a word in the already existing tree 33 | :param word:The word passed to the function to be searched for 34 | :type word:str 35 | :return:True if the word exist in tree else false 36 | :rtype:bool 37 | """ 38 | current = self.words 39 | for alphabet in word: 40 | if alphabet not in current: 41 | print("Word not found!") 42 | else: 43 | current = current[alphabet] 44 | return '#' in current 45 | 46 | def prefix_search(self, prefix): 47 | """ 48 | Function to search for prefix letters in a tree 49 | :param prefix:The letters passed to search as a prefix to be searched 50 | :type prefix:str 51 | :return:True if the prefix exist in tree else false 52 | :rtype:bool 53 | """ 54 | current = self.words 55 | for alphabet in prefix: 56 | if alphabet not in current: 57 | return False 58 | else: 59 | current = current[alphabet] 60 | return True 61 | 62 | 63 | def menu_options(): 64 | """ 65 | Function to print the menu 66 | """ 67 | print("Select your option ") 68 | print("\n1.Insert \n2.Search \n3.Preffix search \n4.Quit") 69 | 70 | 71 | if __name__ == '__main__': 72 | ob1 = Trie() 73 | while True: 74 | menu_options() 75 | choice = input("\nchoice:-") 76 | if choice == '1': 77 | insert_word = input("Enter the word you want to add to the tree ") 78 | ob1.insert(insert_word) 79 | elif choice == '2': 80 | word_search = input("What do you want to search ") 81 | print("\nWord found successfully!!\n" if ob1.search(word_search) 82 | else "\nWord not found!\n") 83 | elif choice == '3': 84 | prefix_letters = input("What do you want to search as prefix ") 85 | print("\nPrefix found successfully!!\n" 86 | if ob1.prefix_search(prefix_letters) 87 | else "\nPrefix not found!\n") 88 | else: 89 | break 90 | -------------------------------------------------------------------------------- /DataStructurePython/TreeDS/RedBlackBST.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """Represents Node in this data structure""" 4 | 5 | 6 | class Node: 7 | def __init__(self, value, color): 8 | self.value = value 9 | self.left = None 10 | self.right = None 11 | self.color = color 12 | 13 | 14 | """Red Black BST""" 15 | 16 | 17 | class RedBlackBST: 18 | def __init__(self): 19 | self.root = None 20 | self.RED = True 21 | self.BLACK = False 22 | 23 | def compareTo(self, first, second): 24 | return first - second 25 | 26 | def isRed(self, node): 27 | if node is None: 28 | return False 29 | return node.color == self.RED 30 | 31 | def Rotateleft(self, h): 32 | assert self.isRed(h.right) 33 | x = h.right 34 | h.right = x.left 35 | x.left = h 36 | x.color = h.color 37 | h.color = self.RED 38 | return x 39 | 40 | def Rotateright(self, h): 41 | assert self.isRed(h.left) 42 | x = h.left 43 | h.left = x.right 44 | x.right = h 45 | x.color = h.color 46 | h.color = self.RED 47 | return x 48 | 49 | def flipColors(self, h): 50 | assert self.isRed(h.left) 51 | assert self.isRed(h.right) 52 | h.left.color = self.BLACK 53 | h.right.color = self.BLACK 54 | h.color = self.RED 55 | 56 | def Realinsert(self, x, value): 57 | if x is None: 58 | return Node(value, self.RED) 59 | cmp = self.compareTo(value, x.value) 60 | if cmp < 0: 61 | x.left = self.Realinsert(x.left, value) 62 | elif cmp > 0: 63 | x.right = self.Realinsert(x.right, value) 64 | else: 65 | x.value = value 66 | 67 | if self.isRed(x.right) and not self.isRed(x.left): 68 | x = self.Rotateleft(x) 69 | if self.isRed(x.left) and self.isRed(x.left.left): 70 | x = self.Rotateright(x) 71 | if self.isRed(x.left) and self.isRed(x.right): 72 | self.flipColors(x) 73 | 74 | return x 75 | 76 | def insert(self, value): 77 | self.root = self.Realinsert(self.root, value) 78 | 79 | def search(self, value): 80 | x = self.root 81 | while x is not None: 82 | cmp = self.compareTo(value, x.value) 83 | if cmp < 0: 84 | x = x.left 85 | elif cmp > 0: 86 | x = x.right 87 | else: 88 | return x.value 89 | return None 90 | 91 | """Hibbard Deletion""" 92 | 93 | def delete(self, value): 94 | self.root = self.Realdelete(self.root, value) 95 | 96 | def Realdelete(self, x, value): 97 | if x is None: 98 | return None 99 | cmp = self.compareTo(value, x.value) 100 | 101 | if cmp < 0: 102 | x.left = self.Realdelete(x.left, value) 103 | elif cmp > 0: 104 | x.right = self.Realdelete(x.right, value) 105 | else: 106 | if x.right is None: 107 | return x.left 108 | if x.left is None: 109 | return x.right 110 | 111 | t = x 112 | x = self.Min(t.right) 113 | x.right = self.deleteMin(t.right) 114 | x.left = t.left 115 | 116 | return x 117 | 118 | def deleteMin(self, x): 119 | if x.left is None: 120 | return x.right 121 | x.left = self.deleteMin(x.left) 122 | return x 123 | 124 | def Min(self, x): 125 | if x.left is None: 126 | return x 127 | return self.Min(x.left) 128 | 129 | def inorder(self): 130 | self.inorderRec(self.root) 131 | 132 | def inorderRec(self, root): 133 | if root is not None: 134 | self.inorderRec(root.left) 135 | print(root.value, end=" ") 136 | self.inorderRec(root.right) 137 | 138 | 139 | if __name__ == "__main__": 140 | """The class name is RedBlackBST() 141 | After creating an object of this class, the client can 142 | use the following methods: 143 | 1.object.insert(value): insert the value given 144 | to the BST 145 | 2.object.search(value): this method would give you the 146 | node here this value exist 147 | 3. object.delete(value): this method will delete 148 | the provided value form the tree 149 | 4.object.inorder(): this method will print all the values 150 | in the tree in a non-decreasing order""" 151 | -------------------------------------------------------------------------------- /DataStructurePython/TreeDS/TreeDS.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class TreeNode: 4 | """ Tree Node Class """ 5 | 6 | def __init__(self, val=0, left=None, right=None): 7 | self.val = val 8 | self.left = left 9 | self.right = right 10 | 11 | 12 | class Tree: 13 | def __init__(self): 14 | self.root = None 15 | 16 | def insert(self, key): 17 | """ Insert key at first available node 18 | Do a level order traversal of tree using 19 | queue. The new node is placed at he first 20 | empty left/right children of a node 21 | """ 22 | 23 | if not self.root: 24 | # if tree is empty 25 | self.root = TreeNode(key) 26 | else: 27 | q = [self.root] 28 | while q: 29 | # deque 30 | temp = q.pop(0) 31 | # check if the left children is node 32 | if not temp.left: 33 | temp.left = TreeNode(key) 34 | break 35 | q.append(temp.left) 36 | 37 | # check if the right children is None 38 | if not temp.right: 39 | temp.right = TreeNode(key) 40 | break 41 | q.append(temp.right) 42 | return self.root 43 | 44 | def delete(self, key): 45 | """ Delete the node with val == key. 46 | Find the node to be deleted. Replace 47 | it with the rightmost deepest node. Delete 48 | the rightmost deepest node 49 | """ 50 | 51 | # if root or it's children are to be deleted 52 | if not self.root: 53 | return None 54 | elif not self.root.left and not self.root.right: 55 | if self.root.val == key: 56 | return None 57 | else: 58 | return self.root 59 | 60 | del_node = None 61 | q = [self.root] 62 | 63 | while q: 64 | temp = q.pop(0) 65 | if temp.val == key: 66 | del_node = temp 67 | if temp.left: 68 | q.append(temp.left) 69 | if temp.right: 70 | q.append(temp.right) 71 | if del_node: 72 | x = temp.val 73 | self.delete_deepest(self.root, temp) 74 | del_node.val = x 75 | return self.root 76 | 77 | def delete_deepest(self, node, d_node): 78 | """ Find and delete the deepest rightmost node """ 79 | q = [node] 80 | while len(q): 81 | temp = q.pop(0) 82 | if temp is d_node: 83 | temp = None 84 | return 85 | if temp.right: 86 | if temp.right is d_node: 87 | temp.right = None 88 | return 89 | else: 90 | q.append(temp.right) 91 | if temp.left: 92 | if temp.left is d_node: 93 | temp.left = None 94 | return 95 | else: 96 | q.append(temp.left) 97 | 98 | def print_inorder(self, node): 99 | """ Print inorder traversal of tree """ 100 | if node.left: 101 | self.print_inorder(node.left) 102 | print(node.val, end=' ') 103 | if node.right: 104 | self.print_inorder(node.right) 105 | 106 | def is_bst(self): 107 | """ 108 | Checks if the Tree is a Binary Search Tree by definition 109 | See also: https://en.wikipedia.org/wiki/Binary_search_tree#Definition 110 | """ 111 | 112 | return self.__is_bst(self.root) 113 | 114 | def __is_bst(self, node): 115 | """ 116 | Checks if the subtree of a given node is a valid BST 117 | :return validity as bool value 118 | """ 119 | 120 | if node is None: 121 | return True 122 | 123 | # Check if the left subtree is less and right is greater 124 | # than the current node, then repeat the process for every other 125 | # node in the tree by making recursive calls for left and right subtrees 126 | return \ 127 | self.__is_subtree_lesser(node.left, node.val) \ 128 | and self.__is_subtree_greater(node.right, node.val) \ 129 | and self.__is_bst(node.left) and self.__is_bst(node.right) 130 | 131 | def __is_subtree_lesser(self, node, val): 132 | if node is None: 133 | return True 134 | 135 | return \ 136 | val >= node.val \ 137 | and self.__is_subtree_lesser(node.left, val) \ 138 | and self.__is_subtree_lesser(node.right, val) 139 | 140 | def __is_subtree_greater(self, node, val): 141 | if node is None: 142 | return True 143 | 144 | return \ 145 | val < node.val \ 146 | and self.__is_subtree_greater(node.left, val) \ 147 | and self.__is_subtree_greater(node.right, val) 148 | 149 | 150 | def main(): 151 | 152 | # Basic driver code to demonstrate methods 153 | 154 | tree = Tree() 155 | tree.insert(50) 156 | tree.insert(25) 157 | tree.insert(75) 158 | tree.insert(60) 159 | tree.print_inorder(tree.root) 160 | 161 | # The insert() method of the Tree class does 162 | # not insert nodes according to the BST definition, 163 | # meaning that this will return False 164 | print(f"\n{tree.is_bst()}") 165 | 166 | bst = Tree() 167 | bst.root = TreeNode(50) 168 | bst.root.left = TreeNode(25) 169 | bst.root.right = TreeNode(75) 170 | bst.root.right.left = TreeNode(60) 171 | bst.print_inorder(bst.root) 172 | 173 | # We have manually constructed a valid BST, 174 | # meaning that this will return True 175 | print(f"\n{bst.is_bst()}") 176 | 177 | 178 | if __name__ == '__main__': 179 | main() 180 | -------------------------------------------------------------------------------- /DupInArr.cpp: -------------------------------------------------------------------------------- 1 | PS: 2 | Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times. 3 | 4 | My Soln: 5 | int Solution::repeatedNumber(const vector &arr) { 6 | 7 | int n = arr.size(); 8 | vectorv(n,0); 9 | for(int i=0;i1){ 13 | return arr[i]; 14 | } 15 | } 16 | return -1; 17 | } 18 | -------------------------------------------------------------------------------- /FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Fibonacci 3 | { 4 | public static void main(String[] args) 5 | { 6 | int n, a = 0, b = 0, c = 1; 7 | Scanner s = new Scanner(System.in); 8 | System.out.print("Enter value of n:"); 9 | n = s.nextInt(); 10 | System.out.print("Fibonacci Series:"); 11 | for(int i = 1; i <= n; i++) 12 | { 13 | a = b; 14 | b = c; 15 | c = a + b; 16 | System.out.print(a+" "); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /First non-repeating character in a stream of characters.cpp: -------------------------------------------------------------------------------- 1 | //First non-repeating character in a stream of characters 2 | 3 | 4 | Given a string A denoting a stream of lowercase alphabets. You have to make new string B. B is formed such that we have to find first non-repeating character each time a character is inserted to the stream and append it at the end to B. If no non-repeating character is found then append '#' at the end of B. 5 | 6 | My Code: 7 | 8 | 9 | string Solution::solve(string s) { 10 | queueq;int i=0; 11 | unordered_mapm; 12 | string b="";int flag=1; 13 | while(i1){ 25 | q.pop(); 26 | } 27 | else{ 28 | break; 29 | } 30 | } 31 | else{ 32 | flag =0; 33 | break; 34 | 35 | } 36 | } 37 | if(flag!=0) 38 | b += q.front(); 39 | else{ 40 | b+='#'; 41 | } 42 | flag=1; 43 | i++; 44 | } 45 | return b; 46 | } 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Flatten binary tree to linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node * left, * right; 9 | }; 10 | 11 | class Solution 12 | { 13 | node * prev = NULL; 14 | public: 15 | void flatten(node * root) 16 | { 17 | if (root == NULL) return; 18 | 19 | flatten(root -> right); 20 | flatten(root -> left); 21 | 22 | root -> right = prev; 23 | root -> left = NULL; 24 | prev = root; 25 | } 26 | 27 | }; 28 | 29 | struct node * newNode(int data) 30 | { 31 | struct node * node = (struct node * ) malloc(sizeof(struct node)); 32 | node -> data = data; 33 | node -> left = NULL; 34 | node -> right = NULL; 35 | 36 | return (node); 37 | } 38 | 39 | int main() 40 | { 41 | 42 | struct node * root = newNode(1); 43 | root -> left = newNode(2); 44 | root -> left -> left = newNode(3); 45 | root -> left -> right = newNode(4); 46 | root -> right = newNode(5); 47 | root -> right -> right = newNode(6); 48 | root -> right -> right -> left = newNode(7); 49 | 50 | Solution obj; 51 | 52 | obj.flatten(root); 53 | while(root->right!=NULL) 54 | { 55 | cout<data<<"->"; 56 | root=root->right; 57 | } 58 | cout<data; 59 | return 0; 60 | } 61 | 62 | //Output: 63 | 64 | //1->2->3->4->5->6->7 65 | 66 | //Time Complexity: O(N) 67 | 68 | //Space Complexity: O(N) 69 | -------------------------------------------------------------------------------- /FullPyramidOfStars.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int space, rows; 7 | 8 | cout <<"Enter number of rows: "; 9 | cin >> rows; 10 | 11 | for(int i = 1, k = 0; i <= rows; ++i, k = 0) 12 | { 13 | for(space = 1; space <= rows-i; ++space) 14 | { 15 | cout <<" "; 16 | } 17 | 18 | while(k != 2*i-1) 19 | { 20 | cout << "* "; 21 | ++k; 22 | } 23 | cout << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /GCD.java: -------------------------------------------------------------------------------- 1 | /* 2 | java program that will take 2 number as input 3 | and print there gcd using Euclidean algorithm 4 | */ 5 | import java.util.*; 6 | import java.io.*; 7 | import java.lang.*; 8 | class GCD { 9 | public static int gcd(int a,int b){ 10 | return b==0?a:gcd(b,a%b); 11 | } 12 | public static void main(String[] args){ 13 | Scanner scn = new Scanner(System.in); 14 | System.out.println("Enter the first number : "); 15 | int num1 = scn.nextInt(); 16 | System.out.println("Enter the Second number : "); 17 | int num2 = scn.nextInt(); 18 | System.out.println("GCD : "+gcd(num1,num2)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Heapsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* function to heapify a subtree. Here 'i' is the 4 | 5 | index of root node in array a[], and 'n' is the size of heap. */ 6 | 7 | void heapify(int a[], int n, int i) 8 | 9 | { 10 | 11 | int largest = i; // Initialize largest as root 12 | 13 | int left = 2 * i + 1; // left child 14 | 15 | int right = 2 * i + 2; // right child 16 | 17 | // If left child is larger than root 18 | 19 | if (left < n && a[left] > a[largest]) 20 | 21 | largest = left; 22 | 23 | // If right child is larger than root 24 | 25 | if (right < n && a[right] > a[largest]) 26 | 27 | largest = right; 28 | 29 | // If root is not largest 30 | 31 | if (largest != i) { 32 | 33 | // swap a[i] with a[largest] 34 | 35 | int temp = a[i]; 36 | 37 | a[i] = a[largest]; 38 | 39 | a[largest] = temp; 40 | 41 | 42 | 43 | heapify(a, n, largest); 44 | 45 | } 46 | 47 | } 48 | 49 | /*Function to implement the heap sort*/ 50 | 51 | void heapSort(int a[], int n) 52 | 53 | { 54 | 55 | for (int i = n / 2 - 1; i >= 0; i--) 56 | 57 | heapify(a, n, i); 58 | 59 | // One by one extract an element from heap 60 | 61 | for (int i = n - 1; i >= 0; i--) { 62 | 63 | /* Move current root element to end*/ 64 | 65 | // swap a[0] with a[i] 66 | 67 | int temp = a[0]; 68 | 69 | a[0] = a[i]; 70 | 71 | a[i] = temp; 72 | 73 | 74 | 75 | heapify(a, i, 0); 76 | 77 | } 78 | 79 | } 80 | 81 | /* function to print the array elements */ 82 | 83 | void printArr(int arr[], int n) 84 | 85 | { 86 | 87 | for (int i = 0; i < n; ++i) 88 | 89 | { 90 | 91 | printf("%d", arr[i]); 92 | 93 | printf(" "); 94 | 95 | } 96 | 97 | 98 | 99 | } 100 | 101 | int main() 102 | 103 | { 104 | 105 | int a[] = {48, 10, 23, 43, 28, 26, 1}; 106 | 107 | int n = sizeof(a) / sizeof(a[0]); 108 | 109 | printf("Before sorting array elements are - \n"); 110 | 111 | printArr(a, n); 112 | 113 | heapSort(a, n); 114 | 115 | printf("\nAfter sorting array elements are - \n"); 116 | 117 | printArr(a, n); 118 | 119 | return 0; 120 | 121 | } 122 | -------------------------------------------------------------------------------- /Insertion_Sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort an array using 7 | // insertion sort 8 | void insertionSort(int arr[], int n) 9 | { 10 | int i, key, j; 11 | for (i = 1; i < n; i++) 12 | { 13 | key = arr[i]; 14 | j = i - 1; 15 | 16 | // Move elements of arr[0..i-1], 17 | // that are greater than key, to one 18 | // position ahead of their 19 | // current position 20 | while (j >= 0 && arr[j] > key) 21 | { 22 | arr[j + 1] = arr[j]; 23 | j = j - 1; 24 | } 25 | arr[j + 1] = key; 26 | } 27 | } 28 | 29 | // A utility function to print an array 30 | // of size n 31 | void printArray(int arr[], int n) 32 | { 33 | int i; 34 | for (i = 0; i < n; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | int arr[] = { 12, 11, 13, 5, 6 }; 43 | int N = sizeof(arr) / sizeof(arr[0]); 44 | 45 | insertionSort(arr, N); 46 | printArray(arr, N); 47 | 48 | return 0; 49 | } 50 | // This is code is contributed by rathbhupendra 51 | -------------------------------------------------------------------------------- /Largest elements in an array.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for k largest elements in an array 2 | #include 3 | using namespace std; 4 | 5 | void kLargest(int arr[], int n, int k) 6 | { 7 | // Sort the given array arr in reverse order. 8 | sort(arr, arr + n, greater()); 9 | 10 | // Print the first kth largest elements 11 | for (int i = 0; i < k; i++) 12 | cout << arr[i] << " "; 13 | } 14 | 15 | // driver program 16 | int main() 17 | { 18 | int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; 19 | int n = sizeof(arr) / sizeof(arr[0]); 20 | int k = 3; 21 | kLargest(arr, n, k); 22 | } 23 | -------------------------------------------------------------------------------- /Leetcode - 1672_Richest_Customer_Wealth.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumWealth(vector>& accounts) { 4 | vector sum; 5 | for(int i=0; inext==NULL) 5 | return NULL; 6 | ListNode *slow=head; 7 | ListNode *fast=head; 8 | ListNode *p=NULL; 9 | while(fast!=NULL&&fast->next!=NULL) 10 | {p=slow; 11 | slow=slow->next; 12 | fast=fast->next->next; 13 | } 14 | p->next=slow->next; 15 | return head; 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode-Longest common prefix.cpp: -------------------------------------------------------------------------------- 1 | //function to find the longest common prefix string amongst an array of strings. 2 | class Solution { 3 | public: 4 | string longestCommonPrefix(vector& strs) { 5 | string ans=""; 6 | if(strs.size()==0) 7 | return ""; 8 | else if(strs.size()==1) 9 | return strs[0]; 10 | else{ 11 | sort(strs.begin(),strs.end()); 12 | if(strs[0]=="") 13 | return ""; 14 | string a = strs[0],b=strs[strs.size()-1]; 15 | for( int i = 0; i 5 | using namespace std; 6 | struct Node { 7 | int value; 8 | Node* next; 9 | }; 10 | struct Node* newNode(int value) { 11 | Node* node = new Node; 12 | node->value = value; 13 | node->next = NULL; 14 | return node; 15 | } 16 | void insertNewNode(Node** root, int value) { 17 | Node* node = newNode(value); 18 | Node* flag; 19 | if (*root == NULL) { 20 | *root = node; 21 | } 22 | else { 23 | flag = *root; 24 | while (flag->next != NULL) { 25 | flag = flag->next; 26 | } 27 | flag->next = node; 28 | } 29 | } 30 | void printLinkedList(Node* root) { 31 | while (root != NULL) { 32 | cout << root->value << " -> "; 33 | root = root->next; 34 | } 35 | cout << "NULL" << endl; 36 | } 37 | Node* createLinkedList(int arr[], int n) { 38 | Node *root = NULL; 39 | for (int i = 0; i < n; i++) { 40 | insertNewNode(&root, arr[i]); 41 | } 42 | return root; 43 | } 44 | int main() { 45 | int arr[] = { 12,13,14,15,16 }, n = 5; 46 | Node* root = createLinkedList(arr, n); 47 | printLinkedList(root); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Longest_Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | 5 | unordered_map index; 6 | int start=0,res=0; 7 | for(int i=0;i= start) 10 | start = index[s[i]] + 1; 11 | 12 | index[s[i]] = i; 13 | res=max(res,i-start+1); 14 | } 15 | 16 | return res; 17 | } 18 | }; -------------------------------------------------------------------------------- /Matrix_Median.cpp: -------------------------------------------------------------------------------- 1 | // problem: 2 | Given a matrix of integers A of size N x M in which each row is sorted. 3 | Find an return the overall median of the matrix A. 4 | 5 | // Solution: 6 | 7 | // // 1 7 1 1 3 3 3 3 3 8 | 9 | 10 | int Solution::findMedian(vector > &arr) { 11 | // find min and max of the array. 12 | // apply binary searh in range(min,max); 13 | // find num of elementsmax){ 29 | max = arr[i][m-1]; 30 | } 31 | } 32 | int vv = (n*m+1)/2; 33 | int start = mini; 34 | int end = max; 35 | // step 3 apply binary search 36 | while(start=vv){ 48 | end = mid; 49 | } 50 | else start = mid+1; 51 | 52 | 53 | } 54 | return end; 55 | } 56 | -------------------------------------------------------------------------------- /Max_and_SecondMax.cpp: -------------------------------------------------------------------------------- 1 | vector largestAndSecondLargest(int n, int arr[]){ 2 | int m1 = 0 , m2 = -1; 3 | vector v; 4 | for(int i=1; iarr[m1]) 7 | { 8 | m2 = m1; 9 | m1 = i; 10 | } 11 | else if (arr[i] != arr[m1]) 12 | { 13 | if(m2 == -1 || arr[i]>arr[m2]) 14 | { 15 | m2 = i; 16 | } 17 | } 18 | } 19 | v.push_back(arr[m1]); 20 | if(m2!=-1) 21 | v.push_back(arr[m2]); 22 | else 23 | v.push_back(-1); 24 | return v; 25 | } 26 | -------------------------------------------------------------------------------- /Maximum Profit_Adarsh_Mohanty.cpp: -------------------------------------------------------------------------------- 1 | //Maximum Profit by buying and selling stocks 2 | //Problem Statement: Suppose you have given the stock prices for respective days like (100, 180, 260, 310, 40, 535, 695). The stock price for the 1st day is 100, the 2nd day it is 180 and so on. Write a Python program to determine what days the user should buy and sell the stocks to get the maximum profit. 3 | 4 | //In the above case, in the following scenarios user will get maximum profit. 5 | //Buy stock on 1st day (100) 6 | //Sell stock on 4th day (310) 7 | //Buy stock on 5th day (100) 8 | //Sell stock on 7th day (695) 9 | 10 | 11 | //Algorithm steps: 12 | //Find the local minima (buying stock) 13 | //Find local maxima (selling stock) 14 | //Repeat until all days are covered. 15 | 16 | 17 | 18 | My sol: 19 | 20 | liStocks = [100, 180, 260, 310, 40, 535, 695] 21 | 22 | #find local minima 23 | def findMin(liStocks): 24 | for i, val in enumerate(liStocks[:-1]): 25 | if val < liStocks[i+1]: 26 | return i, val 27 | return -1, -1 28 | 29 | #find local maxima 30 | def findMax(liStocks): 31 | for i, val in enumerate(liStocks[:-1]): 32 | if val > liStocks[i+1]: 33 | return i, val 34 | return i+1, liStocks[-1] 35 | 36 | 37 | 38 | def buySellStock(): 39 | index=0 40 | while index < len(liStocks): 41 | i, val = findMin(liStocks[index:]) 42 | if i > -1: 43 | index=i+index 44 | print("bye stock on day ", index+1, val) 45 | else: 46 | break 47 | 48 | i, val = findMax(liStocks[index:]) 49 | index=i+index 50 | print("sell stock on day ", index+1, val) 51 | 52 | 53 | if __name__ == "__main__": 54 | buySellStock() 55 | -------------------------------------------------------------------------------- /Mergesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | 5 | /* Function to merge the subarrays of a[] */ 6 | 7 | void merge(int a[], int beg, int mid, int end) 8 | 9 | { 10 | 11 | int i, j, k; 12 | 13 | int n1 = mid - beg + 1; 14 | 15 | int n2 = end - mid; 16 | 17 | 18 | 19 | int LeftArray[n1], RightArray[n2]; //temporary arrays 20 | 21 | 22 | 23 | /* copy data to temp arrays */ 24 | 25 | for (int i = 0; i < n1; i++) 26 | 27 | LeftArray[i] = a[beg + i]; 28 | 29 | for (int j = 0; j < n2; j++) 30 | 31 | RightArray[j] = a[mid + 1 + j]; 32 | 33 | 34 | 35 | i = 0; /* initial index of first sub-array */ 36 | 37 | j = 0; /* initial index of second sub-array */ 38 | 39 | k = beg; /* initial index of merged sub-array */ 40 | 41 | 42 | 43 | while (i < n1 && j < n2) 44 | 45 | { 46 | 47 | if(LeftArray[i] <= RightArray[j]) 48 | 49 | { 50 | 51 | a[k] = LeftArray[i]; 52 | 53 | i++; 54 | 55 | } 56 | 57 | else 58 | 59 | { 60 | 61 | a[k] = RightArray[j]; 62 | 63 | j++; 64 | 65 | } 66 | 67 | k++; 68 | 69 | } 70 | 71 | while (i 2 | using namespace std; 3 | bool ispalindrome(char arr[],int s,int e) 4 | { 5 | if(s>=e) 6 | return 1; 7 | if(char[s]==char[e]) 8 | return ispalindrome(arr,s+1,e-1); 9 | else 10 | return 0; 11 | } 12 | int main() 13 | { 14 | char arr[50]; 15 | cin>>arr; 16 | if(palindrome(arr,0,strlen(arr)-1)) 17 | cout<<"YES"< 2 | 3 | void swap(int *b,int*c) 4 | 5 | { 6 | 7 | int temp; 8 | 9 | temp=*c; 10 | 11 | *c=*b; 12 | 13 | *b=temp; 14 | 15 | } 16 | 17 | int main() 18 | 19 | { 20 | 21 | int i,j,n,cmpt; 22 | 23 | float twt=0,ttat=0; 24 | 25 | printf("Enter number of processes:"); 26 | 27 | scanf("%d",&n); 28 | 29 | int a[n][6]; 30 | 31 | printf("Enter arrival time,bust time,priority of each process:\n"); 32 | 33 | for(i=0;ia[j+1][1]) 64 | 65 | { 66 | 67 | swap(&a[j][0],&a[j+1][0]); 68 | 69 | swap(&a[j][1],&a[j+1][1]); 70 | 71 | swap(&a[j][2],&a[j+1][2]); 72 | 73 | swap(&a[j][5],&a[j+1][5]); 74 | 75 | } 76 | 77 | } 78 | 79 | } 80 | 81 | a[0][3]=a[0][1];//waiting time 82 | 83 | a[0][4]=a[0][2]-a[0][1];//turnaround time 84 | 85 | cmpt=a[0][4];//completion time 86 | 87 | twt=twt+a[0][3]; 88 | 89 | ttat=ttat+a[0][4]; 90 | 91 | for(i=1;ia[j][5] && a[j][1]<=cmpt) 102 | 103 | { 104 | 105 | min=a[j][5]; 106 | 107 | swap(&a[i][0],&a[j][0]); 108 | 109 | swap(&a[i][1],&a[j][1]); 110 | 111 | swap(&a[i][2],&a[j][2]); 112 | 113 | swap(&a[i][5],&a[j][5]); 114 | 115 | } 116 | 117 | } 118 | 119 | a[i][3]=cmpt-a[i][1]; 120 | 121 | twt=twt+a[i][3]; 122 | 123 | cmpt=cmpt+a[i][2]; 124 | 125 | a[i][4]=cmpt-a[i][1]; 126 | 127 | ttat=ttat+a[i][4]; 128 | 129 | } 130 | 131 | printf("Process\tA.T\tB.T\tPR\tT.A.T\tW.T\n"); 132 | 133 | for(i=0;i 2 | 3 | /* function that consider last element as pivot, 4 | 5 | place the pivot at its exact position, and place 6 | 7 | smaller elements to left of pivot and greater 8 | 9 | elements to right of pivot. */ 10 | 11 | int partition (int a[], int start, int end) 12 | 13 | { 14 | 15 | int pivot = a[end]; // pivot element 16 | 17 | int i = (start - 1); 18 | 19 | 20 | 21 | for (int j = start; j <= end - 1; j++) 22 | 23 | { 24 | 25 | // If current element is smaller than the pivot 26 | 27 | if (a[j] < pivot) 28 | 29 | { 30 | 31 | i++; // increment index of smaller element 32 | 33 | int t = a[i]; 34 | 35 | a[i] = a[j]; 36 | 37 | a[j] = t; 38 | 39 | } 40 | 41 | } 42 | 43 | int t = a[i+1]; 44 | 45 | a[i+1] = a[end]; 46 | 47 | a[end] = t; 48 | 49 | return (i + 1); 50 | 51 | } 52 | 53 | 54 | 55 | /* function to implement quick sort */ 56 | 57 | void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ 58 | 59 | { 60 | 61 | if (start < end) 62 | 63 | { 64 | 65 | int p = partition(a, start, end); //p is the partitioning index 66 | 67 | quick(a, start, p - 1); 68 | 69 | quick(a, p + 1, end); 70 | 71 | } 72 | 73 | } 74 | 75 | 76 | 77 | /* function to print an array */ 78 | 79 | void printArr(int a[], int n) 80 | 81 | { 82 | 83 | int i; 84 | 85 | for (i = 0; i < n; i++) 86 | 87 | printf("%d ", a[i]); 88 | 89 | } 90 | 91 | int main() 92 | 93 | { 94 | 95 | int a[] = { 24, 9, 29, 14, 19, 27 }; 96 | 97 | int n = sizeof(a) / sizeof(a[0]); 98 | 99 | printf("Before sorting array elements are - \n"); 100 | 101 | printArr(a, n); 102 | 103 | quick(a, 0, n - 1); 104 | 105 | printf("\nAfter sorting array elements are - \n"); 106 | 107 | printArr(a, n); 108 | 109 | 110 | 111 | return 0; 112 | 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # competetive-programming 2 | 3 | ### A little explanation of the problem will really be appreciated!! 4 | ### have a look at contributing.md file for any relevent instructions 5 | Thanks 6 | 7 | competetive programming 2022 - hacktoberfest 8 | -------------------------------------------------------------------------------- /ReverseNumber.java: -------------------------------------------------------------------------------- 1 | public class ReverseNumber 2 | { 3 | public static void main(String[] args) 4 | { 5 | int number = 987654, reverse = 0; 6 | while(number != 0) 7 | { 8 | int remainder = number % 10; 9 | reverse = reverse * 10 + remainder; 10 | number = number/10; 11 | } 12 | System.out.println("The reverse of the given number is: " + reverse); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ReverseOfNumber.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | int flag = 0; 10 | int i = 0; 11 | while (n > 0){ 12 | int a; 13 | a = n%10; 14 | if (a == 0 && flag == 0){ 15 | n = n/10; 16 | continue; 17 | } 18 | flag = 1; 19 | n = n/10; 20 | cout << a; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Simplify_Path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | 5 | stack st; 6 | string res; 7 | 8 | for(int i = 0; i 3 | using namespace std; 4 | 5 | // To heapify a subtree rooted with node i which is 6 | // an index in arr[]. n is size of heap 7 | void heapifyfunc(int arr[], int n, int i) 8 | { 9 | int largest = i; // Initialize largest as root 10 | int l = 2 * i + 1; // left = 2*i + 1 11 | int r = 2 * i + 2; // right = 2*i + 2 12 | 13 | // If left child is larger than root 14 | if (l < n && arr[l] > arr[largest]) 15 | largest = l; 16 | 17 | // If right child is larger than largest so far 18 | if (r < n && arr[r] > arr[largest]) 19 | largest = r; 20 | 21 | // If largest is not root 22 | if (largest != i) { 23 | swap(arr[i], arr[largest]); 24 | 25 | // Recursively heapify the affected sub-tree 26 | heapifyfunc(arr, n, largest); 27 | } 28 | } 29 | 30 | // main function to do heap sort 31 | void heapSort(int arr[], int n) 32 | { 33 | // Build heap (rearrange array) 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapifyfunc(arr, n, i); 36 | 37 | // One by one extract an element from heap 38 | for (int i = n - 1; i >= 0; i--) { 39 | // Move current root to end 40 | swap(arr[0], arr[i]); 41 | 42 | // call max heapify on the reduced heap 43 | heapifyfunc(arr, i, 0); 44 | } 45 | } 46 | 47 | /* A function to print array of size n */ 48 | void printArray(int arr[], int n) 49 | { 50 | for (int i = 0; i < n; ++i) 51 | cout << arr[i] << " "; 52 | cout << "\n"; 53 | } 54 | 55 | // Driver program 56 | int main() 57 | { 58 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 59 | int n = sizeof(arr) / sizeof(arr[0]); 60 | 61 | heapSort(arr, n); 62 | 63 | cout << "Sorted array is \n"; 64 | printArray(arr, n); 65 | } 66 | -------------------------------------------------------------------------------- /Subsets 2 Leetcode/ProblemStmt.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kritsid/competetive-programming/8920a76d8d08edf538f9db5289ed11ae74fa080d/Subsets 2 Leetcode/ProblemStmt.docx -------------------------------------------------------------------------------- /Subsets 2 Leetcode/RadixSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort Algorithm 2 | 3 | #include 4 | using namespace std; 5 | 6 | // A function to get maximum value in arr[] 7 | int getMax(int arr[], int n) 8 | { 9 | int max = arr[0]; 10 | for (int i = 1; i < n; i++) 11 | if (arr[i] > max) 12 | max = arr[i]; 13 | return max; 14 | } 15 | 16 | // A function to do counting sort of arr[] according to 17 | // the digit represented by exp. 18 | void countSort(int arr[], int n, int exp) 19 | { 20 | int output[n]; // output array 21 | int i, count[10] = { 0 }; 22 | 23 | // Store count of occurrences in count[] 24 | for (i = 0; i < n; i++) 25 | count[(arr[i] / exp) % 10]++; 26 | 27 | // Change count[i] so that count[i] now contains actual 28 | // position of this digit in output[] 29 | for (i = 1; i < 10; i++) 30 | count[i] += count[i - 1]; 31 | 32 | // Build the output array 33 | for (i = n - 1; i >= 0; i--) { 34 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 35 | count[(arr[i] / exp) % 10]--; 36 | } 37 | 38 | // Copy the output array to arr[], so that arr[] now 39 | // contains sorted numbers according to current digit 40 | for (i = 0; i < n; i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | // The main function to that sorts arr[] of size n using 45 | // Radix Sort 46 | void radixsortfunc(int arr[], int n) 47 | { 48 | // Find the maximum number to know number of digits 49 | int max_num = getMax(arr, n); 50 | 51 | // Do counting sort for every digit. Note that instead 52 | // of passing digit number, exp is passed. exp is 10^i 53 | // where i is current digit number 54 | for (int exp = 1; max_num / exp > 0; exp *= 10) 55 | countSort(arr, n, exp); 56 | } 57 | 58 | // A function to print an array 59 | void print(int arr[], int n) 60 | { 61 | for (int i = 0; i < n; i++) 62 | cout << arr[i] << " "; 63 | } 64 | 65 | 66 | int main() 67 | { 68 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 69 | int n = sizeof(arr) / sizeof(arr[0]); 70 | 71 | // Function Call 72 | radixsortfunc(arr, n); 73 | print(arr, n); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /Subsets 2 Leetcode/RadixSort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kritsid/competetive-programming/8920a76d8d08edf538f9db5289ed11ae74fa080d/Subsets 2 Leetcode/RadixSort.exe -------------------------------------------------------------------------------- /Subsets 2 Leetcode/Subsets2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | vector> result; 4 | void backtrack(vector &temp,vector nums,int index) 5 | { 6 | result.push_back(temp); 7 | for(int i=index;i> subsetsWithDup(vector& nums) { 19 | 20 | sort(nums.begin(), nums.end()); 21 | vector temp; 22 | backtrack(temp,nums,0); 23 | vector> res=result; 24 | result.clear(); 25 | return res; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /SumOfEvenNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n; 6 | cout << "Enter any number:" << endl; 7 | cin >> n; 8 | 9 | int a = 0; 10 | int sum = 0; 11 | while (a <= n){ 12 | 13 | sum = sum+a; 14 | a = a+2; 15 | 16 | } 17 | cout << "the sum of the numbers is:" << endl << sum; 18 | } 19 | -------------------------------------------------------------------------------- /SumOrProd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int input,choice; 6 | cin >> input >> choice; 7 | 8 | int i = 1; 9 | int sum = 0; 10 | int prod = 1; 11 | while (i <= input){ 12 | if (choice == 1){ 13 | sum = i+sum; 14 | 15 | } 16 | else if (choice == 2){ 17 | prod = prod*i; 18 | } 19 | 20 | else { 21 | cout << -1 << endl; 22 | break; 23 | } 24 | i++; 25 | } 26 | if (choice == 1){ 27 | cout << sum < 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | 9 | int i = 1; 10 | while (i <= n){ 11 | int a = i; 12 | if ((3*a+2)%4 == 0){ 13 | i++; 14 | n++; 15 | continue;} 16 | cout << 3*a+2 << endl; 17 | i++; 18 | } 19 | 20 | 21 | 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Train_and_Querues.cpp: -------------------------------------------------------------------------------- 1 | // This is a question from codeforces to find whether it is possible for train to travel from one station to the other. 2 | // The Question link is : 3 | // https://codeforces.com/contest/1702/problem/C 4 | 5 | // Solution to the above problem is- 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int t; 12 | cin>>t; 13 | while(t--){ 14 | int n,k; 15 | cin>>n>>k; 16 | multimapm,mm; 17 | vectorv; 18 | for(int i=0;i>p; 21 | v.push_back(p); 22 | m.insert({p,i}); 23 | } 24 | for(int i=n-1;i>=0;i--){ 25 | mm.insert({v[i],i}); 26 | } 27 | 28 | 29 | for(int i=0;i>a>>b; 32 | auto ita=m.find(a); 33 | if(ita!=m.end()){ 34 | a_pos=(*ita).second; 35 | } 36 | else{ 37 | cout<<"no"<a_pos || b_pos1>a_pos1 || b_pos>a_pos1 || b_pos1>a_pos){ 57 | cout<<"yes"< 2 | 3 | using namespace std; 4 | 5 | const int N = 1000009; 6 | 7 | int dp[N]; 8 | 9 | int func(int n){ 10 | if(dp[n]!=-1) 11 | return dp[n]; 12 | if(n<2) 13 | return n; 14 | if(n==2) 15 | return 1; 16 | else{ 17 | return dp[n] = func(n-1)+func(n-2)+func(n-3); 18 | } 19 | } 20 | 21 | int tribonacci(int n) { 22 | memset(dp, -1, sizeof(dp)); 23 | int ans = func(n); 24 | return ans; 25 | } 26 | 27 | int main() { 28 | 29 | int n; 30 | cin >> n; 31 | cout << tribonacci(n)<m; 6 | int a=nums.size(); 7 | for(int i=0;i &v) { 4 | // v = remove_duplicates(v); 5 | stackstk; 6 | int temp=-1; 7 | int root= INT_MIN; 8 | for(int i=0;i=stk.top() ){ 13 | root=stk.top(); 14 | stk.pop(); 15 | } 16 | stk.push(v[i]); 17 | 18 | } 19 | return 1; 20 | } 21 | // Here we find the next greater element and after finding next greater, if we find a smaller element, then return false. 22 | 23 | // Create an empty stack. 24 | // Initialize root as INT_MIN. 25 | // Do following for every element pre[i] 26 | // If pre[i] is smaller than current root, return false. 27 | // Keep removing elements from stack while pre[i] is greater 28 | // then stack top. Make the last removed item as new root (to 29 | // be compared next). 30 | // At this point, pre[i] is greater than the removed root 31 | // (That is why if we see a smaller element in step a), we 32 | // return false) 33 | // push pre[i] to stack (All elements in stack are in decreasing 34 | // order) 35 | -------------------------------------------------------------------------------- /backtrack-maxLexicographic.cpp: -------------------------------------------------------------------------------- 1 | Given a string A and integer B, what is maximal lexicographical string that can be made from A if you do atmost B swaps. 2 | 3 | void helper(string s, int b, string &str){ 4 | 5 | if(b<=0){ 6 | return ; 7 | } 8 | for(int i=0;is[i]){ 11 | swap(s[j],s[i]); 12 | if(s>str) 13 | str = s; 14 | helper(s,b-1,str); 15 | swap(s[j],s[i]); 16 | 17 | } 18 | } 19 | } 20 | } 21 | string Solution::solve(string s, int b) { 22 | string str = s; 23 | 24 | helper(s,b,str); 25 | 26 | return str; 27 | } 28 | -------------------------------------------------------------------------------- /backtrack-nQueen.cpp: -------------------------------------------------------------------------------- 1 | // The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 2 | 3 | 4 | bool corrPos(vector&board,int row,int col,int A) 5 | { 6 | for(int r=0;r=0 and c>=0;r--,c--)//in this line we chcek by going in left below 10 | if(board[r][c]=='Q') 11 | return false; 12 | for(int r=row,c=col;r>=0 and c >&ans,vector &board,int row,int A) 18 | { 19 | if(row==A) 20 | { 21 | ans.push_back(board); 22 | return; 23 | } 24 | for(int col=0;col >Solution::solveNQueens(int A) { 36 | vector >ans; 37 | string rows; 38 | vector board; 39 | for(int i=0;i>&v, vector&visited,vector&per,vector&arr){ 15 | if(per.size()==arr.size()){ 16 | v.push_back(per); 17 | return ; 18 | } 19 | for(int i=0;i > Solution::permute(vector &arr) { 30 | vector >v; 31 | vectorvisited(arr.size(),false); 32 | vectorper; 33 | solve(v,visited,per,arr); 34 | return v; 35 | } 36 | -------------------------------------------------------------------------------- /backtracking-subset.cpp: -------------------------------------------------------------------------------- 1 | /*Given a set of distinct integers, S, return all possible subsets. 2 | Example : 3 | 4 | If S = [1,2,3], a solution is: 5 | 6 | [ 7 | [], 8 | [1], 9 | [1, 2], 10 | [1, 2, 3], 11 | [1, 3], 12 | [2], 13 | [2, 3], 14 | [3], 15 | ] 16 | */ 17 | 18 | void solve(vector&visited, vectorarr,vector&v,vector>&ans,int index){ 19 | // if(v.size()==arr.size()){ 20 | ans.push_back(v); 21 | // return; 22 | // } 23 | for(int i=index;i > Solution::subsets(vector &arr) { 30 | vector>ans; 31 | sort(arr.begin(),arr.end()); 32 | if(arr.size()==0){ 33 | ans.push_back({}); 34 | return ans; 35 | } 36 | 37 | vectorvisited(arr.size(),false); 38 | vectorv; 39 | 40 | // ans.push_back({}); 41 | solve(visited,arr,v,ans,0); 42 | return ans; 43 | } 44 | -------------------------------------------------------------------------------- /bellmanford.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program for Bellman-Ford's single source 2 | // shortest path algorithm. 3 | #include 4 | using namespace std; 5 | 6 | // a structure to represent a weighted edge in graph 7 | struct Edge { 8 | int src, dest, weight; 9 | }; 10 | 11 | // a structure to represent a connected, directed and 12 | // weighted graph 13 | struct Graph { 14 | // V-> Number of vertices, E-> Number of edges 15 | int V, E; 16 | 17 | // graph is represented as an array of edges. 18 | struct Edge* edge; 19 | }; 20 | 21 | // Creates a graph with V vertices and E edges 22 | struct Graph* createGraph(int V, int E) 23 | { 24 | struct Graph* graph = new Graph; 25 | graph->V = V; 26 | graph->E = E; 27 | graph->edge = new Edge[E]; 28 | return graph; 29 | } 30 | 31 | // A utility function used to print the solution 32 | void printArr(int dist[], int n) 33 | { 34 | printf("Vertex Distance from Source\n"); 35 | for (int i = 0; i < n; ++i) 36 | printf("%d \t\t %d\n", i, dist[i]); 37 | } 38 | 39 | // The main function that finds shortest distances from src 40 | // to all other vertices using Bellman-Ford algorithm. The 41 | // function also detects negative weight cycle 42 | void BellmanFord(struct Graph* graph, int src) 43 | { 44 | int V = graph->V; 45 | int E = graph->E; 46 | int dist[V]; 47 | 48 | // Step 1: Initialize distances from src to all other 49 | // vertices as INFINITE 50 | for (int i = 0; i < V; i++) 51 | dist[i] = INT_MAX; 52 | dist[src] = 0; 53 | 54 | // Step 2: Relax all edges |V| - 1 times. A simple 55 | // shortest path from src to any other vertex can have 56 | // at-most |V| - 1 edges 57 | for (int i = 1; i <= V - 1; i++) { 58 | for (int j = 0; j < E; j++) { 59 | int u = graph->edge[j].src; 60 | int v = graph->edge[j].dest; 61 | int weight = graph->edge[j].weight; 62 | if (dist[u] != INT_MAX 63 | && dist[u] + weight < dist[v]) 64 | dist[v] = dist[u] + weight; 65 | } 66 | } 67 | 68 | // Step 3: check for negative-weight cycles. The above 69 | // step guarantees shortest distances if graph doesn't 70 | // contain negative weight cycle. If we get a shorter 71 | // path, then there is a cycle. 72 | for (int i = 0; i < E; i++) { 73 | int u = graph->edge[i].src; 74 | int v = graph->edge[i].dest; 75 | int weight = graph->edge[i].weight; 76 | if (dist[u] != INT_MAX 77 | && dist[u] + weight < dist[v]) { 78 | printf("Graph contains negative weight cycle"); 79 | return; // If negative cycle is detected, simply 80 | // return 81 | } 82 | } 83 | 84 | printArr(dist, V); 85 | 86 | return; 87 | } 88 | 89 | // Driver's code 90 | int main() 91 | { 92 | /* Let us create the graph given in above example */ 93 | int V = 5; // Number of vertices in graph 94 | int E = 8; // Number of edges in graph 95 | struct Graph* graph = createGraph(V, E); 96 | 97 | // add edge 0-1 (or A-B in above figure) 98 | graph->edge[0].src = 0; 99 | graph->edge[0].dest = 1; 100 | graph->edge[0].weight = -1; 101 | 102 | // add edge 0-2 (or A-C in above figure) 103 | graph->edge[1].src = 0; 104 | graph->edge[1].dest = 2; 105 | graph->edge[1].weight = 4; 106 | 107 | // add edge 1-2 (or B-C in above figure) 108 | graph->edge[2].src = 1; 109 | graph->edge[2].dest = 2; 110 | graph->edge[2].weight = 3; 111 | 112 | // add edge 1-3 (or B-D in above figure) 113 | graph->edge[3].src = 1; 114 | graph->edge[3].dest = 3; 115 | graph->edge[3].weight = 2; 116 | 117 | // add edge 1-4 (or B-E in above figure) 118 | graph->edge[4].src = 1; 119 | graph->edge[4].dest = 4; 120 | graph->edge[4].weight = 2; 121 | 122 | // add edge 3-2 (or D-C in above figure) 123 | graph->edge[5].src = 3; 124 | graph->edge[5].dest = 2; 125 | graph->edge[5].weight = 5; 126 | 127 | // add edge 3-1 (or D-B in above figure) 128 | graph->edge[6].src = 3; 129 | graph->edge[6].dest = 1; 130 | graph->edge[6].weight = 1; 131 | 132 | // add edge 4-3 (or E-D in above figure) 133 | graph->edge[7].src = 4; 134 | graph->edge[7].dest = 3; 135 | graph->edge[7].weight = -3; 136 | 137 | // Function call 138 | BellmanFord(graph, 0); 139 | 140 | return 0; 141 | } 142 | -------------------------------------------------------------------------------- /binarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | int findELement(int arr[],int n,int key) 7 | { 8 | 9 | int s=0; 10 | int e=arr.size()-1; 11 | 12 | 13 | while(s<=e) 14 | { 15 | int mid=s+(e-s)/2; 16 | if(arr[mid]==key) 17 | { 18 | return mid; 19 | } 20 | else if(arr[mid]>n; 38 | for(int i=0;i>arr[i]; 41 | } 42 | cout<<"Enter the element to be searched"; 43 | int key; 44 | cin>>key; 45 | cout< 0) { 23 | if (b & 1) 24 | res = res * a; 25 | a = a * a; 26 | b >>= 1; 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /breadth-first-search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program implementing BFS (Breadth First Search) 2 | // BFS is a traversal technique where level wise traversal take place where nodes in higher level are visited once all the nodes in lower levels are visited. 3 | // Queue data structure is used in this technique. 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int N = 1e5; 10 | vector g[N]; // adjacency list 11 | int visited[N]; 12 | 13 | void bfs(int source){ 14 | queue q; 15 | q.push(source); 16 | visited[source] = 1; 17 | 18 | // From source vertex : 19 | // 1. remove the firrst vertex of queue. 20 | // 2. mark the vertex as visited. 21 | // 3. Insert all unvisited nwighbours of vertex into queue. 22 | 23 | while (!q.empty()){ 24 | int current_node = q.front(); 25 | cout << current_node << " "; 26 | q.pop(); 27 | for(int child: g[current_node]){ 28 | if(!visited[child]){ 29 | q.push(child); 30 | visited[child] = 1; 31 | } 32 | } 33 | } 34 | 35 | } 36 | 37 | int main(){ 38 | 39 | int nodes, edges; 40 | cout << "Enter number of nodes and edges : "; 41 | cin >> nodes >> edges; 42 | 43 | cout << "Enter "<< edges << " pairs of src, dest vertices of a edge : "; 44 | for(int i=0; i< edges; i++){ 45 | int x,y; 46 | cin >> x >> y; 47 | g[x].push_back(y); 48 | } 49 | 50 | // assuming nodes start from 0 and assuming 0 as source vertex here 51 | cout << "Nodes are : " ; 52 | bfs(0); 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /bubble_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Bubble Sort 2 | 3 | def bubbleSort(arr): 4 | n = len(arr) 5 | # optimize code, so if the array is already sorted, it doesn't need 6 | # to go through the entire process 7 | swapped = False 8 | # Traverse through all array elements 9 | for i in range(n-1): 10 | # range(n) also work but outer loop will 11 | # repeat one time more than needed. 12 | # Last i elements are already in place 13 | for j in range(0, n-i-1): 14 | 15 | # traverse the array from 0 to n-i-1 16 | # Swap if the element found is greater 17 | # than the next element 18 | if arr[j] > arr[j + 1]: 19 | swapped = True 20 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 21 | 22 | if not swapped: 23 | # if we haven't needed to make a single swap, we 24 | # can just exit the main loop. 25 | return 26 | 27 | 28 | # Driver code to test above 29 | arr = [64, 34, 25, 12, 22, 11, 90] 30 | 31 | bubbleSort(arr) 32 | 33 | print("Sorted array is:") 34 | for i in range(len(arr)): 35 | print("% d" % arr[i], end=" ") 36 | -------------------------------------------------------------------------------- /climbing_stairs.cpp: -------------------------------------------------------------------------------- 1 | //You are climbing a staircase. It takes n steps to reach the top. 2 | //Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top 3 | 4 | #include 5 | using namespace std; 6 | 7 | int waysToReachTop(int n, vector &dp){ 8 | if(n==0) return 1; 9 | if(dp[n]!=-1) return dp[n]; 10 | int ans=waysToReachTop(n-1, dp); 11 | if(n>=2) ans+=waysToReachTop(n-2, dp); 12 | return dp[n]=ans; 13 | } 14 | 15 | 16 | int main(){ 17 | int n; 18 | cin>>n; 19 | vector dp(n+1, -1); 20 | cout<<"Number of ways to reach the top is - "< 2 | using namespace std; 3 | 4 | #define int long long 5 | #define F first 6 | #define S second 7 | #define pb push_back 8 | #define pqa priority_queue, greater> 9 | #define pqd priority_queue 10 | 11 | #define all(x) x.begin(), x.end() 12 | #define sort(x) sort(all(x)) 13 | #define reverse(x) reverse(all(x)) 14 | #define minimum(x) *min_element(all(x)) 15 | #define maximum(x) *max_element(all(x)) 16 | 17 | void invec(vector &vec, int n) 18 | { 19 | for (int i = 0; i < n; i++) 20 | { 21 | int x; 22 | cin >> x; 23 | vec.pb(x); 24 | } 25 | } 26 | void printvec(vector &vec) 27 | { 28 | for (int i = 0; i < vec.size(); i++) 29 | { 30 | cout << vec[i] << " "; 31 | } 32 | } 33 | 34 | int32_t main() 35 | { 36 | ios_base::sync_with_stdio(false); 37 | cin.tie(NULL); 38 | int t; 39 | cin >> t; 40 | while (t--) 41 | { 42 | int n; 43 | cin>>n; 44 | int i=1,j=n; 45 | while(n>0){ 46 | cout< 2 | using namespace std; 3 | 4 | #define int long long 5 | #define F first 6 | #define S second 7 | #define pb push_back 8 | #define pqa priority_queue, greater> 9 | #define pqd priority_queue 10 | 11 | #define all(x) x.begin(), x.end() 12 | #define sort(x) sort(all(x)) 13 | #define reverse(x) reverse(all(x)) 14 | #define minimum(x) *min_element(all(x)) 15 | #define maximum(x) *max_element(all(x)) 16 | void invec(vector &vec, int n) 17 | { 18 | for (int i = 0; i < n; i++) 19 | { 20 | int x; 21 | cin >> x; 22 | vec.pb(x); 23 | } 24 | } 25 | void printvec(vector &vec) 26 | { 27 | for (int i = 0; i < vec.size(); i++) 28 | { 29 | cout << vec[i] << " "; 30 | } 31 | } 32 | 33 | int32_t main() 34 | { 35 | ios_base::sync_with_stdio(false); 36 | cin.tie(NULL); 37 | int t; 38 | cin >> t; 39 | while (t--) 40 | { 41 | int n; 42 | cin>>n; 43 | vector vec(n+1,0),vec2; 44 | for(int i=1;i<=n;i++){ 45 | int x,y; 46 | cin>>x>>y; 47 | for(int j=x;j<=y;j++){ 48 | if(i==j) vec[j]=-1; 49 | else if(j!=i){ 50 | if(vec[j]==-1) continue; 51 | else vec[j]++; 52 | } 53 | } 54 | } 55 | 56 | int maxi=maximum(vec); 57 | int cnt=0; 58 | for(int i=1;i<=n;i++){ 59 | if(vec[i]==maxi){ 60 | vec2.pb(i); 61 | cnt++; 62 | } 63 | } 64 | cout< 2 | using namespace std; 3 | 4 | #define int long long 5 | #define F first 6 | #define S second 7 | #define pb push_back 8 | #define pqa priority_queue, greater> 9 | #define pqd priority_queue 10 | 11 | #define all(x) x.begin(), x.end() 12 | #define sort(x) sort(all(x)) 13 | #define reverse(x) reverse(all(x)) 14 | #define minimum(x) *min_element(all(x)) 15 | #define maximum(x) *max_element(all(x)) 16 | void invec(vector &vec, int n) 17 | { 18 | for (int i = 0; i < n; i++) 19 | { 20 | int x; 21 | cin >> x; 22 | vec.pb(x); 23 | } 24 | } 25 | void printvec(vector &vec) 26 | { 27 | for (int i = 0; i < vec.size(); i++) 28 | { 29 | cout << vec[i] << " "; 30 | } 31 | } 32 | 33 | int32_t main() 34 | { 35 | ios_base::sync_with_stdio(false); 36 | cin.tie(NULL); 37 | int t; 38 | cin >> t; 39 | while (t--) 40 | { 41 | int a,b,c,d,e,f,n,m,p,q,r,s,x,y,z; 42 | cin>>n; 43 | if(n==3) cout<<-1< 2 | using namespace std; 3 | #define PI 3.1415926535897932384626433832795 4 | #define MOD 1000000007 5 | #define pb push_back 6 | #define rep(i,a,b) for(int i=a;i 8 | #define vi vector 9 | #define lb lower_bound 10 | #define ub upper_bound 11 | #define print(ans) printf("%.9f\n",ans) 12 | #define all(x) (x).begin(), (x).end() 13 | typedef int64_t ll; 14 | typedef unsigned long long ull; 15 | typedef long double lld; 16 | #define pi pair 17 | #define nline "\n" 18 | 19 | //========================================Debugging Starts================================= 20 | 21 | #ifndef ONLINE_JUDGE 22 | #define debug(x) cerr << #x <<" "; _print(x); cerr << "\n"; 23 | #else 24 | #define debug(x) 25 | #endif 26 | void _print(ll t) {cerr << t;} 27 | void _print(int t) {cerr << t;} 28 | void _print(string t) {cerr << t;} 29 | void _print(char t) {cerr << t;} 30 | void _print(lld t) {cerr << t;} 31 | void _print(double t) {cerr << t;} 32 | void _print(ull t) {cerr << t;} 33 | 34 | template void _print(pair p); 35 | template void _print(vector v); 36 | template void _print(set v); 37 | template void _print(map v); 38 | template void _print(multiset v); 39 | template void _print(pair p) {cerr << "{"; _print(p.first); cerr << ","; _print(p.second); cerr << "}";} 40 | template void _print(vector v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} 41 | template void _print(set v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} 42 | template void _print(multiset v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} 43 | template void _print(map v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} 44 | 45 | //==========================================Debugging Ends========================================== 46 | 47 | // vector> vec( n , vector (m, 0)); 48 | // priority_queue, greater>q; 49 | 50 | bool prime[100000]; 51 | ll gcd(ll a, ll b) { 52 | if (b == 0) 53 | return a; 54 | return gcd(b, a % b); 55 | } 56 | void SieveOfEratosthenes() 57 | { 58 | memset(prime, true, sizeof(prime)); 59 | 60 | for (int p = 2; p * p <= 100000; p++) 61 | { 62 | if (prime[p] == true) 63 | { 64 | for (int i = p * p; i <= 100000; i += p) 65 | prime[i] = false; 66 | } 67 | } 68 | } 69 | long long binpow(long long a, long long b) { 70 | a %= MOD; 71 | long long res = 1; 72 | while (b > 0) { 73 | if (b & 1) 74 | res = res * a % MOD; 75 | a = a * a % MOD; 76 | b >>= 1; 77 | } 78 | return res % MOD 79 | ; 80 | } 81 | ll invmd(ll n) 82 | { 83 | return (binpow(n, MOD - 2)); 84 | } 85 | ll ceil2(ll a, ll b) { 86 | return (a + b - 1) / b; 87 | } 88 | // const int N=1e5+5; 89 | // ll fact[N]; 90 | // void calcfactorial() 91 | // { 92 | // fact[0]=1; 93 | // rep(i,1,N-1) 94 | // { 95 | // fact[i]=(fact[i-1]*i)%MOD; 96 | 97 | // } 98 | // } 99 | // ll ncr(ll n, ll k) { 100 | // return fact[n] * invmd(fact[k] * fact[n - k] % MOD) % MOD; 101 | // } 102 | 103 | void solve() 104 | { 105 | int b, w; 106 | cin >> b >> w; 107 | if(b+w==1) 108 | { 109 | if(b==1) 110 | { 111 | 112 | cout<<'B'<ans(n + 1, 0); 135 | vector>edges; 136 | if (b > w) 137 | { 138 | ans[2] = 'B'; 139 | ans[3] = 'B'; 140 | ans[1] = 'W'; 141 | b = b - 2; 142 | w = w - 1; 143 | edges.pb({1, 2}); 144 | edges.pb({1, 3}); 145 | 146 | 147 | 148 | } 149 | else 150 | { 151 | ans[2] = 'W'; 152 | ans[3] = 'W'; 153 | ans[1] = 'B'; 154 | w = w - 2; 155 | b = b - 1; 156 | edges.pb({1, 2}); 157 | edges.pb({1, 3}); 158 | 159 | } 160 | int node = 4; 161 | while (b--) 162 | { 163 | ans[node] = 'B'; 164 | edges.pb({1,node}); 165 | node++; 166 | 167 | } 168 | while (w--) 169 | { 170 | edges.pb({1,node}); 171 | 172 | ans[node] = 'W'; 173 | node++; 174 | 175 | } 176 | // debug(ans); 177 | for(int i=1;i> t; 201 | while (t--) 202 | { 203 | solve(); 204 | } 205 | return 0; 206 | } -------------------------------------------------------------------------------- /codechefSolutions/long/May1/attackofqueen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t; 7 | while (t--) { 8 | int n,x,y; 9 | cin >> n >> x >> y; 10 | 11 | int a = x - 1; 12 | int b = n - y; 13 | int c = n - x; 14 | int d = y - 1; 15 | 16 | int e = min(a,b); 17 | int f = min(b,c); 18 | int g = min(c,d); 19 | int h = min(a,d); 20 | 21 | int ans = 2*(n - 1) + e + f + g + h; 22 | 23 | cout << ans << endl; 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /codechefSolutions/long/May1/footballCup.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | int x,y; 10 | cin>>x>>y; 11 | if(x > 0 && y > 0 && x == y)cout<<"YES"< 2 | using namespace std; 3 | #define ll long long 4 | const int mod=1e9 + 7; 5 | ll n=1000009; 6 | vectorfact(n,1); 7 | 8 | void start(){ 9 | for(int i=1;i0){ 17 | if(b&1) 18 | res=(res*a)%p; 19 | a=(a*a)%p; 20 | b>>=1; 21 | } 22 | return res; 23 | 24 | } 25 | ll inverse(ll a ,ll n){ 26 | return binpow(a,n-2,n); 27 | } 28 | ll ncr(ll n , ll r){ 29 | if(n < r|| (n < 0) || (r < 0)) return 0 ; 30 | return ((((fact[n] * inverse(fact[r] , mod)) % mod) * inverse(fact[n-r] , mod)) % mod); 31 | } 32 | ll get_ans(ll n, ll x) 33 | { 34 | ll one=n+x; 35 | if(one%2==1) return 0 ; 36 | one/=2; 37 | 38 | return ncr(n,min(one,n-one)) ; 39 | } 40 | 41 | 42 | 43 | void solve(){ 44 | ll n,l,r; 45 | cin>>n>>l>>r; 46 | for(int i=l;i<=r;i++){ 47 | ll ans=get_ans(n,i); 48 | 49 | if(i==l) cout << ans; 50 | else cout << ' ' << ans; 51 | 52 | } 53 | } 54 | 55 | int main(){ 56 | ios_base::sync_with_stdio; 57 | cin.tie(NULL);cout.tie(NULL); 58 | start(); 59 | ll t=1; 60 | cin>>t; 61 | while(t--){ 62 | solve(); 63 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int x,y; 10 | float a; 11 | cin>>x>>y; 12 | a=(float)107*x/100; 13 | if(y<=a) 14 | { 15 | cout<<"YES"<> t; 13 | while (t--) { 14 | int n; cin >> n; 15 | vector a(n); 16 | for (int &x : a) cin >> x; 17 | sort(begin(a), end(a)); 18 | int ans = 0; 19 | for (int i = 0; i < n; ) { 20 | int j = i; 21 | while (j < n and a[j] == a[i]) ++j; 22 | ans = max(ans, a[i] + j - i - 1); 23 | i = j; 24 | } 25 | cout << ans << '\n'; 26 | } 27 | } -------------------------------------------------------------------------------- /codechefSolutions/long/May1/sugarcane.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | int n,res; 10 | cin>>n; 11 | res = n*50; 12 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int t,i; 7 | cin>>t; 8 | while(t--) 9 | { int n,k; 10 | cin>>n>>k; 11 | if(n==1 && k==1)cout<<"1"; 12 | else{ 13 | if(k<2 || k>n)cout<<"-1"; 14 | else{ int y=0; 15 | for(i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int x,y; 10 | cin>>x>>y; 11 | if(xy) 16 | { 17 | cout<<"new phone"< 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | int t; 7 | cin>>t; 8 | while(t--) 9 | { 10 | int x; 11 | cin>>x; 12 | if(x>98) 13 | { 14 | cout<<"YES"< 2 | using namespace std; 3 | 4 | int main() { 5 | int test; 6 | cin>>test; 7 | while(test--){ 8 | int n; 9 | cin>>n; 10 | string s; 11 | cin>>s; 12 | int answer=n; 13 | for(int i=1; i 2 | #define ll long long 3 | #define f(i,a,b) for(ll i = (a); i <= (b); i++) 4 | #define fr(i,a,b) for(ll i = (a); i >= (b); i--) 5 | #define all(x) x.begin(),x.end() 6 | #define sz(x) (ll)x.size() 7 | #define pb push_back 8 | #define F first 9 | #define S second 10 | #define vi vector 11 | #define inf 1e9+5 12 | #define yes cout<<"YES" 13 | #define no cout<<"NO" 14 | #define nn "\n" 15 | using namespace std; 16 | int main(){ 17 | 18 | ll test; cin>>test; 19 | f(ttt,1,test){ 20 | // cout << "Case #" << ttt << ": "; 21 | 22 | ll n; cin>>n; 23 | string s; cin>>s; 24 | ll steps=0, ones=0, zeros=0, x, st=0, en=0, c1=0, c=0; 25 | f(i,0,n-1){ 26 | if(s[i]=='0') zeros++; 27 | else ones++; 28 | } 29 | if(n==1) {cout<<"1 0"<> ans; 32 | while(1){ 33 | while(s[st]=='2') st++; 34 | en=st+1; 35 | while(s[en]=='2') en++, c1++; 36 | x=s[st]-'0'+s[en]-'0'; 37 | vi v; 38 | if(ones==zeros) { 39 | v.pb(1), v.pb(ones+zeros), v.pb(1); 40 | ans.pb(v); 41 | break; 42 | } 43 | if(x==1) ones--, zeros--; 44 | if(x==1 && oneszeros){ 53 | v.pb(st+1-c), v.pb(st+2-c), v.pb(0), ans.pb(v); 54 | zeros++; 55 | s[st]='0'; 56 | s[en]='2'; 57 | st=0; 58 | en=0; 59 | c1=0; 60 | }else{ 61 | st=en; 62 | en=0; 63 | c=c1; 64 | } 65 | // cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t;cin>>t; 6 | while(t--){ 7 | int arr[4]; 8 | int a=0,i=0; 9 | for(int i=0;i<4;i++){ 10 | cin>>arr[i]; 11 | 12 | } 13 | for(int j=0;j<4;j++){ 14 | if(arr[j]==1){ 15 | cout<<"OUT"< 2 | using namespace std; 3 | 4 | int main() { 5 | int d; 6 | cin>>d; 7 | if(d%2!=0)cout<<"-1"; 8 | else 9 | { 10 | cout<<"0"<<" "< 2 | using namespace std; 3 | 4 | int main() { 5 | int t,n; 6 | cin>>t; 7 | while(t--) 8 | { 9 | cin>>n; 10 | if(n%4==0)cout<<"good"<>arr[i]; 2 | sort(arr,arr+3); 3 | 4 | if(arr[0]+arr[1]==arr[2])cout<<"yes"< 2 | using namespace std; 3 | # define ll long long int 4 | 5 | int main() { 6 | // your code goes here 7 | ios_base::sync_with_stdio(false); 8 | cin.tie(NULL); 9 | int numTests; 10 | cin >> numTests; 11 | while(numTests-- ) 12 | { 13 | int array[3]; 14 | for (int i = 0; i < 3; i++) 15 | { 16 | cin >> array[i]; 17 | if (array[i] > 3) 18 | { 19 | array[i] = 3; 20 | } 21 | } 22 | sort(array, array + 3); 23 | int result = 0; 24 | for (int i = 0; i < 3; i++) 25 | { 26 | result += (array[i] > 0); 27 | array[i] -= (array[i] > 0); 28 | } 29 | if (array[2] && array[1]) 30 | { 31 | result++ ; 32 | array[2]--; 33 | array[1]-- ; 34 | } 35 | if (array[0] && array[2]) 36 | { 37 | result++ ; 38 | array[0]--; 39 | array[2]-- ; 40 | } 41 | if (array[0] && array[1]) 42 | { 43 | result++ ; 44 | array[0]--; 45 | array[1]-- ; 46 | } 47 | cout << result << endl; 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /codechefSolutions/straters/56/Nearest Exit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | int main() { 5 | // your code goes here 6 | ll t; 7 | cin>>t; 8 | while(t--) 9 | { 10 | ll n; 11 | cin>>n; 12 | if(n<51) 13 | cout<<"LEFT\n"; 14 | else 15 | cout<<"RIGHT\n"; 16 | } 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /codechefSolutions/straters/56/SUBPERM.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int test; 6 | cin>>test; 7 | while(test--){ 8 | int n,k; 9 | cin>>n>>k; 10 | if(n==1 && k==1)cout<<"1"<n)cout<<"-1"< 2 | #define ll long long int 3 | #define pb push_back 4 | #define mp make_pair 5 | #define mod 1000000007 6 | #define vl vector 7 | #define all(c) (c).begin(),(c).end() 8 | using namespace std; 9 | ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} 10 | ll modInverse(ll a){return power(a,mod-2);} 11 | const int N=500023; 12 | bool vis[N]; 13 | vector adj[N]; 14 | long long readInt(long long l,long long r,char endd){ 15 | long long x=0; 16 | int cnt=0; 17 | int fi=-1; 18 | bool is_neg=false; 19 | while(true){ 20 | char g=getchar(); 21 | if(g=='-'){ 22 | assert(fi==-1); 23 | is_neg=true; 24 | continue; 25 | } 26 | if('0'<=g && g<='9'){ 27 | x*=10; 28 | x+=g-'0'; 29 | if(cnt==0){ 30 | fi=g-'0'; 31 | } 32 | cnt++; 33 | assert(fi!=0 || cnt==1); 34 | assert(fi!=0 || is_neg==false); 35 | 36 | assert(!(cnt>19 || ( cnt==19 && fi>1) )); 37 | } else if(g==endd){ 38 | if(is_neg){ 39 | x= -x; 40 | } 41 | 42 | if(!(l <= x && x <= r)) 43 | { 44 | cerr << l << ' ' << r << ' ' << x << '\n'; 45 | assert(1 == 0); 46 | } 47 | 48 | return x; 49 | } else { 50 | assert(false); 51 | } 52 | } 53 | } 54 | string readString(int l,int r,char endd){ 55 | string ret=""; 56 | int cnt=0; 57 | while(true){ 58 | char g=getchar(); 59 | assert(g!=-1); 60 | if(g==endd){ 61 | break; 62 | } 63 | cnt++; 64 | ret+=g; 65 | } 66 | assert(l<=cnt && cnt<=r); 67 | return ret; 68 | } 69 | long long readIntSp(long long l,long long r){ 70 | return readInt(l,r,' '); 71 | } 72 | long long readIntLn(long long l,long long r){ 73 | return readInt(l,r,'\n'); 74 | } 75 | string readStringLn(int l,int r){ 76 | return readString(l,r,'\n'); 77 | } 78 | string readStringSp(int l,int r){ 79 | return readString(l,r,' '); 80 | } 81 | void solve() 82 | { 83 | vector a(3); 84 | a[0]=readInt(0,100,' '); 85 | a[1]=readInt(0,100,' '); 86 | a[2]=readInt(0,100,'\n'); 87 | 88 | sort(a.rbegin(), a.rend()); 89 | int ans = 0; 90 | 91 | for(int i = 0; i<3; i++) { 92 | if(a[i]){ 93 | ans++; 94 | a[i]--; 95 | } 96 | } 97 | 98 | for(int i = 0; i<3; i++) { 99 | for(int j = i+1; j<3; j++) { 100 | if(a[i] && a[j]) { 101 | ans++; 102 | a[i]--; 103 | a[j]--; 104 | } 105 | } 106 | } 107 | cout<> facs(MX); 14 | vector val(MX); 15 | for (int i = 1; i < MX; ++i) for (int j = i; j < MX; j += i) { 16 | facs[j].push_back(i); 17 | if (j > i) val[j] = 1 + val[i]; 18 | } 19 | 20 | int t; cin >> t; 21 | while (t--) { 22 | int n; cin >> n; 23 | vector a(n+1); 24 | a[0] = 1; 25 | for (int i = 1; i <= n; ++i) { 26 | cin >> a[i]; 27 | } 28 | 29 | const int SZ = 210; 30 | array dp{}; 31 | int ans = 0; 32 | for (int i = 1; i <= n; ++i) { 33 | array curdp{}; 34 | int ptr = 0, mn = INT_MAX; 35 | ans = INT_MAX; 36 | auto &prv = facs[a[i-1]]; 37 | auto &cur = facs[a[i]]; 38 | for (int j = 0; j < cur.size(); ++j) { 39 | int d = cur[j]; 40 | while (ptr < prv.size()) { 41 | if (prv[ptr] <= d) { 42 | mn = min(mn, dp[ptr]); 43 | ++ptr; 44 | } 45 | else break; 46 | } 47 | curdp[j] = mn + val[a[i]/d]; 48 | ans = min(ans, curdp[j]); 49 | } 50 | swap(dp, curdp); 51 | } 52 | cout << ans << '\n'; 53 | } 54 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/56/encode_easy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | typedef double db; 14 | typedef long long ll; 15 | typedef unsigned long long ull; 16 | const int N=1000010; 17 | const int LOGN=28; 18 | const ll TMD=0; 19 | const ll INF=2147483647; 20 | int n,q,cur; 21 | int a[N],key[N],tag[N],enough[N],tot[N]; 22 | ll ans[N]; 23 | vector val; 24 | vector G[N]; 25 | 26 | struct query 27 | { 28 | int t,id; 29 | ll k; 30 | 31 | query() {} 32 | 33 | query(int t,ll k,int id):t(t),k(k),id(id) {} 34 | }; 35 | vector Q[N]; 36 | 37 | void DFS(int x,int pre) 38 | { 39 | tot[x]=tot[pre]+enough[x]; 40 | for(int i=0;i() ); 79 | for(int i=0;i=val[i]) enough[j]=1; 82 | DFS(1,0); 83 | for(int j=1;j<=n;j++) 84 | { 85 | for(int k=0;k=qu.t) 89 | { 90 | ll L=0,R=(ll)sqrt(qu.k/val[i]*2+1)+2,M; 91 | while(L+1!=R) 92 | { 93 | M=(L+R)>>1; 94 | if(M*(1+M)/2*val[i]>=qu.k) R=M; 95 | else L=M; 96 | } 97 | ans[qu.id]=R; 98 | } 99 | } 100 | } 101 | } 102 | for(int i=1;i<=q;i++) printf("%lld\n",ans[i]); 103 | } 104 | 105 | int main() 106 | { 107 | init(); 108 | solve(); 109 | 110 | return 0; 111 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/56/encode_hard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | typedef double db; 14 | typedef long long ll; 15 | typedef unsigned long long ull; 16 | const int N=1000010; 17 | const int LOGN=28; 18 | const ll TMD=0; 19 | const ll INF=2147483647; 20 | int n,q,cur; 21 | int a[N],key[N],tag[N],enough[N],tot[N]; 22 | ll ans[N]; 23 | vector val; 24 | vector G[N]; 25 | 26 | struct query 27 | { 28 | int t,id; 29 | ll k; 30 | 31 | query() {} 32 | 33 | query(int t,ll k,int id):t(t),k(k),id(id) {} 34 | }; 35 | vector Q[N]; 36 | 37 | void DFS(int x,int pre) 38 | { 39 | tot[x]=tot[pre]+enough[x]; 40 | for(int i=0;i() ); 79 | for(int i=0;i=val[i]) enough[j]=1; 82 | DFS(1,0); 83 | for(int j=1;j<=n;j++) 84 | { 85 | for(int k=0;k=qu.t) 89 | { 90 | ll L=0,R=(ll)sqrt(qu.k/val[i]*2+1)+2,M; 91 | while(L+1!=R) 92 | { 93 | M=(L+R)>>1; 94 | if(M*(1+M)/2*val[i]>=qu.k) R=M; 95 | else L=M; 96 | } 97 | ans[qu.id]=R; 98 | } 99 | } 100 | } 101 | } 102 | for(int i=1;i<=q;i++) printf("%lld\n",ans[i]); 103 | } 104 | 105 | int main() 106 | { 107 | init(); 108 | solve(); 109 | 110 | return 0; 111 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/56/faraway.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int t; 5 | cin>>t; 6 | while(t--){ 7 | long long int n,m; 8 | cin>>n>>m; 9 | long long int arr[n]; 10 | for(long long int i=0;i>arr[i]; 12 | } 13 | long long int A=0; 14 | for(long long int i=0;i 2 | using namespace std; 3 | 4 | int gcd (int a, int b) { 5 | if (b == 0) 6 | return a; 7 | else 8 | return gcd (b, a % b); 9 | } 10 | 11 | int main(){ 12 | 13 | int t; 14 | cin >> t; 15 | 16 | while(t--){ 17 | 18 | int n, k; 19 | cin >> n >> k; 20 | 21 | vector v(n); 22 | int G = 0; 23 | 24 | for(int i = 0; i < n; i++){ 25 | cin >> v[i]; 26 | G = gcd(G, v[i]); 27 | } 28 | 29 | int currG = 0, count = 0; 30 | 31 | for(int i = 0; i < n; i++){ 32 | currG = gcd(currG, v[i]); 33 | if(currG == G){ 34 | count++; 35 | currG = 0; 36 | } 37 | if(count == k) break; 38 | } 39 | 40 | if(count == k){ 41 | cout << "YES\n"; 42 | } 43 | else{ 44 | cout << "NO\n"; 45 | } 46 | 47 | } 48 | return 0; 49 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/56/palswap.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kritsid/competetive-programming/8920a76d8d08edf538f9db5289ed11ae74fa080d/codechefSolutions/straters/56/palswap.cpp -------------------------------------------------------------------------------- /codechefSolutions/straters/56/subsbin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | //freopen("inp3.in", "r", stdin); 6 | //freopen("out3.txt", "w", stdout); 7 | int t; 8 | cin >> t; 9 | while(t--) { 10 | int n; 11 | cin >> n; 12 | string s; 13 | cin >> s; 14 | int c[2] = {0, 0}; 15 | for(int i = 0; i < s.size(); i++) c[s[i] - '0']++; 16 | if(c[0] && c[1]) { 17 | cout << "1 " << max(c[0], c[1]) - min(c[0], c[1]) + 1 << "\n"; 18 | while(c[0] != c[1]) { 19 | string now = ""; 20 | int flag = 1; 21 | for(int i = 0; i < s.size(); i++) { 22 | if(s[i] != s[i + 1] && flag) { 23 | flag = 0; 24 | cout << i + 1 << " " << i + 2 << " "; 25 | if(c[0] > c[1]) cout << "1\n", c[1]++, now += '1'; 26 | else cout << "0\n", c[0]++, now += '0'; 27 | i++; 28 | } else now += s[i]; 29 | } 30 | s = now; 31 | } 32 | cout << "1 " << s.size() << " 0\n"; 33 | } else cout << s.size() << " 0\n"; 34 | } 35 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/CHEFPROFIT.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int test,x,y,z,profit; 6 | cin>>test; 7 | while(test--) 8 | { 9 | cin>>x>>y>>z; 10 | profit=x*(z-y); 11 | cout<< profit< 2 | #include 3 | #define ll long long int 4 | using namespace std; 5 | 6 | 7 | bool static cmp(ll a,ll b){ 8 | return a>b; 9 | } 10 | int main() { 11 | // your code goes here 12 | ll t; 13 | cin>>t; 14 | 15 | while(t--){ 16 | ll n; 17 | cin>>n; 18 | 19 | vectorv(n+1);// flavour input 20 | for(ll i=1;i>v[i]; 21 | 22 | vectorpre(n+1,0); 23 | for(ll i=1;i>q; 28 | 29 | map>>mp; 30 | 31 | for(ll i=0;i>a>>b; 34 | mp[a].insert({b,i}); 35 | } 36 | 37 | 38 | vectorres(q);// storing ans in it 39 | for(auto it:mp){ 40 | set>query=it.second; 41 | ll p=it.first; 42 | 43 | vectorprep(n+1,0);// store prefix sum of multiples of prefix 44 | vectorcntp(n+1,0);// store number of multiples of p in it 45 | vectordiv;// store multiples of p in it 46 | 47 | 48 | for(ll i=1;ipren(div.size()+1,0);// at index k will give k largest element sum 64 | 65 | for(ll i=1;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | int test; 8 | cin>>test; 9 | while(test--){ 10 | long int n,element,ans,sum=0; 11 | cin>>n; 12 | long int arr[n]; 13 | 14 | for(int i=0;i>element; 16 | sum=sum+element; 17 | arr[i]=sum; 18 | } 19 | ans = sum; 20 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | int t,n,x,y,i; 6 | cin>>t; 7 | while(t--) 8 | { 9 | cin>>n>>x>>y; 10 | int a[n],b[n]; 11 | for(i=0;i>a[i]; 12 | for(i=0;i>b[i]; 13 | int z=0; 14 | for(i=0;i 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | 11 | int n, m; 12 | cin >> n >> m; 13 | if (n >= 2 * m) 14 | { 15 | cout << "YES" << endl; 16 | } 17 | else 18 | cout << "NO" << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/evensplits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | while (t--) 13 | { 14 | int n; 15 | cin >> n; 16 | string s; 17 | cin >> s; 18 | bool hasZO = false; 19 | bool hasOO = false; 20 | for (int i = 0; i < s.length() - 1; i++) 21 | { 22 | if (s[i] == '0' && s[i + 1] == '1') 23 | hasZO = true; 24 | if (s[i] == '0' && s[i + 1] == '0') 25 | hasZO = true; 26 | if (s[i] == '1' && s[i + 1] == '1') 27 | hasOO = true; 28 | } 29 | if (hasZO || (hasOO && s[n - 1] == '0')) 30 | { 31 | sort(s.begin(), s.end()); 32 | } 33 | cout << s << endl; 34 | } 35 | return 0; 36 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/maximumexpression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | while (t--) 13 | { 14 | int n; 15 | cin >> n; 16 | string s; 17 | cin >> s; 18 | int pluses = 0, minuses = 0; 19 | string ans = ""; 20 | priority_queue pq; 21 | for (int i = 0; i < n; i++) 22 | { 23 | if (s[i] == '+') 24 | pluses++; 25 | else if (s[i] == '-') 26 | minuses++; 27 | else 28 | pq.push(s[i] - '0'); 29 | } 30 | int m = pq.size(); 31 | for (int i = 0; i < m - pluses - minuses; i++) 32 | { 33 | ans += to_string(pq.top()); 34 | pq.pop(); 35 | } 36 | while (pluses--) 37 | { 38 | ans += '+' + to_string(pq.top()); 39 | pq.pop(); 40 | } 41 | while (minuses--) 42 | { 43 | ans += '-' + to_string(pq.top()); 44 | pq.pop(); 45 | } 46 | cout << ans << endl; 47 | } 48 | return 0; 49 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/nonnegative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | while (t--) 13 | { 14 | int n; 15 | cin >> n; 16 | int arr[n]; 17 | for (int i = 0; i < n; i++) 18 | { 19 | cin >> arr[i]; 20 | } 21 | int neg = 0; 22 | bool hasZero = false; 23 | for (int i = 0; i < n; i++) 24 | { 25 | if (arr[i] < 0) 26 | neg++; 27 | if (arr[i] == 0) 28 | hasZero = true; 29 | } 30 | if (neg % 2 == 0 || hasZero) 31 | { 32 | cout << 0 << endl; 33 | } 34 | else 35 | { 36 | cout << 1 << endl; 37 | } 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/sumneq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | cout << t - 1; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/57/twodiffpallindormes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void iA(int arr[], int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | cin >> arr[i]; 7 | } 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | while (t--) 13 | { 14 | int a, b; 15 | cin >> a >> b; 16 | if (a == 1 || b == 1) 17 | cout << "NO" << endl; 18 | else if (a % 2 != 0 && b % 2 != 0) 19 | cout << "NO" << endl; 20 | else 21 | cout << "YES" << endl; 22 | } 23 | return 0; 24 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/58/NOPAL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int test; 6 | cin>>test; 7 | while(test--){ 8 | int num; 9 | cin>>num; 10 | string answer = ""; 11 | char alpha = 97; 12 | while(num--){ 13 | answer += alpha; 14 | alpha++; 15 | if(alpha==123)alpha=97; 16 | } 17 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t,i,x,n,k; 6 | cin>>t; 7 | while(t--) 8 | { 9 | cin>>n>>k>>x; 10 | if(k 2 | using namespace std; 3 | 4 | int main() { 5 | int x,y,total; 6 | cin>>x>>y; 7 | total=x-(y/2); 8 | cout< 2 | using namespace std; 3 | 4 | typedef long long int ll; 5 | 6 | int main() { 7 | // your code goes here 8 | ll T; 9 | cin>>T; 10 | while(T--) 11 | { 12 | ll n; 13 | cin>>n; 14 | vector a(n); 15 | for(ll i=0; i>a[i]; 17 | 18 | ll min_ans_ops=0; 19 | unordered_map mp; 20 | ll max_tom=0; 21 | for(auto x:a) 22 | { 23 | mp[x]++; 24 | } 25 | 26 | for(auto x:a) 27 | { 28 | if(mp[x]>max_tom) max_tom= mp[x]; 29 | } 30 | ll val = 1; 31 | while(val < max_tom) 32 | { 33 | ++min_ans_ops; 34 | val*=2; 35 | } 36 | 37 | cout< 2 | using namespace std; 3 | 4 | void solve() 5 | { 6 | long long n; 7 | cin>>n; 8 | long long arr[n]; 9 | for(int i=0; i>arr[i]; 11 | int e=0; 12 | for(int i=0;i> T; 25 | while(T--) 26 | { 27 | solve(); 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /codechefSolutions/straters/58/equivalentNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define int long long 4 | long long power(long long a,long long l){ 5 | long long ans=0; 6 | while((a%l)==0){ 7 | a=a/l; 8 | ans++; 9 | } 10 | return ans; 11 | } 12 | long long gcd(long long p1,long long p2){ 13 | int k=max(p1,p2); 14 | int h=min(p1,p2); 15 | if(k%h==0) return h; 16 | return gcd(h,k%h); 17 | } 18 | int32_t main() { 19 | ios_base::sync_with_stdio(false); 20 | cin.tie(NULL); 21 | cout.tie(NULL); 22 | int t; 23 | cin>>t; 24 | int r=1e6+1; 25 | vector v(r); 26 | for(int i=0;i>a>>b; 38 | int l=v[a],h=v[b]; 39 | if(l!=h){ 40 | cout<<"NO"< 2 | using namespace std; 3 | 4 | int main() { 5 | // your code goes here 6 | ios_base::sync_with_stdio(0);cin.tie(0); 7 | int t;cin>>t; 8 | while(t--){ 9 | int n;cin>>n; 10 | int x = 0,ok=1; 11 | int y=0,z=0; 12 | for(int i=1;i<=n;i++){ 13 | cin>>ok; 14 | if(i%2){ 15 | y^=(ok%2); 16 | } 17 | else { 18 | x^=((ok/2)); 19 | } 20 | } 21 | x = x^y; 22 | if(x){ 23 | cout<<"CHEF\n"; 24 | }else cout<<"CHEFINA\n"; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /codechefSolutions/straters/58/rankthepages.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin >> t; 7 | while (t--) 8 | { 9 | int n; 10 | cin >> n; 11 | cout << ceil(n / 25.0) << endl; 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /codechefSolutions/straters/58/reachthetarget.cpp: -------------------------------------------------------------------------------- 1 | 2 | // 1 Reach the target 3 | 4 | #include 5 | using namespace std; 6 | void iA(int arr[], int n) 7 | { 8 | for (int i = 0; i < n; i++) 9 | cin >> arr[i]; 10 | } 11 | int main() 12 | { 13 | int t; 14 | cin >> t; 15 | while (t--) 16 | { 17 | int x, y; 18 | cin >> x >> y; 19 | cout << x - y << endl; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codechefSolutions/straters/58/removebadelements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minop(vector v) 5 | { 6 | int n=v.size(); 7 | unordered_map mp; 8 | for(int i=0;i>t; 24 | for(int i=0;i>n; 28 | vectorv(n); 29 | for(int j=0;j>v[j]; 32 | } 33 | cout< 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int t; 9 | cin>>t;//No. of test cases 10 | int X; 11 | for(int i=0;i>X; 14 | if((X>=67)&&(X<=45000))//Audible frequency range 15 | { 16 | cout<<"YES"< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin >> t;//Number of test cases. 7 | vector v(3); 8 | int maxindex,maxval; 9 | while (t--) 10 | { 11 | for (int i = 0; i < 3; i++) 12 | { 13 | cin >> v[i];//Inputs X,Y,Z 14 | } 15 | maxval=v[0]; 16 | maxindex=0; 17 | for (int i = 1; i < 3; i++) 18 | { 19 | if (v[i] > maxval) 20 | { 21 | //Storing max-valued index b/w (X,Y,Z)=>(v[0],v[1],v[2]) 22 | maxindex=i; 23 | maxval=v[i]; 24 | } 25 | } 26 | if (maxindex == 0) 27 | { 28 | cout << "Setter" << endl; 29 | } 30 | else if (maxindex == 1) 31 | { 32 | cout << "Tester" << endl; 33 | } 34 | else 35 | { 36 | cout << "Editorialist" << endl; 37 | } 38 | } 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /count_num_of_subset_sum_k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int targetsum(int arr[],int n,int sum){ 5 | if(n==0 ){ 6 | return 0; 7 | } 8 | if(sum==0){ 9 | return 1; 10 | } 11 | 12 | if(arr[n-1]>sum){ 13 | return targetsum(arr,n-1,sum); 14 | } 15 | 16 | return targetsum(arr,n-1,sum) + targetsum(arr,n-1,sum-arr[n-1]); 17 | } 18 | 19 | int main (){ 20 | int arr[5]={2,3,5,10,11}; 21 | int sum=10; 22 | cout< 28 | using namespace std; 29 | long long N= 1e9+7; 30 | 31 | long long dp[1000][1000]; 32 | int targetsum(int arr[],int n,int sum){ 33 | 34 | if(n==0 & sum>0){ 35 | return 0; 36 | } 37 | if(sum==0){ 38 | return 1; 39 | } 40 | if(dp[n-1][sum]!=-1){ 41 | return dp[n-1][sum]; 42 | } 43 | 44 | if(arr[n-1]>sum){ 45 | return dp[n-1][sum]=targetsum(arr,n-1,sum); 46 | } 47 | 48 | return dp[n-1][sum]=targetsum(arr,n-1,sum) + targetsum(arr,n-1,sum-arr[n-1]); 49 | } 50 | 51 | int main (){ 52 | memset(dp,-1,sizeof(dp)); 53 | int arr[5]={10,10,10,5,5}; 54 | int sum=10; 55 | int n=5; 56 | cout<left && root->left->val==data){ 10 | if(root->right){ 11 | return root->right->val; 12 | } 13 | } 14 | if(root->right && root->right->val==data){ 15 | if(root->left){ 16 | return root->left->val; 17 | } 18 | } 19 | int x= find_sib(root->left,data); 20 | int y =find_sib(root->right,data); 21 | if(x){ 22 | return x; 23 | } 24 | else if(y){ 25 | return y; 26 | } 27 | else return -1; 28 | 29 | } 30 | vector Solution::solve(TreeNode* root, int data) { 31 | 32 | 33 | vectorv; 34 | if(root==NULL || root->val==data){ 35 | // v.push_back(NULL); 36 | return {}; 37 | } 38 | int sib=-1; 39 | 40 | int flag=1,f2=1; 41 | queueq; 42 | q.push(root); 43 | while(!q.empty()){ 44 | if(flag==0)break; 45 | int size=q.size(); 46 | for(int i=0;ival<<" "; 50 | 51 | q.pop(); 52 | if(front->left){ 53 | if(front->left->val==data) 54 | { 55 | flag=0; 56 | continue; 57 | } 58 | else 59 | q.push(front->left); 60 | } 61 | if(root->right){ 62 | if(front->right->val==data) 63 | { 64 | flag=0; 65 | if(root->left && f2==1){ 66 | sib = root->left->val; 67 | f2 =0; 68 | } 69 | continue; 70 | } 71 | else 72 | q.push(front->right); 73 | } 74 | } 75 | } 76 | cout<val<<" "; 79 | if(((q.front()->val)==sib )&& (sib!=-1)){ 80 | q.pop(); 81 | continue; 82 | } 83 | v.push_back(q.front()->val); 84 | q.pop(); 85 | } 86 | 87 | return v; 88 | 89 | } 90 | // 95 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 91 | // 32 92 | // 3 93 | -------------------------------------------------------------------------------- /dfs.cpp: -------------------------------------------------------------------------------- 1 | //tree n nodes h to n-1 edges hogi 2 | //tree are non cyclic graph 3 | //lca lowest comman ancestor are first comman parent of two nodes 4 | //in order to store tree we use adjacant matrix or adjacant list 5 | //In Adjacant matrix space complexity is more O(N^2) but it is easy to check node is connected or not 6 | //In Adjacant list space complexity is less O(V+E) but for connection check we iterate all via loop 7 | 8 | 9 | //full bt have either 0 or child 10 | //complete bt have all level filled except last or have left as possible 11 | //perfect bt have all leaf node at same level 12 | //balance bt have height log(no of nodes) 13 | // degenerate bt have single children of all nodes 14 | 15 | 16 | 17 | #include 18 | using namespace std; 19 | const int N=1e5+10; 20 | 21 | vector g[N]; 22 | bool vis[N]; 23 | 24 | void dfs(int vertex){ 25 | cout<>n>>m; 39 | for(int i=0;i>v1>>v2; 42 | g[v1].push_back(v2); 43 | g[v2].push_back(v1); 44 | 45 | } 46 | 47 | dfs(1); 48 | 49 | } 50 | 51 | /* 52 | //Count no of connected components 53 | 54 | #include 55 | using namespace std; 56 | const int N=1e5+10; 57 | 58 | vector g[N]; 59 | bool vis[N]; 60 | 61 | void dfs(int vertex){ 62 | vis[vertex] = true; 63 | for(int child : g[vertex]){ 64 | if(vis[child]) continue; 65 | dfs(child); 66 | } 67 | 68 | } 69 | 70 | int main(){ 71 | int n,m; 72 | int v1,v2; 73 | int cnt=0; 74 | cin>>n>>m; 75 | for(int i=0;i>v1>>v2; 78 | g[v1].push_back(v2); 79 | g[v2].push_back(v1); 80 | 81 | } 82 | for(int i=1;i<=n;i++){ 83 | if(vis[i]) continue; 84 | dfs(i); 85 | cnt++; 86 | } 87 | cout< 96 | using namespace std; 97 | const int N=1e5+10; 98 | 99 | vector g[N]; 100 | bool vis[N]; 101 | vector> cc; 102 | vector c; 103 | 104 | void dfs(int vertex){ 105 | vis[vertex] = true; 106 | c.push_back(vertex); 107 | for(int child : g[vertex]){ 108 | if(vis[child]) continue; 109 | dfs(child); 110 | } 111 | 112 | } 113 | 114 | int main(){ 115 | int n,m; 116 | int v1,v2; 117 | int cnt=0; 118 | cin>>n>>m; 119 | for(int i=0;i>v1>>v2; 122 | g[v1].push_back(v2); 123 | g[v2].push_back(v1); 124 | 125 | } 126 | for(int i=1;i<=n;i++){ 127 | if(vis[i]) continue; 128 | c.clear(); 129 | dfs(i); 130 | cc.push_back(c); 131 | 132 | } 133 | cout< 2 | using namespace std; 3 | int dp[1000][10000]; 4 | int minisum(int arr[],int n,int sum,int cal){ 5 | 6 | if(n==0){ 7 | return dp[n][cal]=abs((sum-cal)-cal); 8 | } 9 | if(dp[n][cal]!=-1){ 10 | return dp[n][cal]; 11 | } 12 | return dp[n][cal]=min(minisum(arr,n-1,sum,cal+arr[n-1]),minisum(arr,n-1,sum,cal)); 13 | 14 | } 15 | 16 | int main(){ 17 | memset(dp,-1,sizeof(dp)); 18 | int n; 19 | cin>>n; 20 | int arr[n]; 21 | for(int i=0;i>arr[i]; 23 | } 24 | 25 | int sum=0; 26 | for(int i=0;i 12 | 13 | using namespace std; 14 | 15 | int editDistance(string s, string t) { 16 | int n = s.size(); 17 | int m = t.size(); 18 | 19 | // Store minimum number of operations to equate strings at that time 20 | int dp[n+1][m+1]; 21 | for(int i=0;i<=n;i++) { 22 | for(int j=0;j<=m;j++) { 23 | // If one string is empty then minimum operations is delete other string 24 | if(i==0) dp[i][j] = j; 25 | else if(j==0) dp[i][j] = i; 26 | else { 27 | // We take minimum of delete from string, add to string, or replace in string 28 | // If characters are equal then we only check for addition or deletion 29 | if(s[i-1]==t[j-1]) dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])+1); 30 | else dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1; 31 | } 32 | } 33 | } 34 | return dp[n][m]; 35 | } 36 | 37 | int main() { 38 | string s,t; 39 | cin>>s>>t; 40 | cout< 2 | 3 | using namespace std; 4 | 5 | 6 | 7 | int dp[50]; 8 | int am_my11(int n){ 9 | if(dp[n]!=-1) 10 | return dp[n]; 11 | if(n<2) 12 | return n; 13 | else 14 | return dp[n]= am_my11(n-1)+am_my11(n-2); 15 | 16 | } 17 | int fib(int n) { 18 | memset(dp, -1, sizeof(dp)); 19 | int Ans = am_my11(n); 20 | return Ans; 21 | } 22 | int main() { 23 | 24 | 25 | int n; 26 | cin >> n; 27 | 28 | cout << fib(n) << endl; 29 | 30 | 31 | 32 | return 0; 33 | 34 | } 35 | 36 | -------------------------------------------------------------------------------- /firstAndLastposnofElementinSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstOcc(vector& nums, int target){ 4 | int s=0; 5 | int e=nums.size()-1; 6 | int mid=0; 7 | int p=-1; 8 | while(s<=e){ 9 | mid=s+(e-s)/2; 10 | if(nums[mid]==target){ 11 | p=mid; 12 | e=mid-1; 13 | } 14 | if(nums[mid]>target){ 15 | 16 | e=mid-1; 17 | } 18 | if(nums[mid]& nums, int target){ 27 | int s=0; 28 | int e=nums.size()-1; 29 | int mid=0; 30 | int p=-1; 31 | while(s<=e){ 32 | mid=s+(e-s)/2; 33 | if(nums[mid]==target){ 34 | p=mid; 35 | s=mid+1; 36 | } 37 | if(nums[mid]>target){ 38 | 39 | e=mid-1; 40 | } 41 | if(nums[mid] searchRange(vector& nums, int target) { 51 | vector ans; 52 | ans.push_back(firstOcc(nums,target)); 53 | ans.push_back(lastOcc(nums,target)); 54 | return ans; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /first_missing_positive.cpp: -------------------------------------------------------------------------------- 1 | // Given an unsorted integer array nums, return the smallest missing positive integer 2 | 3 | #include 4 | using namespace std; 5 | 6 | int firstMissingPositive(vector& nums){ 7 | int n=nums.size(); 8 | for(int i=0;i0 && nums[i]<=n && nums[nums[i]-1]!=nums[i]){ 10 | swap(nums[i], nums[nums[i]-1]); 11 | } 12 | } 13 | for(int i=0;i>n; 22 | vector nums(n); 23 | for(int i=0;i>nums[i]; 24 | cout<<"Smallest Missing Positive Integer is"< 3 | using namespace std; 4 | 5 | 6 | struct Node { 7 | int data; 8 | struct Node *left, *right; 9 | }; 10 | 11 | Node* newNode(int data) 12 | { 13 | Node* temp = new Node; 14 | temp->data = data; 15 | temp->left = temp->right = NULL; 16 | return temp; 17 | } 18 | 19 | 20 | void printInorder(struct Node* node) 21 | { 22 | if (node == NULL) 23 | return; 24 | 25 | printInorder(node->left); 26 | 27 | 28 | cout << node->data << " "; 29 | 30 | 31 | printInorder(node->right); 32 | } 33 | 34 | 35 | int main() 36 | { 37 | struct Node* root = newNode(1); 38 | root->left = newNode(2); 39 | root->right = newNode(3); 40 | root->left->left = newNode(4); 41 | root->left->right = newNode(5); 42 | 43 | 44 | // Function call 45 | cout << "\nInorder traversal of binary tree is \n"; 46 | printInorder(root); 47 | 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /kadanes_algo.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = INT_MIN, max_ending_here = 0; 8 | 9 | for (int i = 0; i < size; i++) { 10 | max_ending_here = max_ending_here + a[i]; 11 | if (max_so_far < max_ending_here) 12 | max_so_far = max_ending_here; 13 | 14 | if (max_ending_here < 0) 15 | max_ending_here = 0; 16 | } 17 | return max_so_far; 18 | } 19 | 20 | int main() 21 | { 22 | int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; 23 | int n = sizeof(a) / sizeof(a[0]); 24 | 25 | int max_sum = maxSubArraySum(a, n); 26 | cout << "Maximum contiguous sum is " << max_sum; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /kthRowOfPascal'sTriangle.cpp: -------------------------------------------------------------------------------- 1 | source: InterviewBit 2 | PS: 3 | Problem Description 4 | 5 | Given an index k, return the kth row of the Pascal's triangle. 6 | Pascal's triangle: To generate A[C] in row R, sum up A'[C] and A'[C-1] from previous row R - 1. 7 | 8 | Example: 9 | 10 | Input : k = 3 11 | 12 | 13 | Return : [1,3,3,1] 14 | 15 | My Soln: 16 | 17 | vector Solution::getRow(int k) { 18 | vectorv;int c; 19 | if(k==0){ 20 | v.push_back(1); 21 | return v; 22 | } 23 | for (int i = k; i <= k; i++) { 24 | for (int j = 0; j <= i; j++) { 25 | if (j == 0 || i == 0) 26 | c = 1; 27 | else 28 | c= c * (i - j + 1) / j; 29 | v.push_back(c); 30 | } 31 | } 32 | return v; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /largest.cpp: -------------------------------------------------------------------------------- 1 | PS: Given a list of non negative integers, arrange them such that they form the largest number. 2 | soln: 3 | bool compare(int v1, int v2){ 4 | string s1 = to_string(v1); 5 | string s2 = to_string(v2); 6 | return s1+s2>s2+s1; 7 | } 8 | string Solution::largestNumber(const vector &ar) { 9 | string s=""; 10 | vectorarr(ar); 11 | sort(arr.begin(),arr.end(),compare); 12 | for(int i=0;i 2 | using namespace std; 3 | 4 | void linear_search(int arr[], int num, int size){ 5 | int pos, fl = 0; 6 | for (int i = 0; i < size; i++) 7 | { 8 | if(arr[i] == num){ 9 | cout << i+1 << endl; 10 | fl = 1; 11 | } 12 | } 13 | if(fl == 0) 14 | cout << "Element not found" << endl; 15 | } 16 | 17 | int main() 18 | { 19 | int a; 20 | cin >> a; 21 | int arr[a]; 22 | for (int i = 0; i < a; i++) 23 | cin >> arr[i]; 24 | linear_search(arr, 2, a); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /longest_common_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int lcs(string &x, string &y,int n, int m){ 5 | int dp[n+1][m+1]; 6 | 7 | for(int i=0;i>x; 26 | cin>>y; 27 | int n=x.length(); 28 | int m=y.length(); 29 | 30 | cout<& nums,vector& multi,vector> &dp){ 4 | if(idx==multi.size()) return 0; 5 | if(dp[idx][st]!=INT_MIN) return dp[idx][st]; 6 | int ans=INT_MIN; 7 | ans= max(multi[idx]*nums[st] + rec(idx+1,st+1,end,nums,multi,dp), 8 | multi[idx]*nums[end] + rec(idx+1,st,end-1,nums,multi,dp)); 9 | return dp[idx][st]= ans; 10 | } 11 | int maximumScore(vector& nums, vector& multi) { 12 | vector> dp(multi.size(),vector(multi.size(),INT_MIN)); 13 | return rec(0,0,nums.size()-1,nums,multi,dp); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /mergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Merges two subarrays of array[]. 5 | // First subarray is arr[begin..mid] 6 | // Second subarray is arr[mid+1..end] 7 | void merge(int array[], int const left, int const mid, 8 | int const right) 9 | { 10 | auto const subArrayOne = mid - left + 1; 11 | auto const subArrayTwo = right - mid; 12 | 13 | // Create temp arrays 14 | auto *leftArray = new int[subArrayOne], 15 | *rightArray = new int[subArrayTwo]; 16 | 17 | // Copy data to temp arrays leftArray[] and rightArray[] 18 | for (auto i = 0; i < subArrayOne; i++) 19 | leftArray[i] = array[left + i]; 20 | for (auto j = 0; j < subArrayTwo; j++) 21 | rightArray[j] = array[mid + 1 + j]; 22 | 23 | auto indexOfSubArrayOne 24 | = 0, // Initial index of first sub-array 25 | indexOfSubArrayTwo 26 | = 0; // Initial index of second sub-array 27 | int indexOfMergedArray 28 | = left; // Initial index of merged array 29 | 30 | // Merge the temp arrays back into array[left..right] 31 | while (indexOfSubArrayOne < subArrayOne 32 | && indexOfSubArrayTwo < subArrayTwo) { 33 | if (leftArray[indexOfSubArrayOne] 34 | <= rightArray[indexOfSubArrayTwo]) { 35 | array[indexOfMergedArray] 36 | = leftArray[indexOfSubArrayOne]; 37 | indexOfSubArrayOne++; 38 | } 39 | else { 40 | array[indexOfMergedArray] 41 | = rightArray[indexOfSubArrayTwo]; 42 | indexOfSubArrayTwo++; 43 | } 44 | indexOfMergedArray++; 45 | } 46 | // Copy the remaining elements of 47 | // left[], if there are any 48 | while (indexOfSubArrayOne < subArrayOne) { 49 | array[indexOfMergedArray] 50 | = leftArray[indexOfSubArrayOne]; 51 | indexOfSubArrayOne++; 52 | indexOfMergedArray++; 53 | } 54 | // Copy the remaining elements of 55 | // right[], if there are any 56 | while (indexOfSubArrayTwo < subArrayTwo) { 57 | array[indexOfMergedArray] 58 | = rightArray[indexOfSubArrayTwo]; 59 | indexOfSubArrayTwo++; 60 | indexOfMergedArray++; 61 | } 62 | delete[] leftArray; 63 | delete[] rightArray; 64 | } 65 | 66 | // begin is for left index and end is 67 | // right index of the sub-array 68 | // of arr to be sorted */ 69 | void mergeSort(int array[], int const begin, int const end) 70 | { 71 | if (begin >= end) 72 | return; // Returns recursively 73 | 74 | auto mid = begin + (end - begin) / 2; 75 | mergeSort(array, begin, mid); 76 | mergeSort(array, mid + 1, end); 77 | merge(array, begin, mid, end); 78 | } 79 | 80 | // UTILITY FUNCTIONS 81 | // Function to print an array 82 | void printArray(int A[], int size) 83 | { 84 | for (auto i = 0; i < size; i++) 85 | cout << A[i] << " "; 86 | } 87 | 88 | // Driver code 89 | int main() 90 | { 91 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 92 | auto arr_size = sizeof(arr) / sizeof(arr[0]); 93 | 94 | cout << "Given array is \n"; 95 | printArray(arr, arr_size); 96 | 97 | mergeSort(arr, 0, arr_size - 1); 98 | 99 | cout << "\nSorted array is \n"; 100 | printArray(arr, arr_size); 101 | return 0; 102 | } 103 | 104 | // This code is contributed by Mayank Tyagi 105 | // This code was revised by Joshua Estes 106 | -------------------------------------------------------------------------------- /minStep.cpp: -------------------------------------------------------------------------------- 1 | source: INTERVIEW BIT 2 | problem statement: 3 | Problem Description 4 | 5 | You are in an infinite 2D grid where you can move in any of the 8 directions 6 | 7 | (x,y) to 8 | (x-1, y-1), 9 | (x-1, y) , 10 | (x-1, y+1), 11 | (x , y-1), 12 | (x , y+1), 13 | (x+1, y-1), 14 | (x+1, y) , 15 | (x+1, y+1) 16 | 17 | 18 | You are given a sequence of points and the order in which you need to cover the points.. Give the minimum number of steps in which you can achieve it. You start from the first point. 19 | 20 | 21 | solution: 22 | 23 | int Solution::coverPoints(vector &a, vector &b) { 24 | int diff1=0,diff2=0,ans=0; 25 | for(int i=1;i 2 | using namespace std; 3 | int static dp[1000][1000]; 4 | 5 | int lcs(string &x, string &y,int n, int m){ 6 | if(n==0 || m==0){return 0;} 7 | if(dp[n][m]!=-1){ 8 | return dp[n][m]; 9 | } 10 | if(x[n-1]==y[m-1]){ 11 | return dp[n][m]= 1+lcs(x,y,n-1,m-1); 12 | } 13 | else 14 | return dp[n][m]=max(lcs(x,y,n-1,m),lcs(x,y,n,m-1)); 15 | 16 | } 17 | 18 | int main(){ 19 | memset(dp,-1,sizeof(dp)); 20 | string x,y; 21 | cin>>x; 22 | cin>>y; 23 | int n=x.length(); 24 | int m=y.length(); 25 | 26 | //only change at cout ,for ex x=heap y=pea lcs is ea convert a->b via lcs 27 | 28 | cout< 0) { 12 | if (num % 1000 != 0) 13 | words = helper(num % 1000) +THOUSANDS[i] + " " + words; 14 | num /= 1000; 15 | i++; 16 | } 17 | 18 | return words.trim(); 19 | } 20 | 21 | private String helper(int num) { 22 | if (num == 0) 23 | return ""; 24 | else if (num < 20) 25 | return LESS_THAN_20[num] + " "; 26 | else if (num < 100) 27 | return TENS[num / 10] + " " + helper(num % 10); 28 | else 29 | return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); 30 | } 31 | -------------------------------------------------------------------------------- /palindrome/palindrome.cpp: -------------------------------------------------------------------------------- 1 | Determine whether an integer is a palindrome. Do this without extra space. 2 | 3 | int Solution::isPalindrome(int A) { 4 | if(A<0){ 5 | return false; 6 | } 7 | int n=10; 8 | int num = A; 9 | int len=0; 10 | while(num>0){ 11 | num = num/10; 12 | len++; 13 | } 14 | string s= to_string(A); 15 | 16 | // cout<stk; 10 | stk.push('x'); 11 | int i=0; 12 | if(str[0]==')'){ 13 | return 0; 14 | } 15 | if(str[str.size()-1]=='('){ 16 | return 0; 17 | } 18 | while(i Solution::primesum(int a) { 25 | int num=a; 26 | bool isPrime[a+1];//marking all numbers as prime 27 | for(int i=1;i<=num;i++){ 28 | isPrime[i]=true; 29 | } 30 | isPrime[0]=false; 31 | isPrime[1]=false; 32 | isPrime[2]=true; 33 | calculatePrime(isPrime,a); 34 | int x = a-2; 35 | for(int i=2;iv; 39 | v.push_back(i); 40 | v.push_back(a-i); 41 | return v; 42 | } 43 | } 44 | } 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /prime_find_using_sieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | long long n; 6 | cin>>n; 7 | int count=0; 8 | vector prime(n,1); 9 | 10 | for(int i=2;i<=n;i++){ 11 | if(prime[i]==1){ 12 | for(int j=i*i;j<=n;j+=i){ 13 | prime[j]=0; 14 | } 15 | } 16 | } 17 | 18 | for(int i=2;i<=n;i++){ 19 | if(prime[i]==1){ 20 | cout< 2) 28 | cout << n << " "; 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int n = 315; 35 | primeFactors(n); 36 | return 0; 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /remove_duplicate_letters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Problem 316. Remove Duplicate Letters 3 | Given a string s, remove duplicate letters so that every letter appears once and only once. 4 | You must make sure your result is the smallest in lexicographical order among all possible results. 5 | */ 6 | 7 | class Solution { 8 | public: 9 | string removeDuplicateLetters(string s) { 10 | //cnt for storing frequency of characters 11 | //vis for marking visited characters 12 | vector cnt(26,0), vis(26,0); 13 | string ans = ""; 14 | int n = s.size(); 15 | 16 | for(int i=0; i s[i] and its count > 0 27 | while(ans.size() > 0 && ans.back() > s[i] && cnt[ans.back()-'a'] > 0) 28 | { 29 | //marking letter visited 30 | vis[ans.back()-'a'] = 0; 31 | ans.pop_back(); 32 | } 33 | //add s[i] in ans and mark it visited 34 | ans += s[i]; 35 | vis[s[i]-'a'] = 1; 36 | } 37 | } 38 | 39 | return ans; 40 | } 41 | }; -------------------------------------------------------------------------------- /reverse_linked_list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* curr=head; 15 | ListNode* prev=NULL; 16 | if(head==NULL) 17 | return NULL; 18 | while(curr->next!=NULL) 19 | { 20 | ListNode* curr1=curr->next; 21 | curr->next=prev; 22 | prev=curr; 23 | curr=curr1; 24 | } 25 | head=curr; 26 | curr->next=prev; 27 | return head; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /reverse_string_using_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Stack { 5 | public: 6 | int top; 7 | unsigned capacity; 8 | char* array; 9 | }; 10 | 11 | Stack* createStack(unsigned capacity) 12 | { 13 | Stack* stack = new Stack(); 14 | stack->capacity = capacity; 15 | stack->top = -1; 16 | stack->array 17 | = new char[(stack->capacity * sizeof(char))]; 18 | return stack; 19 | } 20 | 21 | int isFull(Stack* stack) 22 | { 23 | return stack->top == stack->capacity - 1; 24 | } 25 | 26 | int isEmpty(Stack* stack) { return stack->top == -1; } 27 | 28 | void push(Stack* stack, char item) 29 | { 30 | if (isFull(stack)) 31 | return; 32 | stack->array[++stack->top] = item; 33 | } 34 | 35 | char pop(Stack* stack) 36 | { 37 | if (isEmpty(stack)) 38 | return -1; 39 | return stack->array[stack->top--]; 40 | } 41 | 42 | void reverse(char str[]) 43 | { 44 | int n = strlen(str); 45 | Stack* stack = createStack(n); 46 | 47 | int i; 48 | for (i = 0; i < n; i++) 49 | push(stack, str[i]); 50 | 51 | for (i = 0; i < n; i++) 52 | str[i] = pop(stack); 53 | } 54 | 55 | int main() 56 | { 57 | char str[] = "GeeksQuiz"; 58 | 59 | reverse(str); 60 | cout << "Reversed string is " << str; 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /robinround.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | void findWaitingTime(int processes[], int n, 7 | int bt[], int wt[], int quantum) 8 | { 9 | 10 | int rem_bt[n]; 11 | for (int i = 0 ; i < n ; i++) 12 | rem_bt[i] = bt[i]; 13 | 14 | int t = 0; // Current time 15 | 16 | 17 | while (1) 18 | { 19 | bool done = true; 20 | 21 | for (int i = 0 ; i < n; i++) 22 | { 23 | 24 | if (rem_bt[i] > 0) 25 | { 26 | done = false; // There is a pending process 27 | 28 | if (rem_bt[i] > quantum) 29 | { 30 | 31 | t += quantum; 32 | 33 | 34 | rem_bt[i] -= quantum; 35 | } 36 | 37 | 38 | else 39 | { 40 | 41 | t = t + rem_bt[i]; 42 | 43 | 44 | wt[i] = t - bt[i]; 45 | 46 | 47 | rem_bt[i] = 0; 48 | } 49 | } 50 | } 51 | 52 | 53 | if (done == true) 54 | break; 55 | } 56 | } 57 | 58 | 59 | void findTurnAroundTime(int processes[], int n, 60 | int bt[], int wt[], int tat[]) 61 | { 62 | 63 | for (int i = 0; i < n ; i++) 64 | tat[i] = bt[i] + wt[i]; 65 | } 66 | 67 | void findavgTime(int processes[], int n, int bt[], 68 | int quantum) 69 | { 70 | int wt[n], tat[n], total_wt = 0, total_tat = 0; 71 | 72 | 73 | findWaitingTime(processes, n, bt, wt, quantum); 74 | 75 | findTurnAroundTime(processes, n, bt, wt, tat); 76 | 77 | 78 | cout << "PN\t "<< " \tBT " 79 | << " WT " << " \tTAT\n"; 80 | 81 | for (int i=0; i>n; 37 | 38 | cout << "Following are the prime numbers smaller " 39 | << " than or equal to " << n << endl; 40 | SieveOfEratosthenes(n); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /shortest-unsorted-continuous-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findUnsortedSubarray(vector& nums) { 4 | 5 | int n = nums.size(); 6 | 7 | if(n <= 1) { 8 | return 0; 9 | } 10 | 11 | int maxPrefixArray[n]; 12 | int minSuffixArray[n]; 13 | 14 | maxPrefixArray[0] = nums[0]; 15 | 16 | for(int i = 1; i < n; i++) { 17 | maxPrefixArray[i] = max(maxPrefixArray[i - 1], nums[i]); 18 | } 19 | 20 | minSuffixArray[n - 1] = nums[n - 1]; 21 | 22 | for(int i = n - 2; i >= 0; i--) { 23 | minSuffixArray[i] = min(minSuffixArray[i + 1], nums[i]); 24 | } 25 | 26 | int l = -1, h = -1; 27 | 28 | for(int i = 0; i < n; i++) { 29 | if(i == 0 && nums[i] > minSuffixArray[i + 1]) { 30 | l = i; 31 | break; 32 | } 33 | 34 | if(i == n - 1 && nums[i] < maxPrefixArray[i - 1]) { 35 | l = i; 36 | break; 37 | } 38 | 39 | if((i != 0 && i != n - 1) && (nums[i] > minSuffixArray[i + 1] || nums[i] < maxPrefixArray[i - 1])) { 40 | l = i; 41 | break; 42 | } 43 | } 44 | 45 | for(int i = n - 1; i >= 0; i--) { 46 | if(i == n - 1 && nums[i] < maxPrefixArray[i - 1]) { 47 | h = i; 48 | break; 49 | } 50 | 51 | if(i == 0 && nums[i] > minSuffixArray[i + 1]) { 52 | h = i; 53 | break; 54 | } 55 | 56 | if((i != 0 && i != n - 1) && (nums[i] > minSuffixArray[i + 1] || nums[i] < maxPrefixArray[i - 1])) { 57 | h = i; 58 | break; 59 | } 60 | } 61 | 62 | 63 | if(l == -1 && h == -1) { 64 | return 0; 65 | } 66 | 67 | return h - l + 1; 68 | 69 | 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /shortest_comman_supersequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int static dp[1000][1000]; 4 | 5 | int lcs(string &x, string &y,int n, int m){ 6 | if(n==0 || m==0){return 0;} 7 | if(dp[n][m]!=-1){ 8 | return dp[n][m]; 9 | } 10 | if(x[n-1]==y[m-1]){ 11 | return dp[n][m]= 1+lcs(x,y,n-1,m-1); 12 | } 13 | else 14 | return dp[n][m]=max(lcs(x,y,n-1,m),lcs(x,y,n,m-1)); 15 | 16 | } 17 | 18 | int main(){ 19 | memset(dp,-1,sizeof(dp)); 20 | string x,y; 21 | cin>>x; 22 | cin>>y; 23 | int n=x.length(); 24 | int m=y.length(); 25 | 26 | //just change lcs length code to n+m-lcs() remaining code remains same 27 | cout< 2 | using namespace std; 3 | 4 | void SieveOfEratosthenes(int n) 5 | { 6 | bool prime[n + 1]; 7 | memset(prime, true, sizeof(prime)); 8 | 9 | for (int p = 2; p * p <= n; p++) { 10 | if (prime[p] == true) { 11 | for (int i = p * p; i <= n; i += p) 12 | prime[i] = false; 13 | } 14 | } 15 | for (int p = 2; p <= n; p++) 16 | if (prime[p]) 17 | cout << p << " "; 18 | } 19 | int main() 20 | { 21 | int n = 30; 22 | cout << "Following are the prime numbers smaller " 23 | << " than or equal to " << n << endl; 24 | SieveOfEratosthenes(n); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /single_number.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers nums, every element appears twice except for one. Find that single one 2 | 3 | #include 4 | using namespace std; 5 | 6 | int singleNumber(vector& nums) { 7 | int x=0; 8 | for(auto i:nums) x=(x^i); 9 | return x; 10 | } 11 | 12 | int main(){ 13 | int n; 14 | cin>>n; 15 | vector nums(n); 16 | for(int i=0;i>nums[i]; 17 | cout<<"Single occuring element is - "< 4 | using namespace std; 5 | #include 6 | string minWindow(string A, string B) { 7 | //start window size from first matching character 8 | unordered_mapm; 9 | int count = B.size(); 10 | int n = A.size(); 11 | string ans = ""; 12 | string tempans = ""; 13 | for(int i=0;i0){ 56 | count--; 57 | } 58 | m[A[j]]--; 59 | } 60 | j++; 61 | } 62 | 63 | return ans; 64 | } 65 | 66 | int main(){ 67 | 68 | string s1 = "xiEjBOGeHIMIlslpQIZ6jERaAVoHUc9Hrjlv7pQpUSY8oHqXoQYWWll8Pumov89wXDe0Qx6bEjsNJQAQ0A6K21Z0BrmM96FWEdRG69M9CYtdBOrDjzVGPf83UdP3kc4gK0uHVKcPN4HPdccm9Qd2VfmmOwYCYeva6BSG6NGqTt1aQw9BbkNsgAjvYzkVJPOYCnz7U4hBeGpcJkrnlTgNIGnluj6L6zPqKo5Ui75tC0jMojhEAlyFqDs7WMCG3dmSyVoan5tXI5uq1IxhAYZvRQVHtuHae0xxwCbRh6S7fCLKfXeSFITfKHnLdT65K36vGC7qOEyyT0Sm3Gwl2iXYSN2ELIoITfGW888GXaUNebAr3fnkuR6VwjcsPTldQSiohMkkps0MH1cBedtaKNoFm5HbH15kKok6aYEVsb6wOH2w096OwEyvtDBTQwoLN87JriLwgCBBavbOAiLwkGGySk8nO8dLHuUhk9q7f0rIjXCsQeAZ1dfFHvVLupPYekXzxtWHd84dARvv4Z5L1Z6j8ur2IXWWbum8lCi7aErEcq41WTo8dRlRykyLRSQxVH70rUTz81oJS3OuZwpI1ifBAmNXoTfznG2MXkLtFu4SMYC0bPHNctW7g5kZRwjSBKnGihTY6BQYItRwLUINApd1qZ8W4yVG9tnjx4WyKcDhK7Ieih7yNl68Qb4nXoQl079Vza3SZoKeWphKef1PedfQ6Hw2rv3DpfmtSkulxpSkd9ee8uTyTvyFlh9G1Xh8tNF8viKgsiuCZgLKva32fNfkvW7TJC654Wmz7tPMIske3RXgBdpPJd5BPpMpPGymdfIw53hnYBNg8NdWAImY3otYHjbl1rqiNQSHVPMbDDvDpwy01sKpEkcZ7R4SLCazPClvrx5oDyYolubdYKcvqtlcyks3UWm2z7kh4SHeiCPKerh83bX0m5xevbTqM2cXC9WxJLrS8q7XF1nh"; 69 | string s2 = "dO4BRDaT1wd0YBhH88Afu7CI4fwAyXM8pGoGNsO1n8MFMRB7qugS9EPhCauVzj7h"; 70 | cout< 2 | using namespace std; 3 | void countSort(vector &arr) 4 | { 5 | int max = *max_element(arr.begin(), arr.end()); 6 | int min = *min_element(arr.begin(), arr.end()); 7 | int range = max - min + 1; 8 | 9 | vector count(range), output(arr.size()); 10 | for (int i = 0; i < arr.size(); i++) 11 | count[arr[i] - min]++; 12 | 13 | for (int i = 1; i < count.size(); i++) 14 | count[i] += count[i - 1]; 15 | 16 | for (int i = arr.size() - 1; i >= 0; i--) 17 | { 18 | output[count[arr[i] - min] - 1] = arr[i]; 19 | count[arr[i] - min]--; 20 | } 21 | 22 | for (int i = 0; i < arr.size(); i++) 23 | arr[i] = output[i]; 24 | } 25 | 26 | void printArray(vector &arr) 27 | { 28 | for (int i = 0; i < arr.size(); i++) 29 | cout << arr[i] << " "; 30 | cout << "\n"; 31 | } 32 | 33 | int main() 34 | { 35 | vector arr = { -5, -10, 0, -3, 8, 5, -1, 10 }; 36 | countSort(arr); 37 | printArray(arr); 38 | return 0; 39 | } -------------------------------------------------------------------------------- /sorting technique/counting_sort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kritsid/competetive-programming/8920a76d8d08edf538f9db5289ed11ae74fa080d/sorting technique/counting_sort.exe -------------------------------------------------------------------------------- /sorting technique/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort an array using 7 | // insertion sort 8 | void insertionSort(int arr[], int n) 9 | { 10 | int i, key, j; 11 | for (i = 1; i < n; i++) 12 | { 13 | key = arr[i]; 14 | j = i - 1; 15 | 16 | // Move elements of arr[0..i-1], 17 | // that are greater than key, to one 18 | // position ahead of their 19 | // current position 20 | while (j >= 0 && arr[j] > key) 21 | { 22 | arr[j + 1] = arr[j]; 23 | j = j - 1; 24 | } 25 | arr[j + 1] = key; 26 | } 27 | } 28 | 29 | // A utility function to print an array 30 | // of size n 31 | void printArray(int arr[], int n) 32 | { 33 | int i; 34 | for (i = 0; i < n; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | int arr[] = { 12, 11, 13, 5, 6 }; 43 | int N = sizeof(arr) / sizeof(arr[0]); 44 | 45 | insertionSort(arr, N); 46 | printArray(arr, N); 47 | 48 | return 0; 49 | } 50 | //output 51 | /* 52 | 5 6 11 12 13 53 | */ -------------------------------------------------------------------------------- /sorting technique/insertionsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void insertionSort(int arr[], int n) 4 | { 5 | int i, key, j; 6 | for (i = 1; i < n; i++) 7 | { 8 | key = arr[i]; 9 | j = i - 1; 10 | while (j >= 0 && arr[j] > key) 11 | { 12 | arr[j + 1] = arr[j]; 13 | j = j - 1; 14 | } 15 | arr[j + 1] = key; 16 | } 17 | } 18 | void printArray(int arr[], int n) 19 | { 20 | int i; 21 | for (i = 0; i < n; i++) 22 | cout << arr[i] << " "; 23 | cout << endl; 24 | } 25 | int main() 26 | { 27 | int arr[] = { 12, 11, 13, 5, 6 }; 28 | int N = sizeof(arr) / sizeof(arr[0]); 29 | 30 | insertionSort(arr, N); 31 | printArray(arr, N); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /squares_diff_ascending.cpp: -------------------------------------------------------------------------------- 1 | // This program will give the nth minimum no which can obtained 2 | // by the differnce of squares of two numbers. 3 | 4 | // Example- for n=1 the first min will be 2^2-1^2 = 3 5 | // for n=2 the second min will be 3^2-2^2 = 5 6 | // for n=3 the third min will be 4^2-3^2 = 7 7 | // for n=4 the forth min will be 3^2-1^2 = 8 8 | // for n=5 the fifth min will be 5^2-4^2 = 9 9 | 10 | 11 | #include 12 | using namespace std; 13 | int main(){ 14 | int n; 15 | cin>>n; 16 | if(n==1){ 17 | cout<<3; 18 | }else{ 19 | n--; 20 | if(n%3==0){ 21 | cout<<((n/3)+1)*4; 22 | }else if(n%3==2){ 23 | cout<<(((n+2)/3)+1)*4 -1; 24 | 25 | }else if(n%3==1){ 26 | cout<<(((n+2)/3)+1)*4 -3; 27 | 28 | } 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /stack.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | using namespace std; 4 | #define N 10 5 | class StackArray 6 | { 7 | private: 8 | //Declaring an array with top pointer to point on the top of stack 9 | int A[N], top; 10 | public: 11 | //Initializing the top with in constructor 12 | StackArray() { 13 | top = 0; 14 | } 15 | //creating a check method to check if stack is full or not 16 | bool isFull() { 17 | if (top == N) 18 | return true; 19 | return false; 20 | } 21 | //creating the check method to check if stack is empty or not 22 | bool isEmpty() { 23 | if (top == 0) 24 | return true; 25 | return false; 26 | } 27 | //method to push in the stack 28 | bool push(int y) { 29 | if (isFull()) 30 | return false; 31 | A[top] = y; 32 | top++; 33 | return true; 34 | 35 | } 36 | //method to pop from the stack 37 | int pop() { 38 | if (!isEmpty()) { 39 | top--; 40 | int x = A[top]; 41 | return true; 42 | } 43 | return false; 44 | } 45 | //Method to print the whole stack 46 | bool print() { 47 | if (isEmpty()) 48 | return false; 49 | for (int i = 0; i < top; i++) 50 | cout << A[i] << " ,"; 51 | return true; 52 | } 53 | }; 54 | 55 | 56 | -------------------------------------------------------------------------------- /subarraySum.cpp: -------------------------------------------------------------------------------- 1 | //Given an array of n integers, your task is to count the number of subarrays having sum x. 2 | #include 3 | #define ll long long 4 | #define pb push_back 5 | #define fr(a,b) for(int i = a; i < b; i++) 6 | #define rep(i,a,b) for(int i = a; i < b; i++) 7 | #define mod 1000000007 8 | #define inf (1LL<<60) 9 | #define all(x) (x).begin(), (x).end() 10 | #define prDouble(x) cout << fixed << setprecision(10) << x 11 | #define triplet pair> 12 | #define goog(tno) cout << "Case #" << tno <<": " 13 | #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) 14 | #define read(x) int x; cin >> x 15 | using namespace std; 16 | 17 | 18 | void Am_my11(){ 19 | fast_io; 20 | } 21 | const int N = 1000009; 22 | 23 | 24 | int main() { 25 | Am_my11(); 26 | 27 | ll n, x; 28 | cin >> n >> x; 29 | ll A[n]; 30 | ll ans = 0; 31 | 32 | 33 | fr(0,n){ 34 | if(i==0){ 35 | cin >> A[i]; 36 | } 37 | else{ 38 | ll t; 39 | cin >> t; 40 | A[i]=A[i-1]+t; 41 | } 42 | } 43 | mapmp; 44 | mp[0]=1; 45 | fr(0,n){ 46 | ans+=mp[A[i]-x]; 47 | mp[A[i]]++; 48 | } 49 | 50 | cout << ans << endl; 51 | 52 | return 0; 53 | 54 | } -------------------------------------------------------------------------------- /subset sum k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool targetsum(int arr[],int n,int sum){ 5 | int dp[n+1][sum+1]; 6 | for(int i=0;i<=n;i++){ 7 | for(int j=0;j<=sum;j++){ 8 | if(i==0 && j>0){ 9 | dp[i][j]=0; 10 | } 11 | else if(j==0){ 12 | dp[i][j]=1; 13 | } 14 | 15 | else if(arr[i-1]>j){ 16 | dp[i][j]=dp[i-1][j]; 17 | } 18 | else 19 | dp[i][j]= dp[i-1][j] || dp[i-1][j-arr[i-1]]; 20 | } 21 | } 22 | 23 | return dp[n][sum]; 24 | 25 | 26 | } 27 | 28 | int main (){ 29 | int arr[5]={5,2,5,1,4}; 30 | int sum=14; 31 | if(targetsum(arr,5,sum)){ 32 | cout<<"true"; 33 | }else 34 | cout<<"false"; 35 | 36 | } -------------------------------------------------------------------------------- /subset_sum_prblm.cpp: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming solution for subset sum problem 2 | #include 3 | 4 | // Returns true if there is a subset of set[] with sun equal to given sum 5 | bool isSubsetSum(int set[], int n, int sum) 6 | { 7 | // The value of subset[i][j] will be true if there is a 8 | // subset of set[0..j-1] with sum equal to i 9 | bool subset[n + 1][sum + 1]; 10 | 11 | // If sum is 0, then answer is true 12 | for (int i = 0; i <= n; i++) 13 | subset[i][0] = true; 14 | 15 | // If sum is not 0 and set is empty, then answer is false 16 | for (int i = 1; i <= sum; i++) 17 | subset[0][i] = false; 18 | 19 | // Fill the subset table in bottom up manner 20 | for (int i = 1; i <= n; i++) { 21 | for (int j = 1; j <= sum; j++) { 22 | if (j < set[i - 1]) 23 | subset[i][j] = subset[i - 1][j]; 24 | if (j >= set[i - 1]) 25 | subset[i][j] = subset[i - 1][j] || 26 | subset[i - 1][j - set[i - 1]]; 27 | } 28 | } 29 | 30 | 31 | for (int i = 0; i <= n; i++) 32 | { 33 | for (int j = 0; j <= sum; j++) 34 | printf ("%4d", subset[i][j]); 35 | printf("\n"); 36 | } 37 | 38 | return subset[n][sum]; 39 | } 40 | 41 | // Driver program to test above function 42 | int main() 43 | { 44 | int set[] = { 3, 34, 4, 12, 5, 2 }; 45 | int sum = 9; 46 | int n = sizeof(set) / sizeof(set[0]); 47 | if (isSubsetSum(set, n, sum) == true) 48 | printf("Found a subset with given sum"); 49 | else 50 | printf("No subset with given sum"); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /sudoku solver: -------------------------------------------------------------------------------- 1 | public void solveSudoku(char[][] board) { 2 | solve(board); 3 | } 4 | boolean solve (char[][] board) 5 | { 6 | for(int i=0;i<9;i++) 7 | { 8 | for(int j=0;j<9;j++) 9 | { 10 | if(board[i][j]=='.') 11 | { 12 | for(char c='1';c<='9';c++) 13 | { 14 | if(isvalid(board,i,j,c)==true) 15 | { 16 | board[i][j]=c; 17 | if(solve(board)==true) 18 | return true; 19 | else 20 | board[i][j]='.'; 21 | 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | } 28 | } 29 | return true; 30 | } 31 | boolean isvalid(char[][] board,int row,int col,char c) 32 | { 33 | for(int i=0;i<9;i++) 34 | { 35 | 36 | if(board[i][col]==c) 37 | return false; 38 | else if(board[row][i]==c) 39 | return false; 40 | else if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c) 41 | return false; 42 | } 43 | return true; 44 | } 45 | -------------------------------------------------------------------------------- /sum of all sub-arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin>>n; 9 | int arr[n]; 10 | for(int i=0;i>arr[i]; 13 | } 14 | for(int i=0;i