diff --git a/05- May/19- Is Graph Bipartite?/.gitkeep b/05- May/19- Is Graph Bipartite?/.gitkeep deleted file mode 100644 index 8b1378917..000000000 --- a/05- May/19- Is Graph Bipartite?/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Ahmed Hossam).cpp b/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Ahmed Hossam).cpp deleted file mode 100644 index fc8828682..000000000 --- a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Ahmed Hossam).cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Author: Ahmed Hossam - -class Solution { -public: - - vector < int > colour; - - // Function to check if a graph is bipartite - bool is_Bipartite(int u, vector < vector < int > >& adj) { - // Iterate over the adjacent vertices of u - for (auto v : adj[u]) { - // If v has the same color as u, the graph is not bipartite - if (colour[v] == colour[u]) - return false; - // If v is uncolored, assign a different color to it - else if (colour[v] == 0) { - colour[v] = -colour[u]; - // Recursively check if the subgraph starting from v is bipartite - if (!is_Bipartite(v, adj)) - return false; - } - } - // All adjacent vertices have been processed and no conflict was found - return true; - } - - bool isBipartite(vector < vector < int > >& graph) { - int n = graph.size(); - colour = vector < int > (n); - - bool isBip = true; - // Process each vertex in the graph - for (int u = 0; u < n; u++) { - // If the vertex is uncolored, assign color 1 to it - if (!colour[u]) { - colour[u] = 1; - // Check if the subgraph starting from u is bipartite - isBip &= is_Bipartite(u, graph); - } - } - - // Return whether the graph is bipartite or not - return isBip; - } - -}; diff --git a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Lama Salah).cpp b/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Lama Salah).cpp deleted file mode 100644 index beb259c0b..000000000 --- a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Lama Salah).cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Author: Lama Salah - -class Solution { -public: - vector> adj; // Adjacency list to represent the graph. - vector vis; // Array to keep track of node colors. - - // Recursive function to check if the graph is not bipartite. - bool isNotBipartite(int node, int color) { - vis[node] = color; // Assign the current node the specified color (0 or 1). - - bool ans = false; // Variable to store the result. - - for (auto& i : adj[node]) { - if (vis[i] == -1) { - // If the neighbor hasn't been visited, recursively call the function with the opposite color. - ans |= isNotBipartite(i, color ^ 1); - } else if ((color ^ 1) != vis[i]) { - // If the neighbor has been visited and has the same color as the current node, the graph is not bipartite. - return true; - } - } - - return ans; - } - - bool isBipartite(vector>& graph) { - adj.assign(graph.size(), vector()); // Initialize the adjacency list. - vis.assign(graph.size(), -1); // Initialize the vis array. - - // Build the adjacency list based on the given graph. - for (int i = 0; i < graph.size(); i++) { - for (auto& j : graph[i]) { - adj[i].push_back(j); - adj[j].push_back(i); - } - } - - // Iterate over each node in the graph. - for (int i = 0; i < graph.size(); i++) { - if (vis[i] == -1 && isNotBipartite(i, 0)) { - // If the node hasn't been visited and the graph is not bipartite, return false. - return false; - } - } - - return true; // The graph is bipartite. - } -}; \ No newline at end of file diff --git a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Mahmoud aboelsoud).cpp b/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Mahmoud aboelsoud).cpp deleted file mode 100644 index 02f359ad0..000000000 --- a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Mahmoud aboelsoud).cpp +++ /dev/null @@ -1,58 +0,0 @@ -// author: Mahmoud Aboelsoud - -class Solution { -public: - // we just need to check if the graph is bipartite or not - // we can do that by coloring the nodes with 2 colors and check if there is a node with 2 colors - // if there is a node with 2 colors then the graph is not bipartite - // else the graph is bipartite - - - // graph: the adjacency list of the graph - vector> graph; - // cols: the color of each node - vector cols; - // n: the number of nodes in the graph - int n; - - // a dfs function to color the nodes - bool dfs(int node, int col){ - // color the node with col - cols[node] = col; - - // iterate over the neighbours of the node - for(auto&i: graph[node]){ - // if the neighbour is not colored then color it with the opposite color of the node - if(cols[i] == -1){ - // if the coloring failed after coloring the neighbour then the graph is not bipartite - if(!dfs(i, !col)) return false; - // if the neighbour is colored then check if it has the same color of the node - }else{ - // if the neighbour has the same color of the node then the graph is not bipartite - if(cols[i] == col) return false; - } - } - // if we reached here then the graph is bipartite - return true; - } - - - bool isBipartite(vector>& graph) { - // initialize the graph and the cols array and the number of nodes - this -> graph = graph; - n = graph.size(); - cols.assign(n, -1); - - // the graph may not be connected so we need to check each component - for(int i = 0; i < n; i++){ - // if the node is not colored then color it with 0 - if(cols[i] == -1){ - // if the coloring failed then the graph is not bipartite - if(!dfs(i, 0)) return false; - } - } - - // if we reached here then the graph is bipartite - return true; - } -}; diff --git a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Omar Sanad).cpp b/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Omar Sanad).cpp deleted file mode 100644 index 0cc762bca..000000000 --- a/05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Omar Sanad).cpp +++ /dev/null @@ -1,49 +0,0 @@ -// author : Omar Sanad - -class Solution { -public: - // declare an array to store the color of each node - int color[101]; - - // an adjacency list, where each node points to its neighbours - vector> adj; - - // a dfs function to check whether a graph is Bipartite or not... - // it keeps track of the current node, and the color of the parent node - bool isBi(int node, int prevColor) { - - // if this node already has a color - if (color[node]) - // then if the color is the same as its parent (its neighbour), the graph is not Bipartite - // else if the color of this node is different from its parent (its neighbour), till now graph not Bipartite - return color[node] != prevColor; - - // declare a variable that checks whether all the neighbours colors can be different from the current node - bool ok = true; - - // assign a color for the current node, give it a color that's different from the previous color - color[node] = 3 - prevColor; - - // iterate over all neighbours of the current node, and check if we can assign them a color different from the current node. - for (auto &child : adj[node]) - ok &= isBi(child, color[node]); - - // return the status till now (is it Bipartite or not)? - return ok; - } - - bool isBipartite(vector>& graph) { - this->adj = graph; - - // declare a variable that checks for each component if it is Bipartite or not - bool ok = true; - - // iterate over each non-visited node (in other words, each connected component), and check if the component is Bipartite or not - for (int i = 0; i < graph.size(); i++) - if (not color[i]) - ok &= isBi(i, 1); - - // return the answer to the problem - return ok; - } -}; diff --git a/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Ahmed Hossam).cpp b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Ahmed Hossam).cpp new file mode 100644 index 000000000..d3e533d85 --- /dev/null +++ b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Ahmed Hossam).cpp @@ -0,0 +1,36 @@ +// Author: Ahmed Hossam + +class Solution { +public: + + vector topKFrequent(vector& nums, int k) { + + // Create a frequency map to count the occurrences of each number + unordered_map < int, int > freq; + for (auto& i : nums) + freq[i]++; + + // Sort the numbers based on their frequency in descending order + // If two numbers have the same frequency, sort them in ascending order + sort(nums.begin(), nums.end(), [&](int a, int b) { + return freq[a] > freq[b] || (freq[a] == freq[b] && a < b); + }); + + // Create a vector to store the top k frequent elements + vector < int > ans = { nums.front() }; + + // Add unique elements to the vector until it reaches size k + for (int i = 1; i < nums.size(); i++) { + // If the vector has already reached size k, break the loop + if (ans.size() == k) break; + + // Add the current element to the vector if it is different from the previous one + if (nums[i] != nums[i - 1]) + ans.push_back(nums[i]); + } + + // Return the vector containing the top k frequent elements + return ans; + } + +}; diff --git a/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Mohamed Emara).cpp b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Mohamed Emara).cpp new file mode 100644 index 000000000..1cc1109d3 --- /dev/null +++ b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Mohamed Emara).cpp @@ -0,0 +1,42 @@ +// Author: Mohamed Emara + +class Solution { +public: + // Firstly, We want to calculate the frequency of each value in the vector + // Secondly, We want to sort them in an ascending order + // return a vector of first k elements + + vector topKFrequent(vector& nums, int k) { + // Store the frequency of each value in mp + mapmp; + for(auto it : nums) { + mp[it] ++; + } + + // Add the values of mp to tmp but with (value, key) + // to be able to sort them based on the freqecny of each value + vector>tmp; + for(auto it : mp) + tmp.push_back({it.second, it.first}); + + // sort & reverse to guarantee that the first k element have the + // maximum frequecny. + sort(tmp.begin(), tmp.end()); + reverse(tmp.begin(), tmp.end()); + + int cnt = 0; + + // Store the values of the most frequent element + vectorres; + for(auto it : tmp) { + res.push_back(it.second); + cnt ++; + + // if the values taken from tmp = k ---> break. + if(cnt == k) + break; + } + return res; + } +}; + diff --git a/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Noura Algohary).cpp b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Noura Algohary).cpp new file mode 100644 index 000000000..361e3c7df --- /dev/null +++ b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Noura Algohary).cpp @@ -0,0 +1,50 @@ +// Author: Noura Algohary + +class Solution { +public: +// comparison condition to sort in descending order +static bool cmp(pair& a, pair& b) +{ + return a.second > b.second; +} +vector > sortMap(map map) +{ + // Declare vector of pairs + vector > orderedMap; + + // Copy key-value pair from Map + // to vector of pairs + for (auto& it : M) { + orderedMap.push_back(it); + } + + // Sort using comparator function + sort(orderedMap.begin(), orderedMap.end(), cmp); + + return orderedMap; +} + vector topKFrequent(vector& nums, int k) { + mapmap; // original frequency map + vector > orderedMap; + vectoranswer; + + for(int num : nums) + { + if(map.count(num)) + map[num]++; + else + map.insert({num, 1}); + } + + // store ordered map in a vector of pairs + orderedMap = sortMap(map); + + for(auto it=orderedMap.begin(); k > 0 ;it++) + { + answer.push_back(it->first); + k--; + } + + return answer; + } +}; \ No newline at end of file diff --git a/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Omar Sanad).cpp b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Omar Sanad).cpp new file mode 100644 index 000000000..7def3d609 --- /dev/null +++ b/05- May/22- Top K Frequent Elements/22- Top K Frequent Elements (Omar Sanad).cpp @@ -0,0 +1,39 @@ +// author : Omar Sanad + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + // declare the maximum value that can be found in the array + const int MAX_NUM = 10000; + + // declare a frequency array to calc the occurence of all elements in the array + vector < int > fq(MAX_NUM * 2 + 5); + + // iterate over the given array nums, update the frequency of the elements in the array + for (auto &I : nums) + fq[I + MAX_NUM]++; // we add the value "MAX_NUM", to avoid accessing negative numbers + + // declare an array to store all unique elements in the given array "nums" + vector < int > unq_nums; + + // iterate over the frequency array, and add the numbers that appeared in the given array "nums" to "unq_nums" + for (int i = -MAX_NUM; i <= MAX_NUM; i++) + if (fq[i + MAX_NUM]) + unq_nums.emplace_back(i); + + // sort the "unq_nums" according to the freq of each element using the lamda expression + sort(unq_nums.begin(), unq_nums.end(), [&](const int& a, const int& b){ + return fq[a + MAX_NUM] > fq[b + MAX_NUM]; + }); + + // declare an array to store the anwer to the problem + vector < int > Ans; + + // add the answer to the problem in the array, the k most frequent elements + for (int i = 0; i < k; i++) + Ans.emplace_back(unq_nums[i]); + + // return the answer to the problem + return Ans; + } +}; diff --git a/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Ahmed Hossam).cpp b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Ahmed Hossam).cpp new file mode 100644 index 000000000..af5a68806 --- /dev/null +++ b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Ahmed Hossam).cpp @@ -0,0 +1,31 @@ +// Author: Ahmed Hossam + +class KthLargest { +public: + + // Priority queue to store the kth largest elements + priority_queue < int, vector < int >, greater < int > > pq; + int k; + + // Constructor to initialize the object with k and a vector of numbers + KthLargest(int k, vector < int >& nums) { + this -> k = k; + + // Add all the numbers to the priority queue + for(auto& x : nums) + add(x); + } + + // Function to add a new value to the priority queue and return the kth largest element + int add(int val) { + // Add the new value to the priority queue + pq.push(val); + + // Remove the smallest element if the size exceeds k + if(pq.size() > k) + pq.pop(); + + // Return the current kth largest element + return pq.top(); + } +}; diff --git a/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Esraa Syam).cpp b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Esraa Syam).cpp new file mode 100644 index 000000000..1c08b8d48 --- /dev/null +++ b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Esraa Syam).cpp @@ -0,0 +1,37 @@ +// author: Esraa Syam +#include +#include +using namespace __gnu_pbds; +template > +using ordered_map = tree; +template > +using ordered_set = ordered_map; + +template > +using ordered_multimap = tree; +template > +using ordered_multiset = ordered_multimap; +// order_of_key(k) : number of items strictly smaller than k +// find_by_order(k) : k-th largest element (counting from zero) +class KthLargest { +public: + /** + * solution idea: + * 1- use ordered_multiset to store the numbers + * 2- insert the numbers in the constructor + * 3- in add function, insert the number and return the kth largest number by using find_by_order(k) that returns the k-th largest element (counting from zero) + */ + ordered_multiset < int > ms; + int kk; + KthLargest(int k, vector& nums) { + kk = k; + for(auto & x : nums) ms.insert(x); // insert the elements in the multiset + } + + int add(int val) { + + ms.insert(val); // insert the new value + int ans = *ms.find_by_order(kk - 1); // find_by_order(k) : k-th largest element (counting from zero) so we need to subtract 1 + return ans; + } +}; diff --git a/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Mahmoud Aboelsoud).cpp b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Mahmoud Aboelsoud).cpp new file mode 100644 index 000000000..932e58cc4 --- /dev/null +++ b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Mahmoud Aboelsoud).cpp @@ -0,0 +1,43 @@ +// Author: Mahmoud Aboelsoud + +// the needed includes for using the multi ordered set +#include +#include +using namespace __gnu_pbds; + +// define the multi ordered set with greater equal comparator to store duplicates in descending order +#define multi_ordered_set tree, rb_tree_tag, tree_order_statistics_node_update> + +// the idea is to use a multi ordered set to store the elements in descending order +// and find the k'th largest element using find_by_order function + + +class KthLargest { +public: + // k: the k'th largest element + int k; + // ms: the multi ordered set + multi_ordered_set ms; + + // constructor + KthLargest(int k, vector& nums) { + // initialize k and insert all elements in the multi ordered set + this -> k = k; + for(auto&i: nums) ms.insert(i); + } + + // add a new element to the multi ordered set and return the k'th largest element + int add(int val) { + // insert the new element + ms.insert(val); + + // return the k'th largest element + return *ms.find_by_order(k - 1); + } +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ diff --git a/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Omar Sanad).cpp b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Omar Sanad).cpp new file mode 100644 index 000000000..54f2d286a --- /dev/null +++ b/05- May/23- Kth Largest Element in a Stream/23- Kth Largest Element in a Stream (Omar Sanad).cpp @@ -0,0 +1,56 @@ +// author : Omar Sanad + +/* +Here In this solution I will use a data structure call ordered multiset +for more information about this data structre check out this https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/ +briefly the ordered set is like the ordinary set, but we have two extra functions +a function that finds the position of an element, +a function that finds the i_th element + */ + +// We have to include some header files for this data structure +#include +#include + +using namespace __gnu_pbds; + +template > using +__ordered_map = tree; +template > using +ordered_set = __ordered_map; +template > using +__ordered_multimap = tree; +template > using +ordered_multiset = __ordered_multimap; + +class KthLargest { +public: + // declare the k in the class itself + int k; + + // declare an ordered multi set that sorts the elements in descending order (from great to little) + ordered_multiset < int, greater_equal > ost; + KthLargest(int k, vector& nums) { + // assign the given k to the k declared in the class + this->k = k; + + // add the given elements to the ordered multi set + for (auto &I : nums) + ost.insert(I); + } + + int add(int val) { + + // add the given element to the ordered multi set + ost.insert(val); + + // return the element at the index k + return *ost.find_by_order(k - 1); + } +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ diff --git a/05- May/README.md b/05- May/README.md index 668c8c8f7..072bc7bb9 100644 --- a/05- May/README.md +++ b/05- May/README.md @@ -42,6 +42,7 @@ 1. **[Is Graph Bipartite?](#19--is-graph-bipartite)** 1. **[Evaluate Division](#20--evaluate-division)** 1. **[Shortest Bridge](#21--shortest-bridge)** +1. **[Kth Largest Element in a Stream](#23--kth-largest-element-in-a-stream)**


@@ -1190,4 +1191,52 @@ public: } }; ``` + +
+

+ +## 23) [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) + +### Difficulty + +![](https://img.shields.io/badge/Easy-green?style=for-the-badge) + +### Related Topic + +`Tree` `Design` `Binary Search Tree` `Heap (Priority Queue)` `Binary Tree` `Data Stream` + +### Code + + +```cpp +class KthLargest { +public: + + // Priority queue to store the kth largest elements + priority_queue < int, vector < int >, greater < int > > pq; + int k; + + // Constructor to initialize the object with k and a vector of numbers + KthLargest(int k, vector < int >& nums) { + this -> k = k; + + // Add all the numbers to the priority queue + for(auto& x : nums) + add(x); + } + + // Function to add a new value to the priority queue and return the kth largest element + int add(int val) { + // Add the new value to the priority queue + pq.push(val); + + // Remove the smallest element if the size exceeds k + if(pq.size() > k) + pq.pop(); + + // Return the current kth largest element + return pq.top(); + } +}; +``` \ No newline at end of file