id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
25,815
pstring_test.cpp
mandliya_algorithms_and_data_structures/string_problems/pstring_test.cpp
/* 30 unit tests testing pstring library ( a string library) located in include/pstring.cpp include/pstring.h include/pUnitTest.h include/pUnitTest.cpp */ #include <cstdio> #include "pUnitTest.h" #include "pstring.h" bool summary_flag = false; unsigned long int tpass = 0, tfail = 0; using string = algo::String; int main(int argc, const char * argv[]) { // Versions n things printf("String version: %s\n", string::version()); printf("UTest version: %s\n", UTest::version()); UTest u("PstringLib"); u.summary(summary_flag); // string printf("\nTesting string -----\n"); u.init("string"); const char * _ctest = " \tfoo \r\n"; string ttest = _ctest; u.test("cstring ctor", ttest.length() == 12); string other = std::move(ttest); u.test("move ctor", other.length() == 12 && ttest.length() == 0); ttest = std::move(other); u.test("move assignment", other.length() == 0 && ttest.length() == 12); other = ttest; u.test("copy assignment", other.length() == 12 && ttest.length() == 12); ttest = "this is a string"; u.test("length is 16", ttest.length() == 16 && ttest.size() == 16); u.test("substr", ttest.substr(10, 3) == string("str")); u.test("charfind", ttest.find('s') == 3); u.test("charfind (not found)", ttest.find('z') == -1); string string_upper = ttest.upper(); string string_lower = string_upper.lower(); u.test("upper and lower", string_upper == string("THIS IS A STRING") && string_lower == string("this is a string")); string x = "foo"; string y = "bar"; string z = x + "baz" + y; u.test("concat", z.length() == 9 && memcmp(z.c_str(), "foobazbar", 10) == 0); x = y = "foo"; u.test("foo == foo", (x == y)); u.test("foo > foo", !(x > y)); u.test("foo >= foo", (x >= y)); u.test("foo < foo", !(x < y)); u.test("foo <= foo", (x <= y)); x = "bar"; u.test("bar == foo", !(x == y)); u.test("bar > foo", !(x > y)); u.test("bar >= foo", !(x >= y)); u.test("bar < foo", (x < y)); u.test("bar <= foo", (x <= y)); u.test("foo == bar", !(y == x)); u.test("foo > bar", (y > x)); u.test("foo >= bar", (y >= x)); u.test("foo < bar", !(y < x)); u.test("foo <= bar", !(y <= x)); u.test("subscript x[0]", x[0] == 'b'); u.test("subscript x[1]", x[1] == 'a'); u.test("subscript x[2]", x[2] == 'r'); u.test("subscript terminator x[3]", x[3] == 0); x = "this is a big string ###foobarbaz### this is a big string"; x = x.replace(21, 15, "foo bar baz"); u.test("replace", x.length() == 53 && memcmp(x.c_str(), "this is a big string foo bar baz this is a big string", 54) == 0); tpass += u.pass_count(); tfail += u.fail_count(); u.report(); printf("\nTotals: pass: %ld, fail: %ld\n", tpass, tfail); return 0; // Done. Yay! }
2,917
C++
.cpp
74
34.756757
127
0.544326
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,816
robinKarpStringMatching.cpp
mandliya_algorithms_and_data_structures/string_problems/robinKarpStringMatching.cpp
/* * Given a string pattern(P) and large Text string (T), Write a function search( P , T) which provide all the occurrences of P in T. * example : T => "AABAACAADAABAAABAA". * P => "AABA" * Output : 0, 9, 13 ( all indices of T where pattern string P is starts to match. * * Approach: * Lets say size of T ==> N * Size of P ==> M. * Lets have a hash function --> hash. * Step 1 :We will calculate hash of Pattern P, lets say it is p * Step 2 : Then we will calculate hash of text portion from T[0-->M-1]. lets say t(0) * Step 3: if ( p == t(0) ) if they match, add it to list of occurrences. * Step 4: Go back to step 2, and calculate t(1) i.e hash of T[1-->M] using t(0) in O(1). * * The question remains, how do we calculate t(1) from t(0) in O(1), we do it using Horner's rule * H[m] = X[m]+ 10 (X[m-1] + 10(X[m-2]+……10(X[2] + 10 X[1]….))) —-> The 10 is the number of characters * * By Induction, we can calculate * t(s+1) = 10 ( t(s) - 10^(m-1) * T[s] ) + T[s+m+1] * * so for example * T = "123456", and m = 3 * T(0) = 123 * T(1) = 10 * ( 123 - 100 * 1) + 4 = 234 * * So in our case number of character can be 256 * There t(s+1) = 256 ( t(s) - 256 ^ (m-1) * T[s] ) + T[s+m+1] * * alphabet = 256; * In our program we will precalculate 256 ^ m-1; * h = pow(256, m-1) * */ #include<iostream> #include<vector> //alphabet is total characters in alphabet. const int alphabet = 256; //a large prime number const int q = 101; std::vector<int> search(const std::string pattern, const std::string text) { int M = pattern.size(); int N = text.size(); long h = 1; //hash val int p = 0; //hash value of pattern; int t = 0; //hash value of current text substring of size m; std::vector<int> indices; // store all the indices of text where pattern matched. //hash value - pow( alphabet, m-1) % q; for ( int i = 0; i < M - 1; ++i ) { h = (alphabet * h) % q; } //initial hash values of pattern and text substring for ( int i = 0; i < M ; ++i ) { p = ( alphabet * p + pattern[i] ) % q; t = ( alphabet * t + text[i] ) % q; } //Slide the pattern over text for ( int i = 0; i <= N - M; ++i ) { int j = 0; //if hash matches, check the chars one by one. if ( p == t ) { for (j = 0; j < M ; ++j ) { if ( pattern[j] != text[i+j] ) { break; } } //pattern and text portion match if ( j == M ) { indices.push_back(i); } } else { //calculate the next t t = ( alphabet * ( t - text[i] * h) + text[i+M] ) % q; // in case current t is negative if ( t < 0 ) { t = ( t + q); } } } return indices; } void printIndices(std::vector<int> indices, const std::string pattern, const std::string text) { if ( indices.size() == 0 ) { std::cout << "\"" << pattern << "\" does not occur in \"" << text << "\"" << std::endl; } else { std::cout << "\"" << pattern << "\" occurs in \"" << text << "\" at following position(s):"; for ( auto i : indices ) { std::cout << i << " "; } std::cout << std::endl; } } int main() { std::string txt1("AABAACAADAABAAABAA"); std::string pat1("AABA"); std::string txt2("Hello World Hello World , All is great in World"); std::string pat2("World"); std::string txt3("GEEKS FOR GEEKS"); std::string pat3("GEEKS"); std::vector<int> indices1 = search(pat1, txt1); printIndices(indices1, pat1, txt1); std::vector<int> indices2 = search(pat2, txt2); printIndices(indices2, pat2, txt2); std::vector<int> indices3 = search(pat3, txt3); printIndices(indices3, pat3, txt3); return 0; }
4,205
C++
.cpp
112
31.357143
132
0.506558
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,817
z.cpp
mandliya_algorithms_and_data_structures/string_problems/z.cpp
#include <iostream> #include <string> #include <vector> /** * Function to fill in zvalues vector of ztext */ std::vector<size_t> fillZvalues(const std::string & ztext) { size_t n = ztext.length(); std::vector<size_t> zvals(n, 0); size_t L = 0, R = 0; // s[L..R] represent the prefix string. for (size_t i = 1; i < n; ++i) { if ( i > R ) { L = R = i; while( R < n && ztext[R-L] == ztext[R] ) { ++R; } zvals[i] = R-L; --R; } else { size_t K = i - L; if( zvals[K] < R-i+1 ) { zvals[i] = zvals[K]; } else { L = R = i; while( R < n && ztext[R-L] == ztext[R] ) { ++R; } zvals[i] = R-L; --R; } } } return zvals; } /** * This function returns index of text where pattern matches using z algorithm */ std::vector<size_t> search( const std::string & text, const std::string & pattern ) { std::string ztext = pattern + '$' + text; std::vector<size_t> zvalues = fillZvalues(ztext); std::vector<size_t> indices; for ( size_t i = 1; i < zvalues.size(); ++i ) { if (zvalues[i] == pattern.length()) { indices.push_back(i - pattern.length() -1 ); } } return indices; } int main() { std::string text, pattern; std::cout << "String searching using Z algorithm:\n"; std::cout << "Enter text:"; std::getline(std::cin, text); std::cout << "Pattern :"; std::getline(std::cin, pattern); std::vector<size_t> indices = search(text, pattern); for (auto i : indices ) { std::cout << pattern << " occurs in given text starting at index " << i << std::endl; } return 0; }
1,555
C++
.cpp
62
22.387097
87
0.587643
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,818
length_of_last_word.cpp
mandliya_algorithms_and_data_structures/string_problems/length_of_last_word.cpp
/* * Given a string consisting of lower/upper case alphabets and empty space character ' '. * Return the length of last word in the string. * * A word is character sequence containing non-space characters only. * * Return 0, if no last word exist. * * Approach: * * Start from end of the string, and trim the whitespace. * When we find the first non-space character, find the next space or till we reach beginning of string. * */ #include <iostream> int get_length_of_last_word(const std::string& str) { if (str.length() == 0) { return 0; } int n = str.length(); int i = n - 1; int j = 0; // Trim the whitespace in the end while(i >= 0 && str[i] == ' ') i--; // Check if we already reached beginning of the string. if (i < 0) { return 0; } // Now start from the first non-space character for (j = i; j >= 0; --j) { if (str[j] == ' ') break; } return i - j; } int main() { std::string str1 = "Hello"; std::string str2 = "Hello "; std::string str3 = "Hello World!"; std::cout << "String without any space of length " << str1.length() << ": " << str1 << std::endl; std::cout << "Length of last word :" << get_length_of_last_word(str1) << std::endl; std::cout << "String with lot of space in the end, with length of string " << str2.length() << ": " << str2 << std::endl; std::cout << "Length of last word :" << get_length_of_last_word(str2) << std::endl; std::cout << "String with lot of space in the middle, with length of string " << str3.length() << ": " << str3 << std::endl; std::cout << "Length of last word :" << get_length_of_last_word(str3) << std::endl; return 0; }
1,794
C++
.cpp
48
32.125
130
0.58425
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,819
find_difference.cpp
mandliya_algorithms_and_data_structures/string_problems/find_difference.cpp
/* * Find the difference between two string. * String t is generated by random shuffling string s and then add * one more letter at a random position. * Determine the character which is different in t. * * Approach: Since only one letter is different between s and t, * we could try XOR approach. * XOR of a character with itself will give 0. */ #include <iostream> char find_difference(const std::string& s, const std::string& t) { std::string r = s + t; char ch = 0; for (char c : r) { ch ^= c; } return ch; } int main() { std::string str1{"hello"}; std::string str2{"ollleh"}; std::cout << "String 1: " << str1 << std::endl; std::cout << "String 2: " << str2 << std::endl; std::cout << "Diff: " << find_difference(str1, str2) << std::endl; return 0; }
827
C++
.cpp
29
25.034483
70
0.633838
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,820
next_permutation.cpp
mandliya_algorithms_and_data_structures/string_problems/next_permutation.cpp
/** * Implement next permutation algorithm. i.e * Given a word w, rearrange the letters of w to construct another word s in such a way that * s is lexicographically greater than w. * In case of multiple possible answers, find the lexicographically smallest one. * Example: * ab --> ba * bb --> bb * hefg --> hegf * dhck --> dhkc * dkhc --> hcdk */ #include <iostream> std::string next_permutation( std::string str) { int len = str.length(); int i = len -1; // We will iterate string from end, and once we have encountered a pair of letters // such that str[i] < str[i-1] , i-1 would become our pivot while( i > 0 && str[i] <= str[i-1] ) { --i; } if ( i == 0 ) { return str; } //our pivot right now would be str[i-1] int j = len - 1; while( j >= i && str[j] <= str[i-1] ) { --j; } std::swap(str[i-1], str[j]); j = len - 1; //reverse the suffix while( i < j ) { std::swap(str[i], str[j]); --j; ++i; } return str; } int main() { std::string str, str_next; std::cout << "Enter a string : "; std::cin >> str; str_next = next_permutation(str); std::cout << "Next permutation of " << str << " is " << str_next << std::endl; return 0; }
1,237
C++
.cpp
51
21.333333
93
0.591716
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,821
queueDemo.cpp
mandliya_algorithms_and_data_structures/queue_problems/queueDemo.cpp
#include <iostream> #include "../include/queue.h" #include "../include/generic.h" int main() { const int QUEUE_SIZE = 10; algo::Queue<int> Q(QUEUE_SIZE); std::cout << "Pushing following values to queue:\n"; for ( int i = 0; i < QUEUE_SIZE; ++i ) { int rand_value = algo::random_range( 5, 50 ); std::cout << rand_value << " "; Q.push(rand_value); } std::cout << std::endl; std::cout << "Size of Queue is :" << Q.count() << std::endl; std::cout << "\nPopping queue values :\n"; while ( !Q.empty() ) { std::cout << Q.front() << " "; Q.pop(); } std::cout << std::endl; return 0; }
666
C++
.cpp
24
23.041667
64
0.538341
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,822
node_ancestors_in_root_path.cpp
mandliya_algorithms_and_data_structures/tree_problems/node_ancestors_in_root_path.cpp
/** * Given a binary Tree * 1 * / \ * 2 3 * / \ * 4 5 * \ * 6 * * Ancestor of node 6 in root path would be 4, 2, and 1. * */ #include <iostream> #include <vector> struct Node { int data; Node * left; Node * right; Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; bool get_ancestors_util( Node * root, int key, std::vector<int> & ancestors ) { if ( root == nullptr ) { return false; } if ( root->data == key ) { return true; } if ( get_ancestors_util(root->left, key, ancestors) || get_ancestors_util(root->right, key, ancestors) ) { ancestors.push_back(root->data); return true; } return false; } std::vector<int> get_ancestors( Node * root, int key ) { std::vector<int> ancestors; get_ancestors_util(root, key, ancestors); return ancestors; } void printAncestors( Node * root ) { std::vector<int> vec; for ( int i = 1; i <= 6; ++i ) { std::cout << "Ancestor of node with key " << i << " are:"; vec = get_ancestors( root, i ); for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; vec.clear(); } } int main() { Node * root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->left->left->right = new Node(6); printAncestors(root); return 0; }
1,403
C++
.cpp
62
20.467742
79
0.584835
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,823
find_target_k.cpp
mandliya_algorithms_and_data_structures/tree_problems/find_target_k.cpp
/* * Given a Binary Search Tree and a target number, * return true if there exist two elements in the BST such that their sum is equal to the given target. * * Input: * 5 * / \ * 3 6 * / \ \ * 2 4 7 * * Target = 9 * Output: True * * Target = 28 * Output: False * * Approach: * * Use a set to insert node values as we traverse the tree. If we find a node such that * k-current_node_val exist already in set, it means we have found a pair of nodes whose values adds up to k. * (i.e. current node and node with value k-current_node_val) */ #include <iostream> #include <unordered_set> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d): data{d}, left{nullptr}, right{nullptr}{} }; bool find_target_k(TreeNode* root, int k, std::unordered_set<int>& set) { if (root == nullptr) { return false; } if (set.find(k - root->data) != set.end()) { return true; } set.insert(root->data); return find_target_k(root->left, k, set) || find_target_k(root->right, k, set); } bool find_target_k(TreeNode* root, int k) { std::unordered_set<int> set; return find_target_k(root, k, set); } void print_inorder(TreeNode* root) { if (root != nullptr) { print_inorder(root->left); std::cout << root->data << " "; print_inorder(root->right); } } int main() { TreeNode* root = new TreeNode(5); root->left = new TreeNode(3); root->right = new TreeNode(6); root->left->left = new TreeNode(2); root->left->right = new TreeNode(4); root->right->right = new TreeNode(7); std::cout << "Inorder traversal of the current tree:"; print_inorder(root); std::cout << std::endl; if (find_target_k(root, 9)) { std::cout << "The tree contains two nodes which adds up to 9\n"; } else { std::cout << "The tree does not contain two nodes which adds up to 9\n"; } if (find_target_k(root, 24)) { std::cout << "The tree contains two nodes which adds up to 24\n"; } else { std::cout << "The tree does not contain two nodes which adds up to 24\n"; } return 0; }
2,195
C++
.cpp
79
23.746835
109
0.617284
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,824
sortedArrayToBST.cpp
mandliya_algorithms_and_data_structures/tree_problems/sortedArrayToBST.cpp
/** * Given a sorted array, convert it balaned binary search tree. */ #include<iostream> #include<vector> struct Node { int data; Node * left; Node * right; Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; Node * sortedArrayToBST( std::vector<int> & arr, int start, int end ) { if ( start > end ) { return nullptr; } int mid = ( start + end )/2; Node * node = new Node(arr[mid]); node->left = sortedArrayToBST( arr, start, mid - 1 ); node->right = sortedArrayToBST( arr, mid + 1, end ); return node; } void printArray( std::vector<int> & arr ) { for ( auto i : arr ) { std::cout << i << " "; } std::cout << std::endl; } void printTreeInOrder( Node * root ) { if( root ) { printTreeInOrder( root->left ); std::cout << root->data << " "; printTreeInOrder( root->right ); } } int main() { std::vector<int> arr{ 1, 2, 3, 4, 5, 6, 7, 8 }; std::cout << "Arr :"; printArray(arr); Node * root = sortedArrayToBST(arr, 0, arr.size() - 1); std::cout << "Tree :"; printTreeInOrder(root); std::cout << std::endl; return 0; }
1,074
C++
.cpp
44
22.454545
71
0.62207
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,826
k_sum_paths.cpp
mandliya_algorithms_and_data_structures/tree_problems/k_sum_paths.cpp
/* * Given a binary tree, print all the paths whose sum is equal to k * 1 * / \ * 3 -1 * / \ / \ * 2 1 4 5 * / / \ \ * 1 1 2 6 * * For k = 5: * 3 2 * 3 1 1 * 1 3 1 * 4 1 * 1 -1 4 1 * -1 4 2 * 5 * 1 -1 5 */ #include <iostream> #include <vector> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d) : data {d}, left {nullptr}, right {nullptr} { } }; void printPath(const std::vector<int>& path, int index) { for (auto it = path.begin() + index; it != path.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; } void printKPaths(TreeNode * node, std::vector<int>& paths, int k) { if (!node) { return; } // push the current node to paths // paths.push_back(node->data); // now, lets explore the left and right sub-trees // printKPaths(node->left, paths, k); printKPaths(node->right, paths, k); // check if we have reached sum of tree nodes to k. // also, do not break, once we have reached k, as we may have negative // values too. // /* int sum = 0; for (int j=paths.size()-1; j>=0; j--) { sum += (paths[j]); if (sum == k) { printPath(paths, j); } } */ int sum = 0; for (auto it = paths.rbegin(); it != paths.rend(); ++it) { sum += (*it); if (sum == k) { int indexFromStart = paths.size() - 1 - (it - paths.rbegin()); printPath(paths, indexFromStart); } } paths.pop_back(); } int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(3); root->left->left = new TreeNode(2); root->left->right = new TreeNode(1); root->left->right->left = new TreeNode(1); root->right = new TreeNode(-1); root->right->left = new TreeNode(4); root->right->left->left = new TreeNode(1); root->right->left->right = new TreeNode(2); root->right->right = new TreeNode(5); root->right->right->right = new TreeNode(2); int k = 5; std::vector<int> paths; printKPaths(root, paths, k); return 0; }
2,390
C++
.cpp
95
18.936842
75
0.492091
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,828
lowest-common-ancestor-binary-tree.cpp
mandliya_algorithms_and_data_structures/tree_problems/lowest-common-ancestor-binary-tree.cpp
/* * We did lowest common ancestor of a binary SEARCH tree in a different problem. * This will provide lowest common ancestor of a binary tree. * Example * 20 * / \ * 24 22 * / \ * 25 12 * / \ * 10 14 * * In the above tree, LCA of 10 and 14 is 12 * similarly 14 and 25 will have LCA 24 * LCA of 10 and 22 is 20. */ #include <iostream> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d): data{ d }, left{ nullptr }, right{ nullptr }{ } }; void inorder(TreeNode * root) { if (root) { inorder(root->left); std::cout << root->data << " "; inorder(root->right); } } TreeNode* lowest_common_ancestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr || p == root || q == root) { return root; } TreeNode* leftLCA = lowest_common_ancestor(root->left, p, q); TreeNode* rightLCA = lowest_common_ancestor(root->right, p, q); return (!leftLCA ? rightLCA : !rightLCA ? leftLCA : root); } int main() { // Lets create the tree in example TreeNode* root = new TreeNode(20); root->left = new TreeNode(24); root->right = new TreeNode(22); root->left->left = new TreeNode(25); root->left->right = new TreeNode(12); root->left->right->left = new TreeNode(10); root->left->right->right = new TreeNode(14); std::cout << "Inorder Traversal of the tree:" << std::endl; inorder(root); std::cout << std::endl; std::cout << "The LCA of nodes with values 10 and 14 is:" << lowest_common_ancestor(root, root->left->right->left, root->left->right->right)->data << std::endl; std::cout << "The LCA of nodes with values 25 and 14 is:" << lowest_common_ancestor(root, root->left->left, root->left->right->right)->data << std::endl; std::cout << "The LCA of nodes with values 10 and 22 is:" << lowest_common_ancestor(root, root->left->right->left, root->right)->data << std::endl; return 0; }
2,104
C++
.cpp
65
27.907692
97
0.594074
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,829
string_from_tree.cpp
mandliya_algorithms_and_data_structures/tree_problems/string_from_tree.cpp
/* * Given a binary tree, traversing preorder, construct a string output * containing node values and parenthesis. * The null node needs to be represented by empty parenthesis pair "()". * And you need to omit all the empty parenthesis pairs that don't affect * the one-to-one mapping relationship between the string and the original * binary tree * * Example: * 1 * / \ * 2 3 * / \ * 4 5 * * Output: 1(2(4)(5))(3) * Originally it should be 1(2(4)(5))(3()()), but we are ommiting * all the unnecessary empty parenthesis pairs. * * Example: * * 1 * / \ * 2 3 * \ * 4 * Output: 1(2()(4))(3) * Here, we can't omit the first parenthesis pair to break * the one-to-one mapping relationship between the input and the output. * As without empty parenthesis, it would not be clear that 4 is a right child. */ #include <iostream> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d): data{d}, left{nullptr}, right{nullptr}{} }; std::string string_from_tree(TreeNode* root) { if (root == nullptr) { return std::string(""); } if (root->left == nullptr && root->right == nullptr) { return std::to_string(root->data); } if (root->right == nullptr) { return std::to_string(root->data) + "(" + string_from_tree(root->left) +")"; } return std::to_string(root->data) + "(" + string_from_tree(root->left) + ")(" + string_from_tree(root->right) + ")"; } int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->right = new TreeNode(4); std::cout << "Tree to string: " << string_from_tree(root) << std::endl; return 0; }
1,858
C++
.cpp
65
24.784615
79
0.593277
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,830
kth_smallest.cpp
mandliya_algorithms_and_data_structures/tree_problems/kth_smallest.cpp
/* * Given a binary search tree, find the kth smallest element in it. * Assumption: k is always valid i.e. 1 <= k <= total number of nodes in BST * *         8  *        /   \  *       /     \  *      4      10  *     / \     / \  *    /   \   /   \  *   2     6 9    12 * k = 2, answer: 4 * k = 7, answer: 12 */ #include <iostream> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d): data{d}, left{nullptr}, right{nullptr} { } }; int countNodes(TreeNode* root) { if (root == nullptr) { return 0; } return 1 + countNodes(root->left) + countNodes(root->right); } int kthSmallest(TreeNode* root, int k) { int count = countNodes(root->left); if (k <= count && root->left) { return kthSmallest(root->left, k); } else if ( k > count + 1 && root->right) { return kthSmallest(root->right, k - count - 1); } return root->data; } void insertNode(TreeNode* &root, int d) { if (!root) { TreeNode* newNode = new TreeNode(d); root = newNode; return; } if (root->data >= d) { insertNode(root->left, d); } else { insertNode(root->right, d); } } void inorder(TreeNode* root) { if (root) { inorder(root->left); std::cout << root->data << " "; inorder(root->right); } } int main() { TreeNode* root = nullptr; insertNode(root, 8); insertNode(root, 4); insertNode(root, 10); insertNode(root, 2); insertNode(root, 6); insertNode(root, 9); insertNode(root, 12); std::cout << "Inorder traversal of tree:" << std::endl; inorder(root); std::cout << std::endl; std::cout << "2nd smallest element in tree: " << kthSmallest(root, 2) << std::endl; std::cout << "4th smallest element in tree: " << kthSmallest(root, 4) << std::endl; std::cout << "7th smallest element in tree: " << kthSmallest(root, 7) << std::endl; return 0; }
2,087
C++
.cpp
82
20
76
0.553581
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,831
validate_bst.cpp
mandliya_algorithms_and_data_structures/tree_problems/validate_bst.cpp
/* * Validate if a given binary tree is a binary search tree. * * Example: * * 10 * / \ * 5 15 * * Answer: True * * Example: * * 10 * / \ * 5 15 * / \ / \ * 2 7 9 17 * * Answer : False */ #include <iostream> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d) : data{d}, left{nullptr}, right{nullptr} {} }; bool is_valid_bst(TreeNode* root, TreeNode* min, TreeNode* max) { if (root == nullptr) { return true; } if (min != nullptr && root->data <= min->data) { return false; } if (max != nullptr && root->data >= max->data) { return false; } return is_valid_bst(root->left, min, root) && is_valid_bst(root->right, root, max); } bool is_valid_bst(TreeNode* root) { return is_valid_bst(root, nullptr, nullptr); } void print_inorder(TreeNode* root) { if (root != nullptr) { print_inorder(root->left); std::cout << root->data << " "; print_inorder(root->right); } } int main() { TreeNode* root1 = new TreeNode(10); root1->left = new TreeNode(5); root1->right = new TreeNode(15); std::cout << "Inorder traversal of tree: "; print_inorder(root1); std::cout << std::endl; if (is_valid_bst(root1)) { std::cout << "Above tree is a valid binary search tree.\n"; } else { std::cout << "Above tree is not a valid binary search tree.\n"; } TreeNode* root2 = new TreeNode(10); root2->left = new TreeNode(5); root2->right = new TreeNode(15); root2->left->left = new TreeNode(2); root2->left->right = new TreeNode(7); root2->right->left = new TreeNode(9); root2->right->right = new TreeNode(17); std::cout << "Inorder traversal of tree: "; print_inorder(root2); std::cout << std::endl; if (is_valid_bst(root2)) { std::cout << "Above tree is a valid binary search tree.\n"; } else { std::cout << "Above tree is not a valid binary search tree.\n"; } return 0; }
2,145
C++
.cpp
84
21
87
0.559727
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,832
levelOrderTraversalIterative.cpp
mandliya_algorithms_and_data_structures/tree_problems/levelOrderTraversalIterative.cpp
/* * Program to implement level order traversal - iterative version */ #include <iostream> #include <queue.h> const int maxNodes = 15; struct Node { int data; Node* left; Node* right; }; /* * An helper function to get a new node */ Node* newNode( int data ) { Node *temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } /* * function to insert a new node. * Arg : root Node, new data */ void insert( Node* & node, int data) { if ( node == nullptr) { node = newNode(data); } else { if (data < node->data) { insert( node->left, data); } else { insert( node->right, data); } } } /* * Level order traversal */ void levelOrder( Node * node ) { std::cout << "Printing level order traversal of the tree:\n"; if ( node == nullptr ) { std::cout << "Empty tree\n"; return ; } algo::Queue<Node*> Q(maxNodes); Q.push(node); while ( !Q.empty() ) { Node *currNode = Q.front(); std::cout << currNode->data << " "; Q.pop(); if (currNode->left != nullptr) { Q.push(currNode->left); } if (currNode->right != nullptr) { Q.push(currNode->right); } } std::cout << std::endl; } int main() { Node * root; insert(root, 4); insert(root, 2); insert(root, 6); insert(root, 1); insert(root, 3); insert(root, 5); insert(root, 7); levelOrder(root); return 0; }
1,612
C++
.cpp
86
13.697674
65
0.531044
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,833
level_of_node.cpp
mandliya_algorithms_and_data_structures/tree_problems/level_of_node.cpp
/** * Given a Binary Tree and a key, write a function that returns level of the key. * 3 * / \ * 2 5 * / \ * 1 4 * * Here 3 is on level 1 * 2 and 5 have level 2 * 1 and 4 have level 3 * If key not in tree, return 0 * */ #include <iostream> struct Node { int data; Node * left; Node * right; Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; int get_node_level_util( Node * root, int key, int level ) { if ( root == nullptr ) { return 0; } if ( root->data == key ) { return level; } int downlevel = get_node_level_util( root->left, key, level + 1); if ( downlevel != 0 ) { return downlevel; } downlevel = get_node_level_util( root->right, key, level + 1); return downlevel; } int get_node_level( Node * root, int key ) { return get_node_level_util( root, key, 1 ); } void printLevels(Node * root) { for ( int i = 1; i <= 6; ++i ) { std::cout << "Level of node with key as " << i << " is " << get_node_level( root, i ) << std::endl; } } int main() { Node * root = new Node(3); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(1); root->left->right = new Node(4); printLevels(root); return 0; }
1,212
C++
.cpp
52
21.384615
101
0.603806
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,834
convert_to_sum_tree.cpp
mandliya_algorithms_and_data_structures/tree_problems/convert_to_sum_tree.cpp
/** * Convert a given tree to to sum tree. * Given : A tree with positive and negative data values. * Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. * The values of leaf nodes are changed to 0. * 10 20 * / \ / \ * -2 6 ----> 4 12 * / \ / \ / \ / \ * 8 -4 7 5 0 0 0 0 */ #include <iostream> struct Node { int data; Node * left; Node * right; Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; int toSumTree( Node * root ) { if ( root == nullptr ) { return 0; } //store the previous value int previous_val = root->data; // make current node as sum of left and right node. left nodes will become zero root->data = toSumTree(root->left) + toSumTree(root->right); // Now since each node contains the sum of the left and right sub trees in the original tree. // we will return the sum of old + new value as sum. // Focus on the world original here, and try understanding it from top to bottom. return root->data + previous_val; } void inorder( Node * root ) { if ( root ) { inorder(root->left); std::cout << root->data << " "; inorder(root->right); } } int main() { Node * root = new Node(10); root->left = new Node(-2); root->right = new Node(6); root->left->left = new Node(8); root->left->right = new Node(-4); root->right->left = new Node(7); root->right->right = new Node(5); std::cout << "Inorder traversal of tree:"; inorder(root); std::cout << "\nAfter transforming to sum tree\n"; toSumTree(root); std::cout << "Inorder traversal of tree:"; inorder(root); std::cout << std::endl; return 0; }
1,872
C++
.cpp
62
27.419355
112
0.575791
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,835
reverseLevelOrderTraversal.cpp
mandliya_algorithms_and_data_structures/tree_problems/reverseLevelOrderTraversal.cpp
/* * Reverse Level Order Traversal of Binary Tree * Given a binary tree, print its nodes level by level in reverse order. * i.e. all nodes present at last level should be printed first followed * by nodes of second-last level and so on.. * All nodes for any level should be printed from left to right. * * 1 * / \ * 2 3 * / \ / \ * 4 5 6 7 * * The reverse level order traversal of the tree is : * 4, 5, 6, 7, 2, 3, 1 */ #include <iostream> #include <stack> #include <queue> struct TreeNode { int data; TreeNode *left; TreeNode *right; TreeNode (int d) : data {d} , left {nullptr} , right {nullptr} {} }; void printReverseLevelOrder(TreeNode* root) { if (!root) { return; } // Idea is to do a level order traversal and then // push the nodes in a stack, so we can print in // reverse order. // std::queue<TreeNode*> nodeQueue; std::stack<TreeNode*> nodeStack; nodeQueue.push(root); while (!nodeQueue.empty()) { TreeNode* curr = nodeQueue.front(); nodeQueue.pop(); nodeStack.push(curr); // We will push right node first, as we want to print // reverse level order traversal. // if (curr->right) { nodeQueue.push(curr->right); } if (curr->left) { nodeQueue.push(curr->left); } } std::cout << "Reverse level order traversal:"; while (!nodeStack.empty()) { TreeNode* curr = nodeStack.top(); std::cout << curr->data << " "; nodeStack.pop(); } std::cout << std::endl; } int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); printReverseLevelOrder(root); return 0; }
2,152
C++
.cpp
80
20.6125
73
0.553493
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,836
levelOrderTraversalRecursive.cpp
mandliya_algorithms_and_data_structures/tree_problems/levelOrderTraversalRecursive.cpp
/* * Level order BST traveral iterative */ #include <iostream> struct Node { int data; Node *left; Node *right; }; Node* newNode( int data ) { Node *temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } void insert( Node* & node, int data) { if ( node == nullptr) { node = newNode(data); } else { if ( data < node->data ) { insert(node->left, data); } else { insert(node->right, data); } } } int height( const Node * node) { if ( node == nullptr ) { return 0; } else { int leftHeight = height(node->left); int rightHeight = height(node->right); return ( 1 + ((leftHeight > rightHeight) ? leftHeight : rightHeight)); } } void printLevel(Node *node, int level) { if (node == nullptr) { return; } if ( level == 1 ) { std::cout << node->data <<" "; } else { printLevel( node->left, level - 1); printLevel( node->right, level - 1); } } void levelOrder( Node * node ) { std::cout << "Level order traversal of the tree:\n"; int h = height(node); for ( int i = 1; i <= h; ++i ) { printLevel(node, i ); std::cout << std::endl; } } int main() { Node * root; insert(root, 4); insert(root, 2); insert(root, 6); insert(root, 1); insert(root, 3); insert(root, 5); insert(root, 7); levelOrder(root); return 0; }
1,577
C++
.cpp
86
13.313953
79
0.520594
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,837
lowest-common-ancestor.cpp
mandliya_algorithms_and_data_structures/tree_problems/lowest-common-ancestor.cpp
/** * Given a binary search tree, determine the lowest common ancestor of two given nodes with data * key1 and key2. Assumption is key1 and key2 exists in tree * Example * 20 * / \ * 8 22 * / \ * 4 12 * / \ * 10 14 * * In the above tree, LCA of 10 and 14 is 12 * similarly 4 and 22 will have LCA 20 */ #include <iostream> struct Node { int data; Node * left = nullptr; Node * right = nullptr; Node (int d) : data{ d }, left{ nullptr }, right{ nullptr } { } }; Node * lca ( Node * root, int key1, int key2 ) { if ( root == nullptr ) { return nullptr; } if (root->data > key1 && root->data > key2) { return lca(root->left, key1, key2); } else if ( root->data < key1 && root->data < key2 ) { return lca(root->right, key1, key2); } return root; } void inorder(Node * root) { if (root) { inorder(root->left); std::cout << root->data << " "; inorder(root->right); } } int main() { Node * root = new Node(20); root->right = new Node(22); root->left = new Node(8); root->left->left = new Node(4); root->left->right= new Node(12); root->left->right->right = new Node(14); root->left->right->left = new Node(10); std::cout << "Inorder traversal of the tree:"; inorder(root); std::cout << std::endl; std::cout << std::endl; std::cout << "LCA of nodes with data 10 and 14 is :" << (lca(root, 14, 10))->data << std::endl; std::cout << "LCA of nodes with data 14 and 8 is :" << (lca(root, 14, 8))->data << std::endl; std::cout << "LCA of root with data 4 and 22 is :" << (lca(root, 4, 22))->data << std::endl; std::cout << "LCA of root with data 14 and 10 is :" << (lca(root, 10, 14))->data << std::endl; return 0; }
1,851
C++
.cpp
65
24.969231
97
0.557055
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,838
closest_bst_value.cpp
mandliya_algorithms_and_data_structures/tree_problems/closest_bst_value.cpp
/* * Given a non-empty binary search tree and a target value, * find the value in the BST that is closest to the target. * Also, to note that the target value is a floating point. * There will be only one unique value which is closest to the target. */ #include <iostream> #include <limits> #include <cmath> struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int d): data{d}, left{nullptr}, right{nullptr}{} }; int closest_bst_value(TreeNode* root, double target) { // Tree is non-empty, so root is always valid. int curr_value = root->data; TreeNode* child = (target < curr_value) ? (root->left) : (root->right); if (!child) { return curr_value; } int child_value = closest_bst_value(child, target); return std::abs(curr_value - target) < std::abs(child_value- target) ? curr_value : child_value; } int closest_bst_value_iterative(TreeNode* root, double target) { int closest = root->data; while (root != nullptr) { if (std::abs(target - closest) >= std::abs(target - root->data)) { closest = root->data; } root = target < root->data ? root->left : root->right; } return closest; } void print_inorder(TreeNode* root) { if (root != nullptr) { print_inorder(root->left); std::cout << root->data << " "; print_inorder(root->right); } } int main() { TreeNode* root = new TreeNode(10); root->left = new TreeNode(5); root->right = new TreeNode(15); root->left->left = new TreeNode(2); root->left->right = new TreeNode(7); root->right->left = new TreeNode(12); root->right->right = new TreeNode(16); std::cout << "Inorder traversal of tree: "; print_inorder(root); std::cout << std::endl; std::cout << "Closest value from 3.6778 is :" << closest_bst_value(root, 3.6778) << std::endl; std::cout << "(Iterative) Closest value from 3.6778 is :" << closest_bst_value_iterative(root, 3.6778) << std::endl; return 0; }
2,070
C++
.cpp
66
26.681818
84
0.627825
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,839
sumTree.cpp
mandliya_algorithms_and_data_structures/tree_problems/sumTree.cpp
/** * Problem: Determine if a tree is sum tree. * A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree. * An empty tree is SumTree and sum of an empty tree can be considered as 0. * A leaf node is also considered as SumTree. * * 26 * / \ * 10 3 * / \ \ * 4 6 3 */ #include <iostream> struct Node { /* data */ int data; Node * left; Node * right; Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; /** * addTree - Adds the contents of the tree * @param root * @return total of contents of tree */ int addTree( Node * root ) { if ( root == nullptr ) { return 0; } return (addTree(root->left) + root->data + addTree(root->right)) ; } bool sumTree( Node * root ) { if ( root == nullptr ) { return true; } else if ( root->left == nullptr && root->right == nullptr ) { return true; } else { if ((addTree(root->left) + addTree(root->right) == root->data) && sumTree(root->left) && sumTree(root->right)) { return true; } else { return false; } } } void inorder(Node * root) { if ( root ) { inorder(root->left); std::cout << root->data << " "; inorder(root->right); } } int main() { /** * 26 * / \ * 10 3 * / \ \ * 4 6 3 */ Node * root = new Node(26); root->left = new Node(10); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(6); root->right->right = new Node(3); std::cout << "Inorder of the tree is :"; inorder(root); std::cout << std::endl; std::cout << "Is above tree sum-tree? : "; std::cout << ( sumTree(root) ? "Yes\n" : "No\n" ); return 0; }
1,836
C++
.cpp
79
20.21519
131
0.552511
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,841
floor_ceil_bst.cpp
mandliya_algorithms_and_data_structures/tree_problems/floor_ceil_bst.cpp
/* * Given a BST, find ceil and floor of a given key in it. If the given key lie in the BST, * then both floor and ceil is equal to that key, else ceil is equal to next greater key (if any) * in the BST and floor is equal to previous greater key (if any) in the BST. * source : techiedelight.com * *         8  *        /   \  *       /     \  *      4      10  *     / \     / \  *    /   \   /   \  *   2     6 9    12 * floor of 1 do not exist, ceil of 1 is 2 * floor of 3 is 2, ceil of 3 is 4 * floor of 9 is 9, ceil of 9 is 9 * floor of 7 is 6, ceil of 7 is 8 * * Approach: Search for the key in BST, every time we narrow down a subtree where key might belong, * We update the ceil if we choose left-subtree, and we update floor if choose right-subtree * If the key is not in the tree, we will have updated floor and ceil values. */ #include <iostream> struct TreeNode { int key; TreeNode* left; TreeNode* right; TreeNode (int d) : key {d} , left {nullptr} , right {nullptr}{} }; void insertNode(TreeNode* &root, int d) { if (!root) { TreeNode* newNode = new TreeNode(d); root = newNode; return; } if (root->key >= d) { insertNode(root->left, d); } else { insertNode(root->right, d); } } void findFloorCeil(TreeNode* root, int& floor, int& ceil, int key) { if (!root) { return; } if (root->key == key) { floor = ceil = key; } else if (key < root->key) { ceil = root->key; findFloorCeil(root->left, floor, ceil, key); } else { floor = root->key; findFloorCeil(root->right, floor, ceil, key); } } void inOrder(TreeNode* root) { if (root) { inOrder(root->left); std::cout << root->key << " "; inOrder(root->right); } } int main() { TreeNode* root = nullptr; insertNode(root, 8); insertNode(root, 4); insertNode(root, 10); insertNode(root, 2); insertNode(root, 6); insertNode(root, 9); insertNode(root, 12); std::cout << "InOrder traversal of the tree:\n"; inOrder(root); std::cout << std::endl; int keyToSearch = 3; int floor = -1; int ceil = -1; findFloorCeil(root, floor, ceil, keyToSearch); std::cout << "For key = "<< keyToSearch << " floor is " << floor << " and ceil is " << ceil << std::endl; keyToSearch = 9; // Reset floor and ceil floor = -1; ceil = -1; findFloorCeil(root, floor, ceil, keyToSearch); std::cout << "For key = "<< keyToSearch << " floor is " << floor << " and ceil is " << ceil << std::endl; return 0; }
2,934
C++
.cpp
108
20.537037
100
0.546228
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,842
verticalSum.cpp
mandliya_algorithms_and_data_structures/tree_problems/verticalSum.cpp
/** * Given a binary Tree * 1 * / \ * 2 3 * / \ / \ * 4 5 6 7 * * Find vertical sums of the tree. * Align the nodes in vertical line. * Here * The tree has 5 vertical lines * * Vertical-Line-1 has only one node 4 => vertical sum is 4 * Vertical-Line-2: has only one node 2=> vertical sum is 2 * Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12 * Vertical-Line-4: has only one node 3 => vertical sum is 3 * Vertical-Line-5: has only one node 7 => vertical sum is 7 * * So expected output is 4, 2, 12, 3 and 7 * */ #include <iostream> #include <unordered_map> #include <vector> #include <algorithm> #include <map> struct Node { int data; Node * left; Node * right; Node ( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { } }; void vertical_sum_util( Node * root, int dist, std::unordered_map<int,int> & vmap) { if ( root == nullptr ) { return ; } if ( vmap.find(dist) != vmap.end() ) { vmap[dist] += root->data; } else { vmap[dist] = root->data; } vertical_sum_util( root->left, dist-1, vmap); vertical_sum_util( root->right, dist+1, vmap); } void vertical_sum( Node * root ) { if ( root == nullptr ) { return; } std::unordered_map<int, int> vmap; vertical_sum_util( root, 0, vmap ); std::map<int, int> ordered( vmap.begin(), vmap.end()); std::cout << "Printing vertical sum values, first column represent the position of vertical column with respect to root(0)\n" << "and second column represent vertical sum for that column\n"; for ( auto it = ordered.begin(); it != ordered.end(); ++it ) { std::cout << it->first << " " << it->second << std::endl; } } int main() { Node * root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); vertical_sum(root); return 0; }
1,964
C++
.cpp
69
26.449275
126
0.628375
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,844
predecessorSuccessor.cpp
mandliya_algorithms_and_data_structures/tree_problems/predecessorSuccessor.cpp
/* * Goal : To find successor and predecessor ( if exists ) of a key in Binary Search Tree * */ #include <iostream> #include <generic.h> /* Node of the tree */ struct Node { int data; Node *left; Node *right; }; // Helper function to return a new node Node* newNode( const int & data ) { Node *node = new Node; node->data = data; node->left = node->right = nullptr; return node; } //insert to a binary tree void insert( Node * & node, const int & data ) { if ( node == nullptr ) { node = newNode(data); return; } if ( data < node->data ) { insert( node->left, data); } else { insert( node->right, data); } } // print inorder traversal of the tree void inorder( Node * node) { if ( node != nullptr ) { inorder(node->left); std::cout << node->data << " "; inorder(node->right); } } void predecessorSuccessor( Node *node, Node * &pred, Node * & succ, int key ) { if ( node == nullptr ) return; if ( node->data == key ) { if (node->left) { Node *temp = node->left; while (temp->right) temp = temp->right; pred = temp; } if (node->right) { Node * temp = node->right; while (temp->left) temp = temp->left; succ = temp; } } else if ( key < node->data ) { succ = node; predecessorSuccessor( node->left, pred, succ, key ); } else { pred = node; predecessorSuccessor( node->right, pred, succ, key ); } } int main() { Node * root = nullptr; int key = 20; for ( int i = 0; i < 10; ++i) { insert( root, algo::random_range(10, 40)); } Node *pred = nullptr, *succ = nullptr; //print the inorder of created tree std::cout << "Tree's inorder traversal:\n"; inorder(root); std::cout << "Finding predecessor and successor of key " << key << " (if exists):\n"; predecessorSuccessor(root, pred, succ, key); if (pred != nullptr ) { std::cout << "Predeccessor is " << pred->data << std::endl; } else { std::cout << "No predecessor\n"; } if (succ != nullptr) { std::cout << "Successor is " << succ->data << std::endl; } else { std::cout << "No successor\n"; } return 0; }
2,391
C++
.cpp
94
19.734043
89
0.539001
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,848
save_quantamland.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/save_quantamland.cpp
/** * In Quantumland, there are n cities numbered from 1 to n. Here, ci denotes the ith city. * There are n−1 roads in Quantumland. Here, ci and ci+1 have a bidirectional road between them for each i<n. * There is a rumor that Flatland is going to attack Quantumland, and the queen wants to keep her land safe. * The road between ci and ci+1 is safe if there is a guard in ci or ci+1. * The queen has already placed a few guards in some of the cities, * but she is not sure if they are enough to keep the roads safe. * She wants to know the minimum number of new guards she needs to hire. * * Input format: * The first line will contain an integer n. * In the next line, there will be n integers b1,b2...bn. * * If bi=1, that means there is a guard in city ci. * If bi=0, that means there are no guards in city ci. * * Example input * 5 * 1 1 0 1 0 * 5 * 0 0 1 0 0 * * Output: * 0 * 2 * */ #include <vector> #include <iostream> int min_guards_required(std::vector<int> & cities ) { int guardCount = 0; int unsafeRoads = 0; int n = cities.size(); if ( n == 1 ) { std::cout << guardCount << std::endl; return 0; } int i = 0; while ( i < n - 1 ) { unsafeRoads = 0; if (cities[i] == 0 && cities[i+1] == 0) { while(i < n-1 && cities[i] == 0 && cities[i+1] == 0) { ++unsafeRoads; ++i; } if ( unsafeRoads <= 2 ) { guardCount += 1; } else { if ( unsafeRoads % 2 ) { guardCount += (unsafeRoads/2) + 1; } else { guardCount += unsafeRoads/2; } } } ++i; } return guardCount; } int main() { int n; std::cin >> n; std::vector<int> cities(n); for(int i = 0; i < n; i++){ std::cin >> cities[i]; } std::cout << min_guards_required(cities) << std::endl; return 0; }
1,765
C++
.cpp
69
22.913043
111
0.632327
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,849
vigenere_cipher.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/vigenere_cipher.cpp
/** * Implements a program which encrypts and then decrypts text using Vigenère cipher. * The Vigenère cipher is a method of encrypting alphabetic text by using a series of interwoven Caesar ciphers based on the letters of a keyword. * Refer : https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher * * Enter the key for encrypting:bacon * Enter the plain text you want to encrypt:Meet me at the park at eleven am * Encrypted text: Negh zf av huf pcfx bt gzrwep oz * Decrypted text: Meet me at the park at eleven am */ #include <iostream> #include <string> #include <sstream> #include <cctype> std::string encrypt_data (std::string plain_text, std::string key) { std::stringstream encrypted_stream; unsigned int text_len = plain_text.length(); unsigned int key_len = key.length(); unsigned int char_index = 0; unsigned int shift_len = 0; for (unsigned int i = 0; i < text_len; ++i) { if (isalpha(plain_text[i])) { // If current key char is uppercase, keyReferenceValue would be 'A', otherwise 'a' // We use keyReferenceValue to convert key char to ascii // char keyReferenceValue = (isupper(key[char_index % key_len])) ? 'A' : 'a'; // Similarly, we use referenceValue to convert plain text char to ascii, it would // char referenceValue = (isupper(plain_text[i])) ? 'A' : 'a'; shift_len = key[char_index % key_len] - keyReferenceValue; encrypted_stream << char(((plain_text[i] - referenceValue + shift_len) % 26) + referenceValue); ++char_index; } else { // for non alpha chars, we don't encrypt and keep them as it is. encrypted_stream << plain_text[i]; } } return encrypted_stream.str(); } std::string decrypt_data(std::string encrypted_text, std::string key) { std::stringstream decrypted_stream; unsigned int text_len = encrypted_text.length(); unsigned int key_len = key.length(); unsigned int char_index = 0; unsigned int shift_len = 0; for (unsigned int i = 0; i < text_len; ++i) { if (isalpha(encrypted_text[i])) { // If current key char is uppercase, keyReferenceValue would be 'A', otherwise 'a' // We use keyReferenceValue to convert key char to ascii // char keyReferenceValue = (isupper(key[char_index % key_len])) ? 'A' : 'a'; // Similarly, we use referenceValue to convert plain text char to ascii, it would // char referenceValue = (isupper(encrypted_text[i])) ? 'A' : 'a'; shift_len = key[char_index % key_len] - keyReferenceValue; decrypted_stream << char((((encrypted_text[i] - referenceValue) + (26 - shift_len)) % 26) + referenceValue); ++char_index; } else { // We don't encrypt non-alpha chars, so keeping them as it is. decrypted_stream << encrypted_text[i]; } } return decrypted_stream.str(); } int main() { std::string plain_text, encrypted_text; std::string key; std::cout << "Enter the key for encrypting:"; std::cin >> key; std::cin.clear(); std::cin.sync(); std::cin.ignore(); std::cout << "Enter the plain text you want to encrypt:"; std::getline(std::cin, plain_text); encrypted_text = encrypt_data(plain_text, key); std::cout << "Encrypted text: " << encrypted_text << std::endl; plain_text.clear(); plain_text = decrypt_data(encrypted_text, key); std::cout << "Decrypted text: " << plain_text << std::endl; return 0; }
3,707
C++
.cpp
92
33.23913
146
0.620959
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,850
rotate_matrix.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/rotate_matrix.cpp
/** * Given a 2D matrix, a, of dimension MxN and a positive integer R. * You have to rotate the matrix R times and print the resultant matrix. * Rotation should be in anti-clockwise direction. * * Input : First line contains M (number of rows of matrix), N (number of columns in matrix) * and R (Number of rotations to be performed).Then M x N matrix is expected. * Ouput : Matrix after R rotations. * * Example : * Input : * 5 4 7 * 1 2 3 4 * 7 8 9 10 * 13 14 15 16 * 19 20 21 22 * 25 26 27 28 * Output : * 28 27 26 25 * 22 9 15 19 * 16 8 21 13 * 10 14 20 7 * 4 3 2 1 * * Approach : * Accumulate each bordering rectangle in a vector, shift it R rotations and copy it back to matrix. * Keep doing for all levels till we have reached the center of matrix. */ #include <vector> #include <iostream> using namespace std; void rotateLeftSingle(vector<int>& vec) { int first = vec[0]; for ( unsigned int i = 0; i < vec.size()-1; ++i) { vec[i] = vec[i+1]; } vec[vec.size() - 1] = first; } void rotate(vector<int> & vec, long r) { r = r % vec.size(); for ( int i = 0; i < r; ++i) { rotateLeftSingle(vec); } } int main() { long M, N, R; cin >> M >> N >> R; int ** matrix = new int*[M]; for ( int i = 0; i < M; ++i) { matrix[i] = new int[N]; } for ( int i = 0; i < M; ++i) { for ( int j = 0; j < N; ++j) { cin >> matrix[i][j]; } } int a = 0, b = N-1, c = M-1, d = 0; int al,bl,cl,dl; while( a < c && d < b ) { vector<int> currLevel; al = a; bl = b; cl = c; dl = d; for ( int j = d; j <= b; ++j ) { currLevel.push_back(matrix[a][j]); } ++a; for ( int i = a; i <= c; ++i) { currLevel.push_back(matrix[i][b]); } --b; for ( int j = b; j >= d; --j) { currLevel.push_back(matrix[c][j]); } --c; for ( int i = c; i >= a; --i ) { currLevel.push_back(matrix[i][d]); } ++d; rotate(currLevel, R); int k = 0; for ( int j = dl; j <= bl; ++j ) { matrix[al][j] = currLevel[k]; ++k; } ++al; for ( int i = al; i <= cl; ++i) { matrix[i][bl] = currLevel[k]; ++k; } --bl; for ( int j = bl; j >= dl; --j) { matrix[cl][j] = currLevel[k]; ++k; } --cl; for ( int i = cl; i >= al; --i) { matrix[i][dl] = currLevel[k]; ++k; } ++dl; } for ( int i = 0; i < M; ++i) { for ( int j = 0; j < N; ++j) { cout << matrix[i][j] << " "; } cout << endl; } return 0; }
2,888
C++
.cpp
112
19.4375
101
0.449783
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,852
findDigits.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/findDigits.cpp
/** * You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. * For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2. * * Note * * If the same number is repeated twice at different positions, it should be counted twice, * e.g., For N=122, 2 divides 122 exactly and occurs at ones' and tens' position. So for this case, our answer is 3. * Division by 0 is undefined. * * * Input Format * The first line contains T (the number of test cases), followed by T lines (each containing an integer N). * * Constraints * 1≤T≤15 * 0<N<1010 * Output Format * * For each test case, display the count of digits in N that exactly divide N in a separate line. * * Sample Input * * 2 * 12 * 1012 * * Sample Output * 2 * 3 */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int T, num; cin >> T; for (int t = 0; t < T; ++t) { cin >> num; int c = 0, d =0; int x = num; while(x > 0) { d = x % 10; if ( d != 0 && num % d == 0) { ++c; } x = x/10; } cout << c << endl; } return 0; }
1,342
C++
.cpp
55
20.309091
146
0.602033
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,853
n_binary.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/n_binary.cpp
/* * Generate numbers between 1 to N, in binary using a data-structure. */ #include <iostream> #include <string> #include <queue> void print_n_binary(int n) { std::queue<std::string> q; q.push("1"); int i = 1; while (i++ <= n) { // append 0 and 1 to the existing binary string. // q.push(q.front() + "0"); q.push(q.front() + "1"); std::cout << q.front() << std::endl; q.pop(); } } int main() { int n; std::cout << "Enter number n:"; std::cin >> n; print_n_binary(n); return 0; }
611
C++
.cpp
29
15.551724
70
0.505226
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,854
power_function.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/power_function.cpp
/* * Implement pow(a, b) function. * We can recursively call a sub-problem * if n is even, then pow(a,b) = pow(a, b/2) * pow(a, b/2); * if n is odd then, pow(a, b) = a * pow(a, b/2) * pow(a, b/2); */ #include <iostream> int power(int a, int b) { // base condition // if (b == 0) { return 1; } // sub-problem for this recursive call. // int p = power(a, b/2); // if b is odd if (b & 1) { return (a * p * p); } else { // if b is even return (p * p); } } int main() { int a, b; std::cout << "Calculating pow(a,b):\n"; std::cout << "Enter a:"; std::cin >> a; std::cout << "Enter b:"; std::cin >> b; std::cout << "pow(a,b) :" << power(a, b) << std::endl; }
829
C++
.cpp
39
15.717949
64
0.455013
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,855
caeser_cipher.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/caeser_cipher.cpp
/* * Encrypts a plain text to decrypts an encrypted text back to plain using Caeser Cipher. * It is a type of substitution cipher in which each letter in the plaintext is replaced by a * letter some fixed number of positions down the alphabet. For example, with a left shift of 3, * D would be replaced by A, E would become B, and so on. * The method is named after Julius Caesar, who used it in his private correspondence * * Enter plain text:the brown fox jumped over the lazy dog * Enter shift length:24 * Encrypted text:rfc zpmul dmv hskncb mtcp rfc jyxw bme * Decrypted text:the brown fox jumped over the lazy dog. */ #include <iostream> #include <string> #include <sstream> char caeser_encrypt(char c, int shift_length); char caeser_decrypt(char c, int shift_length); int main() { std::string plain_text, encrypted_text; int shift_length; std::cout << "Enter plain text:"; std::getline(std::cin, plain_text); std::cout << "Enter shift length:"; std::cin >> shift_length; std::stringstream ss; unsigned int text_length = plain_text.length(); // Encrypt the text // for (unsigned int i = 0; i < text_length; ++i) { ss << caeser_encrypt(plain_text[i], shift_length); } encrypted_text = ss.str(); std::cout << "Encrypted text:" << encrypted_text << std::endl; // Reset the stream // ss.str(std::string()); // Decrypt the text again // for (unsigned int i = 0; i < text_length; ++i) { ss << caeser_decrypt(encrypted_text[i], shift_length); } std::cout << "Decrypted text:" << ss.str() << std::endl; return 0; } // Encrypts a character based on shift length // char caeser_encrypt(char c, int shift_length) { if (c >= 'A' && c <= 'Z') { return (((c - 'A' + shift_length) % 26) + 'A'); } else if (c >= 'a' && c <= 'z') { return (((c - 'a' + shift_length) % 26) + 'a'); } // In case of non-alpha characters, return as it is. return c; } // Decrypts a character based on shift length // char caeser_decrypt(char c, int shift_length) { if (c >= 'A' && c <= 'Z') { return (((c - 'A' + (26 - shift_length)) % 26) + 'A'); } else if (c >= 'a' && c <= 'z') { return (((c - 'a' + (26 - shift_length)) % 26) + 'a'); } // In case of non-alpha characters, return as it is. return c; }
2,510
C++
.cpp
77
27.207792
97
0.59666
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,857
matrix_spiral_print.cpp
mandliya_algorithms_and_data_structures/common_ds_algo_problems/matrix_spiral_print.cpp
/** * Given a m * n matrix, print the contents of it spiral way. for example. * Matrix is : * 1 2 3 4 5 * 6 7 8 9 10 * 11 12 13 14 15 * 16 17 18 19 20 * Sprial order print would * 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 */ #include <iostream> void spiral_print_matrix( int ** matrix, int m, int n) { int a = 0, b = n-1, c = m-1, d = 0; while( a < c && d < b) { for(int i = d; i <= b; ++i ) { std::cout << matrix[a][i] << " "; } ++a; for( int j = a; j <= c; ++j ) { std::cout << matrix[j][b] << " "; } --b; for( int i = b; i >= d; --i ) { std::cout << matrix[c][i] << " "; } --c; for( int j = c; j >= a; --j) { std::cout << matrix[j][d] << " "; } ++d; } std::cout << std::endl; } int main() { int m, n; std::cout << "Enter num of rows :" ; std::cin >> m; std::cout << "Enter num of columns : "; std::cin >> n; int ** matrix = new int*[m]; for ( int i = 0; i < m; ++i ) { matrix[i] = new int[n]; } std::cout << "Enter content of matrix of size " << m << " * " << n << " :"; for( int i = 0; i < m; ++i ) { for( int j = 0; j < n; ++j ) { std::cin >> matrix[i][j]; } } std::cout << "Printing content of above matrix in spiral order:\n"; spiral_print_matrix(matrix, m, n); return 0; }
1,381
C++
.cpp
56
20.821429
75
0.459726
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,858
max_subsequence.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/max_subsequence.cpp
/** * Maximum Value Contiguous Subsequence * Given an array of n numbers, give an algorithm for finding a contigous * subsequence A(i)...A(j) for which the sum of elements is maximum. * Example - { -2, 11, -4, 13, -5, 2} --> 20 i.e. { 11, -4, 13} * Example - { 1, -3, 4, -2, -1, 6} --> 7 { 4, -2, -1, 6} * * Approach : * For selecting an ith element, we have to make a decision * - Add it to the old sum M(i-1) + A[i] * - or start the new window with one element A[i] * * We will use above approach in solving it with O(n) space and with O(1) space (Kadane's approach). * Special Case: * If all the elements are positive then, we the Maximum Value Contigous Subsequence would be the entire set * */ #include <iostream> #include <vector> #include <algorithm> #include <limits> //approach one using O(n) space. int max_contigous_subsequence_sum( const std::vector<int> & v ) { //special case when all the elements are negative. bool allNegativeOrZero = true; int maxSum = std::numeric_limits<int>::min(); for ( size_t i = 0; i < v.size(); ++i ) { if ( v[i] > 0 ) { allNegativeOrZero = false; } if (v[i] > maxSum) { maxSum = v[i]; } } if (allNegativeOrZero) { return maxSum; } maxSum = 0; std::vector<int> M(v.size(), 0); if (v[0] > 0) { M[0] = v[0]; } for (size_t i = 1; i < v.size(); ++i) { if ( M[i-1] + v[i] > 0 ) { M[i] = M[i-1] + v[i]; } else { M[i] = 0; } } for ( size_t i = 0; i < v.size(); ++i ) { if (M[i] > maxSum) { maxSum = M[i]; } } return maxSum; } //approach two // Kadane's algorithm. // Since we care about sum till i-1 for calculating i // and we need to pick the maximum of all the sums eventully, // We don't really need an array to store sums. // We have to take care of special case when array contains only negative nums. int max_contigous_subsequence_sum2( std::vector<int> & v ) { int max_so_far = std::numeric_limits<int>::min(); int sum_so_far = 0; //special case all negative or zero bool allNegativeOrZero = true; for ( size_t i = 0; i < v.size(); ++i ) { if ( v[i] > 0 ) { allNegativeOrZero = false; } if ( v[i] > max_so_far ) { max_so_far = v[i]; } } if (allNegativeOrZero) { return max_so_far; } //case 2 normal case; max_so_far = 0; for ( size_t i = 0; i < v.size(); ++i ) { sum_so_far += v[i]; if ( sum_so_far < 0 ) { sum_so_far = 0; } if ( max_so_far < sum_so_far ) { max_so_far = sum_so_far; } } return max_so_far; } void printVec(const std::vector<int> & vec) { for(auto x : vec) { std::cout << x << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{ -2, 11, -4, 13, -5, 2}; std::cout << "Vector: "; printVec(vec); std::cout << "Sum of Maximum Contiguous Subarray for above vector is : " << max_contigous_subsequence_sum(vec) << std::endl; std::vector<int> vec1{ -2, -1, -4, -3, -5, -2}; std::cout << " Special Vector: "; printVec(vec1); std::cout << "Sum of Maximum Contiguous Subarray for above vector is : " << max_contigous_subsequence_sum(vec1) << std::endl; std::vector<int> vec2{ -200, -100, -50, -70, -500, -51}; std::cout << " Special Vector: "; printVec(vec2); std::cout << "Sum of Maximum Contiguous Subarray for above vector is : " << max_contigous_subsequence_sum(vec2) << std::endl; std::vector<int> vec3{ 1, -3, 4, -2, -1, 6 }; std::cout << "Vector: "; printVec(vec3); std::cout << "Sum of Maximum Contiguous Subarray for above vector is : " << max_contigous_subsequence_sum(vec3) << std::endl; return 0; }
3,700
C++
.cpp
121
26.933884
108
0.59332
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,859
lcs.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/lcs.cpp
/** * Given two strings X(1..m) and Y(1..n). Find the longest common substring * that appears left to right (but not necessarily in a contiguous manner) * in both strings. For example X = "ABCBDAB" and Y = "BDCABA" * LCS(X,Y) = {"BCBA", "BDAB", "BCAB"}. * LCS-LENGTH(X,Y) = 4 */ #include <iostream> #include <string> #include <vector> size_t max( size_t a, size_t b ) { return a > b ? a : b; } size_t max(size_t a, size_t b, size_t c) { return (max(a,b) > c ) ? max(a,b) : c ; } void longest_common_subsequence(std::vector<std::vector<size_t>> & lcs, std::string s1, std::string s2) { size_t m = s1.length(); size_t n = s2.length(); for ( size_t j = 0; j <= n; ++j ) { lcs[0][j] = 0; } for ( size_t i = 0; i <= m; ++i ) { lcs[i][0] = 0; } for( size_t i = 0; i < m; ++i ) { for( size_t j = 0; j < n; ++j ) { lcs[i+1][j+1] = lcs[i][j]; //getting previous max val if (s1[i] == s2[j]) { lcs[i+1][j+1]++; } else { lcs[i+1][j+1] = max(lcs[i][j+1], lcs[i+1][j]); } } } std::cout << "Longest common subsequence length - " << lcs[m][n] << std::endl; size_t i = m; size_t j = n; size_t index = lcs[m][n]; std::string seq(lcs[m][n], ' '); while( i > 0 && j > 0 ) { if ( s1[i-1] == s2[j-1] ) { seq[index -1 ] = s1[i-1]; --index; --i; --j; } else if ( lcs[i-1][j] > lcs[i][j-1] ) { --i; } else { --j; } } std::cout << "One of possible many Longest Common Subsequence is : " << seq << std::endl; } int main() { std::string str1, str2; std::cout << "Longest common subsequence Problem:\n"; std::cout << "Enter string 1:"; std::cin >> str1; std::cout << "Enter string 2:"; std::cin >> str2; std::vector<std::vector<size_t>> lcs( str1.length() + 1, std::vector<size_t>(str2.length() + 1)); longest_common_subsequence(lcs, str1, str2); return 0; }
1,837
C++
.cpp
68
24.455882
98
0.559932
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,860
0_1_knapsack_problem.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/0_1_knapsack_problem.cpp
/* * 0-1 Knapsack Problem: Imagine you are a thief and you want to steal things from room full of things. * You have a knapsack which can handle maximum capacity of weight W, and you want to fill it up such * that it's worth is maximum. Being an intelligent thief, you know weights and values of each item in the room. * How would you fill your knapsack, such that you get the maximum possible value for your knapsack of capacity W. * * The problem essentially boils down to whether item i would be part of your loot or not. * This has optimal substructure: * case 1: Item I is in your loot: * Then the maximum value of the loot is determined by remaining n-1 items whose possible weight would be * W-(weight of Item I) * * case 2: Item I is not in your loot: * Then the maximum value of the loot is determined by remaining n-1 items whose possible weight would be * W. (i.e excluding the ith item) * * We could get all subsets of possible items in the loot, and choose the one with maximum value. * * Since this problem will have overlapping subproblems, we could use dynamic programming to solve it. * So that we don't recurse to calculate the same subproblem which we have already calculated. * */ #include <iostream> #include <vector> int maximum_possible_loot_value(const std::vector<int>& weights, const std::vector<int>& values, const int capacity) { int items_count = values.size(); std::vector<std::vector<int>> loots(items_count + 1, std::vector<int>(capacity + 1)); for (int i = 0; i <= items_count; ++i) { for (int w = 0; w <= capacity; ++w) { if (i == 0 || w == 0) { loots[i][w] = 0; } else if (weights[i-1] <= w) { loots[i][w] = std::max(values[i-1] + loots[i-1][w-weights[i-1]], loots[i-1][w]); } else { loots[i][w] = loots[i-1][w]; } } } return loots[items_count][capacity]; } void print_vector(const std::vector<int>& vec) { for (auto v : vec) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> values{40, 10, 90}; std::vector<int> weights{20, 40, 60}; int capacity = 100; std::cout << "Weights of items: "; print_vector(weights); std::cout << "Values of items: "; print_vector(values); std::cout << "Capacity :" << capacity << std::endl; std::cout << "Maximum possible loot value for capacity " << capacity << ": " << maximum_possible_loot_value(weights, values, capacity) << std::endl; return 0; }
2,598
C++
.cpp
63
36.31746
114
0.642829
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,861
fibonacci.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/fibonacci.cpp
/** * Calculating Fibonacci series term of index N using DP memoization. */ #include <iostream> #include <vector> //bottom up int fib1(int n) { std::vector<int> fib(n, 0); if ( n == 0 || n == 1 ) { return 1; } fib[0] = 1; fib[1] = 1; for ( int i = 2; i < n; ++i ) { fib[i] = fib[i-1] + fib[i-2]; } return fib[n-1]; } //top down std::vector<int> fib(1000, 0); int fib2( int n ) { if ( n == 0 ) { return 0; } if ( n == 1 || n == 2 ) { return 1; } if ( fib[n] != 0 ) { return fib[n]; } fib[n] = fib2(n-1) + fib2(n-2); return fib[n]; } //leverage the fact we are just using last 2 term int fib3( int n ) { int a = 0; int b = 1; for ( int i = 2; i <= n; ++i ) { int c = a + b; a = b; b = c; } return b; } int main() { std::cout << "Demonstrating fibonacci term calculation:\n"; std::cout << fib1(9) << " " << fib2(9) << " " << fib3(9) << std::endl; return 0; }
907
C++
.cpp
50
16.14
71
0.540636
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,862
unique_paths.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/unique_paths.cpp
/* * Level : Easy * Given a grid, calculate the maximum number of unique paths * from source (0,0) to destination (m, n). You can only move * either in down or in right direction. * * S . . . . . . . . * . . . . . . . . . * . . . . . . . . . * . . . . . . . . . * . . . . . . . . . * . . . . . . . . D * * In this 6 x 9 grid, * unique paths from source origin to destination are 1287. * */ #include <iostream> #include <vector> int unique_paths(int m, int n) { std::vector<std::vector<int>> paths(m, std::vector<int>(n)); for (int i = 0; i < m; ++i) { paths[i][0] = 1; } for (int j = 0; j < n; ++j) { paths[0][j] = 1; } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { paths[i][j] = paths[i-1][j] + paths[i][j-1]; } } return paths[m-1][n-1]; } int main() { std::cout << "Number of unique paths for 6 x 9 grid: " << unique_paths(6, 9) << std::endl; return 0; }
993
C++
.cpp
41
20.390244
64
0.472574
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,863
catalan_number.cpp
mandliya_algorithms_and_data_structures/dynamic_programming_problems/catalan_number.cpp
/** * Dynamic Programming problem * Catalan number - How many binary search trees are possible with n keys. * n = 1 , num of BST - 1 * n = 2 , num of BST - 2 * * 2 1 * / and \ * 1 2 * * n = 3, num of BST - 5 * * 3 1 2 2 3 * / \ / \ \ / * 2 and 2 and 1 3 and 3 and 1 * / \ / \ * 1 3 1 2 * * So, If we choose, ith element as root, there will be i-1 elements on the * left subtree and n-i on the right. The two side subtrees would be independent * of each other. Therefore we can say. * C(i) = C(i-1) * C(n-i) * Since there will be many subproblems, which will overlap, we can use dynamic * programming. */ #include <iostream> #include <vector> // calculating catalan number using DP, Time complexity O(n^2) int catalan_number( int n ) { std::vector<int> table(n+1); table[0] = table[1] = 1; for ( int i = 2; i <= n; ++i ) { table[i] = 0; for ( int j = 0; j < i; ++j ) { table[i] += ( table[j] * table[i - j - 1] ); } } return table[n]; } int main() { int n; std::cout << "Enter a number : "; std::cin >> n; std::cout << "Number of possible Binary Search Trees for " << n << " is " << catalan_number(n) << std::endl; return 0; }
1,583
C++
.cpp
48
30.354167
80
0.440235
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,864
primsMST.cpp
mandliya_algorithms_and_data_structures/graph_problems/primsMST.cpp
/** * Minimum spanning tree using Prim's algorithm. * Approach greedy * Calculate the weight of minimum spanning tree(sum of weight of edges of MST) * and print the edges which makes MST. * Input format: * ROW 1 :: V - number of vertices, E - number of Edges. * Next E lines give details of each edge in format x y w. * where x is start of edge, y is end of edge and w is weight of xy edge * After that, S - Index of the starting point of finding the MST. * all the input is not 0 indexed. */ #include <iostream> #include <limits> const int MIN = std::numeric_limits<int>::min(); const int MAX = std::numeric_limits<int>::max(); /** * Print the Minimum spanning tree */ void printMST( int ** graph, int * MST, int V ) { std::cout << " Edge Weight \n"; for ( int v = 0; v < V; ++v ) { if (MST[v] != -1 && graph[v][MST[v]] != -1 ) { std::cout << v+1 << "<-->" << MST[v]+1 << " " << graph[v][MST[v]] << std::endl; } } } /** * minKey * returns the index of the vertex which is not yet part of MST * and has minimum key. */ int minKey( int * keys, bool * inMST, int V ) { int min = MAX, minIndex; for ( int v = 0; v < V; ++v ) { if ( inMST[v] == false && min > keys[v] ) { minIndex = v; min = keys[v]; } } return minIndex; } /** * primsMSTWeight * returns the weight of the minimum spanning tree of the graph * Args: * graph: adjacency matrix of the graph * V : Total number of vertices in the graph * S : Starting index of MST */ int primsMSTWeight( int ** graph, int V, int S, int * MST) { int * key = new int[V]; bool * inMST = new bool[V]; for ( int v = 0; v < V; ++v ) { inMST[v] = false; key[v] = MAX; } key[S] = 0; for ( int count = 0; count < V-1; ++count ) { int u = minKey(key, inMST, V); inMST[u] = true; for ( int v = 0; v < V; ++v ) { if ( (graph[u][v] != -1) && (inMST[v] == false) && (key[v] > graph[u][v]) ) { key[v] = graph[u][v]; MST[v] = u; } } } int sum = 0; for ( int v = 0 ;v < V; ++v ) { if ( MST[V] != -1 && graph[v][MST[v]] != -1 ) { sum += graph[v][MST[v]]; } } delete[] key; delete[] inMST; return sum; } int main() { int V, E, x, y, w, S; /** * V -- number of vertices * E -- number of edges * xy-- edge with endpoints x and y * w -- weight of edge * S -- Starting index */ std::cin >> V >> E; int ** graph = new int*[V]; for ( int v = 0; v < V; ++v ) { graph[v] = new int[V]; for ( int w = 0; w < V; ++w ) { graph[v][w] = -1; } } for ( int i = 0; i < E; ++i ) { std::cin >> x >> y >> w; if ( graph[x-1][y-1] == -1 || ( (graph[x-1][y-1] > 0) && (graph[x-1][y-1] > w ))) { graph[x-1][y-1] = w; graph[y-1][x-1] = w; } } std::cin >> S; int * MST = new int[V]; MST[S-1] = -1; std::cout << "Min Spanning tree weight " << primsMSTWeight(graph, V, S-1, MST) << std::endl; std::cout << "Min Spanning tree:\n"; printMST(graph, MST, V); return 0; }
2,938
C++
.cpp
113
23.539823
93
0.560584
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,866
flood_fill.cpp
mandliya_algorithms_and_data_structures/graph_problems/flood_fill.cpp
/* * Given a 2D screen, location of the pixel and new value of the color to fill, replace the color of the * pixel and all the adjacent(up, below, left, right) same colored pixel with new color. * * This is same as flood fill (remember the bucket symbol) a region in MS-PAINT. * * [[1 1 1 2 2 1 1] * [1 1 1 2 1 1 1] * [1 2 2 2 1 3 3] * [4 4 1 2 7 9 9]] * * The screen is 0-indexed. * Start at pixel (1, 3) and replace color 2 with color 5, in this pixel and all the adjacent same * color pixels. * * Therefore, the answer would be: * [[1 1 1 5 5 1 1] * [1 1 1 5 1 1 1] * [1 5 5 5 1 3 3] * [4 4 1 5 7 9 9]] * * Approach: Use the simple depth first search to search adjacent pixels of same color * and mark them with new color. */ #include <iostream> #include <vector> bool is_valid(int grid_height, int grid_width, int sr, int sc) { return (sr >= 0 && sr < grid_height && sc >= 0 && sc < grid_width); } void flood_fill_helper(std::vector<std::vector<int>>& image, int sr, int sc, int new_color, int old_color) { if (!is_valid(image.size(), image[0].size(), sr, sc)) { return; } if (image[sr][sc] != old_color) { return; } image[sr][sc] = new_color; flood_fill_helper(image, sr - 1, sc, new_color, old_color); flood_fill_helper(image, sr + 1, sc, new_color, old_color); flood_fill_helper(image, sr, sc - 1, new_color, old_color); flood_fill_helper(image, sr, sc + 1, new_color, old_color); } std::vector<std::vector<int>> flood_fill(std::vector<std::vector<int>>& image, int sr, int sc, int new_color) { if (image[sr][sc] != new_color) { int old_color = image[sr][sc]; flood_fill_helper(image, sr, sc, new_color, old_color); } return image; } void print_image(const std::vector<std::vector<int>>& image) { for (auto row : image) { for (auto pixel : row) { std::cout << pixel << " "; } std::cout << std::endl; } } int main() { std::vector<std::vector<int>> image = { {1, 1, 1, 2, 2, 1, 1}, {1, 1, 1, 2, 1, 1, 1}, {1, 2, 2, 2, 1, 3, 3}, {4, 4, 1, 2, 7, 9, 9} }; std::cout << "Current Image:" << std::endl; print_image(image); std::cout << "Applying flood fill at pixel (1,3) to change color to 5:" << std::endl; image = flood_fill(image, 1, 3, 5); print_image(image); return 0; }
2,419
C++
.cpp
75
28.093333
109
0.590501
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,867
grid_word_search.cpp
mandliya_algorithms_and_data_structures/graph_problems/grid_word_search.cpp
/* * Search a given word in a 2D board containing letters. * The word can be constructed by sequentially traversing adjacent * horizontal or vertical cells. In a sequence to form word, * letter on same position can not be used more than once. * * Example: * Input: * * ['H' 'E' 'Y' 'A'] * ['O' 'L' 'A' 'Y'] * ['I' 'L' 'O' 'V'] * * Word: HELLO * Output: Yes/true * * Word: YELL * Output: Yes/true * * Word: LOVE * Output: No/false * * Assumption: grid or word does not contain '$' char * * Approach: We can use Depth First Search with backtracking to solve this. * We can search the grid to match the first letter of search word * in the grid, and then apply depth first search on the grid at that position. * Finding appropriate next characters in the search word at each depth while * searching sequentially in the four directions. * * We need some way to mark a position in grid as already visited. I will use * '$' to mark the position as visited, and we will reset the letter at the * position back to original letter at the end of backtracking. * */ #include <iostream> #include <vector> #include <iomanip> bool depth_first_search(std::vector<std::vector<char>>& grid, const std::string& word, int r, int c, int index) { if (index == word.size()) { return true; } int rows = grid.size(); int cols = grid[0].size(); if (r < 0 || r >= rows || c < 0 || c >= cols) { return false; } if (word[index] != grid[r][c]) { return false; } char cur = grid[r][c]; grid[r][c] = '$'; bool result = false; result = depth_first_search(grid, word, r - 1, c, index + 1) || depth_first_search(grid, word, r + 1, c, index + 1) || depth_first_search(grid, word, r, c - 1, index + 1) || depth_first_search(grid, word, r, c + 1, index + 1); grid[r][c] = cur; return result; } bool grid_search(std::vector<std::vector<char>>& grid, const std::string& word) { int rows = grid.size(); int cols = grid[0].size(); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (word[0] == grid[i][j]) { if (depth_first_search(grid, word, i, j, 0)) { return true; } } } } return false; } void print_grid(const std::vector<std::vector<char>>& grid) { for (auto vec : grid) { std::cout << "{ "; for (auto c : vec) { std::cout << c << " "; } std::cout << "}" << std::endl; } } int main() { std::vector<std::vector<char>> grid{ {'H', 'E', 'Y', 'A'}, {'O', 'L', 'A', 'Y'}, {'I', 'L', 'O', 'V'} }; print_grid(grid); std::cout << std::boolalpha; std::cout << "Does word 'HELLO' exist in grid? "; bool result = grid_search(grid, "HELLO"); std::cout << result << std::endl; std::cout << "Does word 'HELL' exist in grid? "; result = grid_search(grid, "HELL"); std::cout << result << std::endl; std::cout << "Does word 'LOVE' exist in grid? "; result = grid_search(grid, "LOVE"); std::cout << result << std::endl; std::vector<std::vector<char>> grid2 { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }; print_grid(grid2); std::cout << "Does word 'SEE' exist in grid? "; result = grid_search(grid2, "SEE"); std::cout << result << std::endl; std::cout << "Does word 'ABCCSE' exist in grid? "; result = grid_search(grid2, "ABCCSE"); std::cout << result << std::endl; std::cout << "Does word 'ABDE' exist in grid? "; result = grid_search(grid2, "ABDE"); std::cout << result << std::endl; return 0; }
3,757
C++
.cpp
122
25.844262
86
0.565386
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,868
kruskalMST.cpp
mandliya_algorithms_and_data_structures/graph_problems/kruskalMST.cpp
/** * Given an undirected weighted connected graph, it is required to find the Really Special SubTree in it. * The Really Special SubTree is defined as a subgraph consisting of all the nodes in the graph and * There is only one exclusive path from a node to every other node. * The subgraph is of minimum overall weight (sum of all edges) among all such subgraphs. * While creating the Really Special SubTree, start of by picking the edge with smallest weight. * If there are edges of equal weight available at an instant, then the edge to be chosen first among them is the * one with minimum value of sum of the following expression : * u + wt + v , where u and v are the node numbers of the corresponding edge and wt is the weight. * Even then if there is a collision, choose any one of them. * While doing the above, ensure that no cycle is formed while picking up edges. */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; struct Edge { int x; int y; int r; Edge( int a, int b, int c) : x{ a-1 }, y{ b-1 }, r{ c } { } }; bool sortComparer( Edge a, Edge b ) { if ( a.r < b.r ) { return true; } else if ( a.r > b.r ) { return false; } return ( a.x + a.y + a.r <= b.x + b.y + b.r); } class Graph { public: Graph(int N, int M) : V{ N }, E{ M }, edges(E, Edge(0,0,0)) { } void getEdges(); void sortEdges(); int numberOfVertices() { return V; } int numberOfEdges() { return E; } std::vector<Edge> kruskalMST(); private: int V; //number of vertices int E; //number of Edges std::vector<Edge> edges; }; void Graph::getEdges( ) { int x, y, r; for ( int i = 0; i < E; ++i ) { std::cin >> x >> y >> r; edges.push_back(Edge(x, y, r)); } } void Graph::sortEdges() { std::sort(edges.begin(), edges.end(), sortComparer); } struct subset { int rank; int parent; }; int find( std::vector<subset> & subsets, int i ) { if ( subsets[i].parent != i ) { subsets[i].parent = find(subsets, subsets[i].parent); } return subsets[i].parent; } void union_edges( std::vector<subset> & subsets, int a, int b) { int aroot = find(subsets, a); int broot = find(subsets, b); if ( subsets[aroot].rank < subsets[broot].rank ) { subsets[aroot].parent = broot; } else if ( subsets[aroot].rank > subsets[broot].rank ) { subsets[broot].parent = aroot; } else { subsets[broot].parent = aroot; subsets[broot].rank++; } } std::vector<Edge> Graph::kruskalMST() { sortEdges(); std::vector<subset> subsets(numberOfEdges()); for ( int i = 0; i < numberOfEdges(); ++i ) { subsets[i].rank = 0; subsets[i].parent = i; } int e = 0; int i = 0; std::vector<Edge> resultMST; while ( e < numberOfVertices() - 1) { Edge next_edge = edges[i++]; int a = find( subsets, next_edge.x ); int b = find( subsets, next_edge.y ); if ( a != b ) { resultMST.push_back(next_edge); union_edges(subsets, a, b); ++e; } } return resultMST; } void printMST(std::vector<Edge> & MST) { std::cout << std::endl << "Given Graph's MST:\n"; std::cout << "V1\tV2\tWeight\n"; for ( auto e : MST ) { std::cout << e.x + 1 << "\t" << e.y + 1 << "\t" << e.r << std::endl; } std::cout << std::endl; } void inputFormat() { std::cout << "Input Format:\nFirst line has two integers N, denoting the number of nodes in the graph and M," "denoting the number of edges in the graph\n" "The next M lines each consist of three space separated integers x y r,\n" "where x and y denote the two nodes between which the undirected edge exists," "r denotes the weight of edge between the corresponding nodes.\n"; } int main() { int N, M; inputFormat(); std::cin >> N >> M; Graph G(N, M); G.getEdges(); std::vector<Edge> MST = G.kruskalMST(); printMST(MST); return 0; }
4,036
C++
.cpp
124
28.346774
113
0.620991
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,869
dfsDemo.cpp
mandliya_algorithms_and_data_structures/graph_problems/dfsDemo.cpp
#include <iostream> #include "graph.h" /** * Implementation of BFS algorithm is in ../include/graph.h */ int main() { std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; algo::Graph<int> g(vec); g.setEdge(0, 1); g.setEdge(0, 2); g.setEdge(0, 3); g.setEdge(0, 4); g.setEdge(1, 5); g.setEdge(2, 6); g.setEdge(3, 1); g.setEdge(3, 5); g.setEdge(3, 7); g.setEdge(4, 2); g.setEdge(5, 3); g.setEdge(5, 6); g.setEdge(6, 2); g.setEdge(6, 4); g.setEdge(6, 5); g.display(); g.depth_first_search(0); return 0; }
541
C++
.cpp
28
16.714286
59
0.592157
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,870
bfsDemo.cpp
mandliya_algorithms_and_data_structures/graph_problems/bfsDemo.cpp
#include <iostream> #include "graph.h" /** * Implementation of BFS algorithm is in ../include/graph.h */ int main() { std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; algo::Graph<int> g(vec); g.setEdge(0, 1); g.setEdge(0, 2); g.setEdge(1, 0); g.setEdge(1, 2); g.setEdge(1, 3); g.setEdge(2, 4); g.setEdge(2, 6); g.setEdge(3, 1); g.setEdge(3, 7); g.setEdge(4, 6); g.setEdge(5, 1); g.setEdge(5, 3); g.setEdge(6, 5); g.setEdge(7, 5); g.display(); g.breadth_first_search(0); return 0; }
523
C++
.cpp
27
16.814815
59
0.595142
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,872
pstring.cpp
mandliya_algorithms_and_data_structures/include/pstring.cpp
/** * A string library for practice * Ravi Mandliya */ #include "pstring.h" using String = algo::String; String::String( ) { _reset(); } String::String( const char * s ) { _copy_str(s); } String::String( const String & str ) { _copy_str(str); } String::String( String && other ) noexcept { _reset(); _str = other._str; _str_len = other._str_len; other._str = nullptr; other._str_len = 0; other._reset(); } String::~String() { _reset(); } void String::_alloc_cstr(size_t sz) { if ( _str ) { _reset(); } _str_len = ( sz > algo::_PSTRING_MAX_LEN ) ? algo::_PSTRING_MAX_LEN : sz; _str = new char[_str_len + 1](); } void String::_reset() { if ( _str ) { delete [] _str; } _str = nullptr; _str_len = 0; } void String::_swap( String & other ) { std::swap( _str, other._str ); std::swap( _str_len, other._str_len ); } const char * String::c_str() const { return _str; } void String::_copy_str( const char * s ) { if ( s ) { size_t sz = strnlen( s, algo::_PSTRING_MAX_LEN ); _alloc_cstr( sz ); strncpy( _str, s, sz ); } } bool String::_have_value() const { if ( _str ) { return true; } return false; } size_t String::_char_find( const char & match, size_t pos ) const { if ( pos >= _str_len ) { return algo::npos; } for ( size_t i = 0; _str[i + pos]; ++i ) { if ( _str[i] == match ) { return i; } } return algo::npos; } void String::_char_replace( const char & match_char, const char & replace_char) { for ( size_t i = 0; _str[i]; ++i ) { if ( _str[i] == match_char ) { _str[i] = replace_char; return; } } } String & String::operator = ( String other ) { _swap(other); return *this; } String & String::operator += ( const char * s ) { if ( s ) { size_t len1 = strlen(s); if ( len1 < 1 ) { return *this; } size_t new_len = len1 + _str_len; new_len = (new_len > algo::_PSTRING_MAX_LEN ) ? algo::_PSTRING_MAX_LEN : new_len; char * buf = new char[new_len + 1]; if (_str_len && _str ) { memcpy(buf, _str, _str_len); } memcpy(buf + _str_len, s, len1); _copy_str( buf ); delete[] buf; } return * this; } String & String::operator += ( const String & s ) { operator+=( s.c_str() ); return * this; } const char String::operator [] (const size_t index) const { if ( index >= this->length() ) return 0; return _str[index]; } bool String::operator == ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) == 0 ) { return true; } else return false; } bool String::operator != ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) != 0 ) { return true; } else return false; } bool String::operator >= ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) >= 0 ) { return true; } else return false; } bool String::operator <= ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) <= 0 ) { return true; } else return false; } bool String::operator < ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) < 0 ) { return true; } else return false; } bool String::operator > ( const String & s ) const { if ( std::strncmp(this->c_str(), s.c_str(), algo::_PSTRING_MAX_LEN ) > 0 ) { return true; } else return false; } String::operator const char * () const { return this->c_str(); } String String::lower() const { String rs = *this; for ( size_t i = 0; rs._str[i]; ++i ) { rs._str[i] = tolower(rs._str[i]); } return rs; } String String::upper() const { String rs = *this; for ( size_t i = 0; rs._str[i]; ++i ) { rs._str[i] = toupper(rs._str[i]); } return rs; } const char & String::front() const { return _str[0]; } const char & String::back() const { return _str[_str_len - 1]; } String String::substr( size_t pos, size_t len ) const { String rs; char * buf; if ( len + 1 > algo::_PSTRING_MAX_LEN || ( pos + len ) > algo::_PSTRING_MAX_LEN ) { return rs; } if ( _str_len - pos < len ) { return rs; } if (!_str) { return rs; } buf = new char[ len + 1 ](); memcpy( buf, _str + pos, len ); rs = buf; delete[] buf; return rs; } size_t String::find( const char * s, size_t pos ) const { size_t index = algo::npos; if ( pos >= _str_len ) { return index; } char * sub = strstr( _str + pos, s ); if ( sub ) { return ( sub - _str ); } return algo::npos; } size_t String::find( const String & match, size_t pos ) const { return find( match.c_str(), pos); } size_t String::find( char c, size_t pos ) const { return _char_find(c, pos); } String String::replace( size_t pos, size_t len, const char * str ) { String res; if ( ( pos >= _str_len ) || ( pos + len >= _str_len ) ) { return res; } String s1 = pos > 0 ? substr( 0, pos ) : "" ; String s2 = str; String s3 = substr( pos + len, _str_len - (pos+len)); String s4 = s1 + s2 + s3; return s4; } String String::replace( size_t pos, size_t len, const String & str) { return replace(pos, len, str.c_str()); } int String::compare( const char * str ) const { return strncmp( this->c_str(), str, algo::_PSTRING_MAX_LEN ); } int String::compare( const String & str ) const noexcept { return strncmp( this->c_str(), str.c_str(), algo::_PSTRING_MAX_LEN ); } String algo::operator + ( const String & lhs, const String & rhs ) { String ans = lhs; ans += rhs; return ans; } String algo::operator + ( const String & lhs, const char * rhs ) { String ans = lhs; ans += rhs; return ans; }
5,780
C++
.cpp
235
21.587234
86
0.580926
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,873
reverse_vowels.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/reverse_vowels.cpp
/* * Write a function that takes a string as input and reverse only the vowels of a string. * * Example 1: * Given s = "hello", return "holle". * * Example 2: * Given s = "leetcode", return "leotcede". * * Note: * The vowels does not include the letter "y". */ #include <iostream> #include <algorithm> bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); } std::string reverseVowels(std::string s) { if (s.length() == 0) { return s; } unsigned int i = 0; unsigned int j = s.length() - 1; while (i < j) { while (i < j && !isVowel(s[i])) { i++; } while (i < j && !isVowel(s[j])) { j--; } if (i < j) { std::swap(s[i], s[j]); ++i; --j; } } return s; } int main() { std::string str; std::cout << "Please enter input string: "; std::cin >> str; std::cout << "Expected output string: " << reverseVowels(str) << std::endl; return 0; }
1,220
C++
.cpp
57
15.210526
89
0.449378
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,874
moveZeroes.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/moveZeroes.cpp
/** * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. * * Approach: start putting all non zero elements from at the start, We will fill in all non zero elements in order. */ #include <iostream> #include <vector> #include <algorithm> void moveZeroes(std::vector<int>& nums) { size_t j = 0; for ( size_t i = 0; i < nums.size(); ++i ) { if ( nums[i] != 0 ) { std::swap(nums[i], nums[j]); ++j; } } } void printVec(std::vector<int> & vec) { std::cout << "Vec:"; for( auto & v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> nums{ 0, 1, 0, 3, 12 }; std::cout << "Before "; printVec(nums); moveZeroes(nums); std::cout << "After "; printVec(nums); return 0; }
924
C++
.cpp
34
25.147059
136
0.628668
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,875
remove_element.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/remove_element.cpp
/* * Source LeetCode Problem 27 Remove element. * Given an array and a value, remove all instances of that value in-place and return the new length. * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. * The order of elements can be changed. It doesn't matter what you leave beyond the new length. * * Approach: * * The idea is to use two pointers, one iterates the entire nums(i), and the other one maintains the length of set of numbers * which we want in our output.(j). The idea is everytime we find a wanted element we move the j. This way j maintains all * the wanted element at top of the nums. */ #include <iostream> #include <vector> int remove_element(std::vector<int>& nums, int value) { int j = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != value) { nums[j] = nums[i]; j++; } } return j; } void print_vector(std::vector<int>& nums, int count) { for (int i = 0; i < count; ++i) { std::cout << nums[i] << " "; } std::cout << std::endl; } int main() { std::vector<int> nums = {2, 2, 3, 4, 4, 5, 6, 2, 4, 3, 2, 3}; std::cout << "Vector: "; print_vector(nums, nums.size()); int count = remove_element(nums, 2); std::cout << "Removing 2 from above vector: "; print_vector(nums, count); return 0; }
1,458
C++
.cpp
42
29.738095
129
0.616915
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,876
maxProfitStock.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/maxProfitStock.cpp
/** * Say you have an array for which the ith element is the price of a given stock on day i. * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), * Design an algorithm to find the maximum profit. */ #include <iostream> #include <vector> int maxProfit(std::vector<int>& prices) { if (prices.size() == 0 ) { return 0; } std::vector<int> dp(prices.size()); dp[0] = 0; int buyPrice = prices[0]; int mostProfit = 0; for ( size_t i = 1; i < prices.size(); ++i ) { if ( prices[i] >= buyPrice ) { dp[i] = dp[i-1] + prices[i] - prices[i-1]; } else { dp[i] = 0; buyPrice = prices[i]; } if (mostProfit < dp[i]) { mostProfit = dp[i]; } } return mostProfit; } void printStocks( std::vector<int> & stocks ) { std::cout << "Stock prices:"; for ( auto stock : stocks ) { std::cout << stock << " "; } std::cout << std::endl; } int main() { std::vector<int> prices{ 45, 33, 66, 78, 90, 47 }; printStocks(prices); std::cout << "Max profit from above price range:" << maxProfit(prices) << std::endl; return 0; }
1,102
C++
.cpp
41
24.658537
112
0.63327
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,878
connectNextPointers.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/connectNextPointers.cpp
/** * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. * * Initially, all next pointers are set to NULL. * * Note: * * You may only use constant extra space. * You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). * */ #include<iostream> #include<queue> struct TreeLinkNode { int data; TreeLinkNode * left; TreeLinkNode * right; TreeLinkNode * next; TreeLinkNode( int d ) : data{ d }, left{ nullptr }, right{ nullptr }, next{ nullptr } {} }; void connect(TreeLinkNode *root) { if( root == nullptr) { return; } std::queue<TreeLinkNode*> qu; qu.push(root); qu.push(nullptr); TreeLinkNode * curr = nullptr; while(!qu.empty()) { curr = qu.front(); qu.pop(); if ( curr == nullptr ) { if (!qu.empty()) { qu.push(nullptr); } continue; } if (!qu.empty()) { curr->next = qu.front(); } else { curr->next = nullptr; } if ( curr->left ) { qu.push(curr->left); } if ( curr->right ) { qu.push(curr->right); } } } void printTree( TreeLinkNode * root ) { if (root) { std::cout << "Node value " << root->data << "-->"; if ( root->next != nullptr ) { std::cout << root->next->data << std::endl; } else { std::cout << "nullptr" << std::endl; } printTree(root->left); printTree(root->right); } } int main() { TreeLinkNode * root = new TreeLinkNode(1); root->left = new TreeLinkNode(2); root->right = new TreeLinkNode(3); root->left->left = new TreeLinkNode(4); root->left->right = new TreeLinkNode(5); root->right->left = new TreeLinkNode(6); root->right->right = new TreeLinkNode(7); std::cout << "Before Connect:\n"; printTree(root); connect(root); std::cout << "After Connect:\n"; printTree(root); return 0; }
1,857
C++
.cpp
77
21.662338
134
0.65031
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,879
containsDuplicate.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/containsDuplicate.cpp
/** * Given an array of integers, find if the array contains any duplicates. * Your function should return true if any value appears at least twice in the array, * and it should return false if every element is distinct. * * Approach : sort and check for adjacent elements for duplicates. * */ #include <iostream> #include <vector> #include <algorithm> bool containsDuplicate(std::vector<int>& nums) { std::sort( nums.begin(), nums.end()); for ( size_t i = 1; i < nums.size(); ++i ) { if ( nums[i-1] == nums[i] ) { return true; } } return false; } void printVect( std::vector<int> & vec ) { std::cout << "VEC:"; for ( auto & i : vec ) { std::cout << i << " "; } std::cout << std::endl; } int main() { std::vector<int> vec1{ 1, 99, 99, 4, 8, 98, 96, 3, 5, 19, 23, 17, 84, 23 }; printVect(vec1); if ( containsDuplicate(vec1) ) { std::cout << "Above vector contains duplicates\n"; } else { std::cout << "Above vector does not contain duplicates\n"; } return 0; }
1,000
C++
.cpp
37
24.945946
85
0.652038
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,880
median_stream.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/median_stream.cpp
/* * Source : Leetcode, 295. Find Median from Data Stream * Category : hard * * Find median from a data stream. Design a data structure that supports addNum to add a number to the stream, * and findMedian to return the median of the current numbers seen so far. Also, if the count of numbers is * even, return average of two middle elements, return median otherwise. * * In naive approach, we could maintain an internal vector and sort the array everytime median is requested, * and return the middle element(when odd count) or mean of two middle elements (when mean count) * * However, this doesn't scale well as the size of the vector grows, and if 'findMedian' is accessed too * frequently. We would want a potentially better solution which could reduce the cost of finding median, * even though we might make add a little slow. * * We could use something which maintains a ordered stream of numbers, and median could be retrieved in O(1) * time, and add could be done in O(logn) time. * * This could be achieved using a Self-Balanced Binary search tree, or using two heaps. * We will currently solve with a heap approach. * * Why two heaps? * We want two middle numbers (in even count case), so if we maintain two heaps, one min-heap and other * max-heap, the max-heap will maintain the lower ordered half of the numbers while the min-heap would * maintained the upper half of the numbers. * Consider even number of numbers in stream so far, in that case, the top of the lower heap (max heap) * will contain the left middle number of the stream and top of upper heap (min heap) will contain the * right middle number of the stream. Thus we could retrive the two middle numbers in O(1) time. * * [1, 2, 3, 4, 5] <-- values in lower heap. (MAX heap) * [6, 7, 8, 9, 10] <-- Values in upper heap. (MIN heap) * * lower.top() = 5 * upper.top() = 6 * So we will want (6+5)/2 = 5.5 as answer. * * Now, the algorithm: * In order to maintain the two middle numbers of the stream on the top of the two heaps, * we will have to balance them with each addition of new number. * * In case of odd numbers, the lower heap will contain 1 number extra then the upper heap. * In case of even numbers, both the heaps will have equal numbers of elements. * * As we add a new number, we will add it to lower, then we will balance the heaps by transferring * the top to upper heap, and then we will maintain the size property maintained above. */ #include <iostream> #include <queue> #include <vector> #include <random> #include <algorithm> class MedianFinder { public: MedianFinder() {} void addNum(int num) { // first add it to lower. lower.push(num); // balance the heaps to set the right values at the top. upper.push(lower.top()); lower.pop(); // Maintain the size property. if (lower.size() < upper.size()) { lower.push(upper.top()); upper.pop(); } } double findMedian() { return (lower.size() > upper.size()) ? static_cast<double>(lower.top()) : (static_cast<double>(lower.top() + upper.top()) / 2); } // utility function to print current sorted stream. void printSortedStream() { std::priority_queue<int> lc{lower}; std::priority_queue<int, std::vector<int>, std::greater<int>> uc{upper}; std::vector<int> temp; // lower half first; while(!lc.empty()){ temp.push_back(lc.top()); lc.pop(); } std::reverse(temp.begin(), temp.end()); for (auto n: temp) { std::cout << n << " "; } while (!uc.empty()) { std::cout << uc.top() << " "; uc.pop(); } std::cout << std::endl; } private: // max heap maintaining the lower half of ordered stream. std::priority_queue<int> lower; // min heap maintaining the upper half of ordered stream. std::priority_queue<int, std::vector<int>, std::greater<int>> upper; }; int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0,20); MedianFinder medianFinder; for (int i=0; i<5; ++i) { medianFinder.addNum(distribution(generator)); } // current state of stream medianFinder.printSortedStream(); std::cout << "Median of current stream: " << medianFinder.findMedian() << std::endl; // Add 5 more. // for (int i=0; i<5; ++i) { medianFinder.addNum(distribution(generator)); } // current state of stream medianFinder.printSortedStream(); std::cout << "Median of current stream: " << medianFinder.findMedian() << std::endl; return 0; }
4,797
C++
.cpp
124
33.596774
110
0.660864
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,881
hamming_distance.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/hamming_distance.cpp
/** The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different */ #include <iostream> int hamming_distance(int x, int y) { // XOR will set only those bits in z which are different in x and y int z = x ^ y; // Now just count set bits in z. int count = 0; while (z) { count += (z % 2); z >>= 2; } return count; } int main() { int x = 4; int y = 1; std::cout << "Hamming distance between " << x << " and " << y << " is : " << hamming_distance(x, y) << std::endl; }
870
C++
.cpp
33
21.30303
79
0.588957
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,882
intersection_of_array.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/intersection_of_array.cpp
/* * Find intersection of two arrays/vectors: * Given two vectors find the result of their interaction. * The result should only contain unique characters and can be in any order. * * [1 2 3 3 4 4 5 5] * [2 3 5 5 4 4 6] * Result: [2 3 5 4] or [2 3 4 5] */ #include <iostream> #include <vector> #include <unordered_set> std::vector<int> find_intersection(const std::vector<int>& vec1, const std::vector<int>& vec2) { std::vector<int> result; std::unordered_set<int> set(vec1.begin(), vec1.end()); for (int num : vec2) { if (set.erase(num)) { result.push_back(num); } } return result; } template <typename T> void print_vector(const std::vector<T>& vec) { for (auto n: vec) { std::cout << n << " "; } std::cout << std::endl; } int main() { std::vector<int> vec1 {1, 2, 3, 3, 4, 4, 5, 5}; std::vector<int> vec2 {2, 3, 5, 5, 4, 4, 6}; std::cout << "Vec 1: "; print_vector(vec1); std::cout << "Vec 2: "; print_vector(vec2); std::vector<int> result = find_intersection(vec1, vec2); std::cout << "Result: "; print_vector(result); return 0; }
1,160
C++
.cpp
44
22.522727
76
0.598383
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,884
longestConsecutiveSeq.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/longestConsecutiveSeq.cpp
/** * Leet code problem: * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. * For example, * Given [100, 4, 200, 1, 3, 2], * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. */ #include <iostream> #include <vector> #include <unordered_map> int longestConsecutive(std::vector<int>& nums) { std::unordered_map<int,int> hashMap; for ( auto n : nums ) { hashMap.insert({n, -1}); } int max_so_far = 0; for ( size_t i = 0; i < nums.size(); ++i ) { int j = 0; int k = nums[i]; while( hashMap.find(k + j) != hashMap.end() ) { if (hashMap[k+j] != -1 ) { j += hashMap[k+j]; break; } ++j; } hashMap[k] = j; if ( j > max_so_far ) { max_so_far = j; } } return max_so_far; } void printVec(std::vector<int> & vec) { for ( auto & v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::cout << "Vector:"; std::vector<int> vec{ 100, 4, 200, 1, 3, 2 }; printVec(vec); std::cout << "Longest consecutive sequence length:" << longestConsecutive(vec) << std::endl; return 0; }
1,126
C++
.cpp
46
22.086957
101
0.609302
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,885
remove_duplicates.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/remove_duplicates.cpp
/* * Given a sorted array, remove duplicates in place and return the new length. * It doesn't matter what is in array beyond the unique elements size. * Expected O(1) space and O(n) time complexity. * Input : {1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7} * Output: {1, 2, 3, 4, 5, 6, 7} */ #include <iostream> #include <vector> template <typename T> void swap(T& a, T& b) { T c(std::move(a)); a = std::move(b); b = std::move(c); } unsigned int remove_duplicates(std::vector<int>& nums) { unsigned int i = 0; for (unsigned int j = 0; j < nums.size(); ++j) { if (nums[i] != nums[j]) { swap(nums[++i], nums[j]); } } return i+1; } void print_vector(const std::vector<int>& vec, unsigned int n) { for (unsigned int i = 0; i < n; ++i) { std::cout << vec[i] << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7}; std::cout << "Original vector:"; print_vector(vec, vec.size()); unsigned int size = remove_duplicates(vec); std::cout << "Output vector:"; print_vector(vec, size); return 0; }
1,195
C++
.cpp
43
23
79
0.549518
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,886
sortCharByFrequency.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/sortCharByFrequency.cpp
/* * Given a string, sort it in decreasing order based on the frequency of characters. * Example: * Input: cccbbbbaa * Output: bbbcccaa * * Input: AaaBBaa * Output: aaaaBBA * * Input: cccaaa * Output:cccaaa or aaaccc * * Notice that order of chars in alphabatical order does not matter for same frequency elements. * However, also all the same characters should be together. cacaca will not be a valid answer. */ #include <iostream> #include <unordered_map> #include <map> std::string frequencySort(std::string s) { // Create a hash map of our characters with frequency as their values. std::unordered_map<char,int> frequencyMap; for (char c : s) { frequencyMap[c]++; } // Now we will maintain an another ordered map whose key would be // the frequency and values would be accumulated chars of same frequency. // std::map<int, std::string> stringMap; for (auto frqPair : frequencyMap) { char c = frqPair.first; int n = frqPair.second; stringMap[n] += std::string(n, c); } // Now pick the accumulated string in reverse order (highest first) std::string result; for (auto it = stringMap.rbegin(); it != stringMap.rend(); ++it) { result += it->second; } return result; } int main() { std::string input1{"cccbbbbaa"}; std::cout << "Input: " << input1 << std::endl; std::cout << "Output:" << frequencySort(input1) << std::endl; std::string input2{"cccaaa"}; std::cout << "Input:" << input2 << std::endl; std::cout << "Output:" << frequencySort(input2) << std::endl; return 0; }
1,731
C++
.cpp
50
28.46
96
0.627119
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,887
sumRootToLeafNumbers.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/sumRootToLeafNumbers.cpp
/** * * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. * * An example is the root-to-leaf path 1->2->3 which represents the number 123. * * Find the total sum of all root-to-leaf numbers. * * For example, * * 1 * / \ * 2 3 * The root-to-leaf path 1->2 represents the number 12. * The root-to-leaf path 1->3 represents the number 13. * * Return the sum = 12 + 13 = 25. */ #include <iostream> #include <vector> struct TreeNode { int val; TreeNode * left; TreeNode * right; TreeNode( int data ) : val{ data }, left{ nullptr }, right{ nullptr } { } }; void rootToLeafSum( TreeNode* root, int & total, int & curr ) { if( root == nullptr ) { return; } curr = (10*curr) + root->val; if (root && root->left == nullptr && root->right == nullptr ) { total += curr; } int oldCurr = curr; rootToLeafSum(root->left, total, curr); rootToLeafSum(root->right, total, oldCurr); } int sumNumbers(TreeNode* root) { int total = 0; int curr = 0; rootToLeafSum(root, total, curr); return total; } void printTree( TreeNode * root ) { if ( root ) { printTree( root->left ); std::cout << root->val << " "; printTree( root->right ); } } int main() { TreeNode * root = new TreeNode( 1 ); root->left = new TreeNode( 2 ); root->right = new TreeNode( 3 ); std::cout << "Tree in order:"; printTree(root); std::cout << "Output : " << sumNumbers(root) << std::endl; return 0; }
1,499
C++
.cpp
60
22.966667
104
0.637762
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,888
find_min_rotated.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/find_min_rotated.cpp
/** * Find Minimum in Rotated Sorted Array * Suppose a sorted array is rotated at some pivot unknown to you beforehand. * * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * * Find the minimum element. * * You may assume no duplicate exists in the array. */ #include <iostream> #include <vector> int findMin(std::vector<int>& nums) { int n = nums.size(); if ( n == 1 ) { return nums[0]; } if ( n == 2 ) { return ( nums[0] < nums[1] ? nums[0] : nums[1]); } int i = n - 1; while ( i > 0 && nums[i] > nums[i-1]) { --i; } return nums[i]; } int main() { std::cout << "Vec:"; std::vector<int> vec{ 4, 5, 6, 7, 0, 1, 2 }; for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; std::cout << "Min in above vector: " << findMin(vec) << std::endl; return 0; }
805
C++
.cpp
36
20.333333
77
0.581699
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,889
editDistance.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/editDistance.cpp
/** * Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) * * You have the following 3 operations permitted on a word: * * a) Insert a character * b) Delete a character * c) Replace a character * */ #include <iostream> #include <string> using std::string; int min( int a, int b, int c ) { int minab = ( a < b ) ? a : b; return ( minab < c ) ? minab:c; } int minEditDistance(string word1, string word2) { int len1 = word1.size(); int len2 = word2.size(); int minCost; int ** table = new int*[len1+1]; for ( int i = 0;i <= len1; ++i ) { table[i] = new int[len2+1]; } for (int i = 0; i <= len1; ++i) { for (int j = 0; j <= len2; ++j ) { if ( i == 0 ) { table[i][j] = j; } else if ( j == 0 ) { table[i][j] = i; } else if ( word1[i-1] == word2[j-1]) { table[i][j] = table[i-1][j-1]; } else { table[i][j] = 1+ min(table[i-1][j-1], table[i][j-1], table[i-1][j]); } } } minCost = table[len1][len2]; for ( int i = 0; i <= len1; ++i ) { delete table[i]; } delete[] table; return minCost; } int main() { std::string word1, word2; std::cout << "Enter word 1 : " ; std::cin >> word1; std::cout << "Enter word 2 : " ; std::cin >> word2; std::cout << "Min edit distance : " << minEditDistance(word1, word2) << std::endl; return 0; }
1,388
C++
.cpp
55
22.781818
143
0.585219
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,890
best_time_to_buy_sell.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/best_time_to_buy_sell.cpp
/* * You are provided a vector of numbers, where each number represents * price of a stock on ith day. If you are permitted to only complete * one transaction per day (i.e buy one and sell one stock), design * an algorithm to find the maximum profit. * * Input: [7, 1, 5, 3, 6, 4] * Output: 5 * max. difference = 6-1 = 5 * (not 7-1 = 6, as selling price needs to be larger than buying price) * * Approach: * * We need to find the maximum difference between two numbers in the array * (which would be maximum profit) such that selling price(second number) * is bigger than buying price. */ #include <iostream> #include <vector> #include <limits> int maximum_profit(const std::vector<int>& prices) { int min_price = std::numeric_limits<int>::max(); int max_profit = 0; for (int i = 0; i < prices.size(); ++i) { if (prices[i] < min_price) { min_price = prices[i]; } else if (prices[i] - min_price > max_profit) { max_profit = prices[i] - min_price; } } return max_profit; } void print_vector(const std::vector<int>& vec) { for (auto v : vec) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> prices{7, 1, 5, 3, 6, 4}; std::cout << "Prices of stocks in last " << prices.size() << " days:" << std::endl; print_vector(prices); std::cout << "Maximum profit: " << maximum_profit(prices) << std::endl; return 0; }
1,487
C++
.cpp
49
26.326531
74
0.616457
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,891
word_pattern.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/word_pattern.cpp
/* * * Given a pattern and a string str, find if str follows the same pattern. * Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. * Examples: * pattern = "abba", str = "dog cat cat dog" should return true. * pattern = "abba", str = "dog cat cat fish" should return false. * pattern = "aaaa", str = "dog cat cat dog" should return false. * pattern = "abba", str = "dog dog dog dog" should return false. * Notes: * You may assume pattern contains only lowercase letters, and str * contains lowercase letters separated by a single space. * * Approach: * * Split the string into words, and then map it to each character of the patterns as _we move. * If the character is being mapped to multiple words, or a word is being mapped to multiple * character, then the str is not following pattern. */ #include <iostream> #include <vector> #include <sstream> #include <unordered_map> #include <unordered_set> bool match_pattern(const std::string& str, const std::string& pattern) { // split string to words std::istringstream iss(str); std::vector<std::string> words(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (words.size() != pattern.size()) { return false; } std::unordered_map<char, std::string> map; std::unordered_set<std::string> set; for (int i = 0; i < pattern.size(); ++i) { if (map.find(pattern[i]) != map.end()) { // pattern is already mapped to some other string. if (words[i] != map[pattern[i]]) { return false; } } else { // word is already mapped to some other string. if (set.count(words[i])) { return false; } else { map[pattern[i]] = words[i]; set.insert(words[i]); } } } return true; } int main() { std::string pattern{"abba"}; std::string str{"dog cat cat dog"}; std::cout << "Pattern : " << pattern << std::endl; std::cout << "String :" << str << std::endl; bool r = match_pattern(str, pattern); std::string result = (r) ? "true" : "false"; std::cout << "Result :" << result << std::endl; pattern = "aaaa"; std::cout << "Pattern : " << pattern << std::endl; std::cout << "String :" << str << std::endl; r = match_pattern(str, pattern); result = (r) ? "true" : "false"; std::cout << "Result :" << result << std::endl; return 0; }
2,587
C++
.cpp
69
31.623188
122
0.601513
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,893
generate_parenthesis.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/generate_parenthesis.cpp
/** * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. * * For example, given n = 3, a solution set is: * * "((()))", "(()())", "(())()", "()(())", "()()()" * */ #include <iostream> #include <vector> #include <string> void generate_parenthesis_helper( int n, int left, int right, std::string curr, std::vector<std::string> & result ) { if (right == n) { result.push_back(curr); } else { if (left < n) { generate_parenthesis_helper( n, left + 1, right, curr + '(', result); } if (right < left) { generate_parenthesis_helper( n, left, right + 1, curr + ')', result); } } } std::vector<std::string> generate_parenthesis( int n ) { std::vector<std::string> result; std::string curr{ "" }; generate_parenthesis_helper(n, 0, 0, curr, result); return result; } int main() { std::vector<std::string> result = generate_parenthesis(3); for ( auto s : result ) { std::cout << "{ " << s << " }" << std::endl; } return 0; }
1,007
C++
.cpp
36
25.833333
117
0.619048
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,894
merge_trees.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/merge_trees.cpp
/* Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 */ #include <iostream> struct Node { int value; Node* left; Node* right; Node(int val): value{val}, left{nullptr}, right{nullptr}{} }; Node* mergeTrees(Node* t1, Node* t2) { if (!t1) { return t2; } if (!t2) { return t1; } t1->value += t2->value; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; } void preOrder(Node* t1) { if (t1) { std::cout << t1->value << " "; if (t1->left) { preOrder(t1->left); } else { std::cout << "null" << " "; } if (t1->right) { preOrder(t1->right); } else { std::cout << "null" << " "; } } } int main() { Node* t1 = new Node(1); t1->left = new Node(3); t1->right = new Node(2); t1->left->left = new Node(5); std::cout << "Tree 1:"; preOrder(t1); std::cout << std::endl; Node* t2 = new Node(2); t2->left = new Node(1); t2->right = new Node(3); t2->left->right = new Node(4); t2->right->right = new Node(7); std::cout << "Tree 2:"; preOrder(t2); std::cout << std::endl; Node* t3 = mergeTrees(t1, t2); std::cout << "Tree 3:"; preOrder(t3); std::cout << std::endl; return 0; }
2,326
C++
.cpp
90
17.677778
97
0.432384
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,895
remove_invalid_parenthesis.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/remove_invalid_parenthesis.cpp
/* * Remove the minimum number of invalid parentheses in order to make the input string valid. * Return all possible results. * Note: The input string may contain letters other than the parentheses ( and ). * * Source: Leetcode, 301. Remove Invalid Parentheses * * solution approach: * * We can solve this problem in many ways, I am choosing DFS. * For a string to be valid, we have two requirements: * 1. The number of left and right parenthesis should be same. * 2. They should be in right order, for each open there has to be a close, so for example '()' is valid * but ')(' is not. * * 1. We track the count of left and right parenthesis which are out of place. * 2. We recursively backtrack and go two ways. * If a character is left or right parenthesis, * a. we keep it * b. or we drop it. * 3. In both the cases we adjust open left and right parameters accordingly. * Open is the count of parenthesis sets which are open but not close yet. * When we reach end of string, we check if it is valid by left, right and open count and * push the string to result set. * 4. If a character is not a parenthesis operator, we simply add it to the result string. * 5. At the end of backtracking, we simply replace the current result string with the one * we started this iteration with. * * We are using a set to keep the results unique. * */ #include <iostream> #include <string> #include <unordered_set> #include <vector> void dfs(const std::string& s, std::string temp, int index, int left, int right, int open, std::unordered_set<std::string>& result) { if (index == s.length()) { if (left == 0 && right == 0 && open == 0) { result.insert(temp); } return; } if (left < 0 || right < 0 || open < 0) { return; } std::string current{temp}; char c = s[index]; if (c == '(') { // Drop dfs(s, temp, index + 1, left - 1, right, open, result); // Keep dfs(s, temp + c, index + 1, left, right, open + 1, result); } else if (c == ')') { // Drop dfs(s, temp, index + 1, left, right - 1, open, result); // Keep dfs(s, temp + c, index + 1, left, right, open - 1, result); } else { dfs(s, temp + c, index + 1, left, right, open, result); } temp = current; } std::vector<std::string> remove_invalid_parenthesis(const std::string& s) { std::vector<std::string> result; if (s.length() == 0) { result.push_back(""); return result; } int left = 0; int right = 0; for (char c : s) { if (c == '(') left++; else if (c == ')') { if (left > 0) left--; else right++; } } std::unordered_set<std::string> result_set; std::string temp(""); dfs(s, temp, 0, left, right, 0, result_set); return std::vector<std::string>(result_set.begin(), result_set.end()); } template<typename T> void print_vec(const std::vector<T>& vec) { for (auto v: vec) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::string str("(a)())()"); std::cout << "Pattern: " << str << std::endl; std::cout << "Possible valid parenthesis combinations: "; print_vec(remove_invalid_parenthesis(str)); }
3,333
C++
.cpp
98
29.204082
104
0.611699
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,896
excelColSheetTitle.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/excelColSheetTitle.cpp
/** * Given a positive integer, return its corresponding column title as appear in an Excel sheet. * * For example: * * 1 -> A * 2 -> B * 3 -> C * ... * 26 -> Z * 27 -> AA * 28 -> AB * * Approach: * We need to convert the column value to effective a base 26 number, Imagine this is similar * to converting a decimal to hexadecimal value. However, we need to be cautious of that the * column numbers are not 0 indexed, they are indexed from 1. So every time our n % 26 is 0, * we reduce 1 from remaining number. * */ #include <iostream> #include <string> #include <algorithm> std::string convertToTitle(int n) { std::string result(""); while ( n > 0) { int rem = n % 26; if ( rem == 0 ) { result += 'Z'; n = (n/26) - 1; } else { result += char( rem-1 + 'A'); n = n/26; } } std::reverse(result.begin(), result.end()); return result; } int main() { std::cout << "Enter the column index(1 based):"; int col; std::cin >> col; std::cout << "Corresponding excel sheet title for column number " << col << " is :" << convertToTitle(col) << std::endl; return 0; }
1,151
C++
.cpp
47
22.276596
96
0.613079
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,897
count_islands.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/count_islands.cpp
/* * In a given 2D grid, 1 represents land and 0 represents water body. * We need to count number of islands. * An island is surrounded by connecting neighbouring lands vertically * or horizontally. * Assume: That everything around the grid is water. * * Approach: We can solve this problem with Depth/Breadth first search. * * With Depth first search: * Consider a land body, and start a depth first search, and mark all the * connected land bodies to it as water bodies (i.e. mark all connected 1's * as 0 to mark them visited) * In this case, number of islands for which DFS was started is the total * count of islands. * Similar idea could be used for BFS. * * Example: * * 1 1 0 0 * 1 0 1 0 * 1 0 0 1 * * There are 3 islands in above grid. */ #include <iostream> #include <vector> void depth_first_search(std::vector<std::vector<int> >& grid, int i, int j) { int m = grid.size(); int n = grid[0].size(); if (i < 0 || i >= m || j < 0 || j >= n) { return; } grid[i][j] = 0; if (i + 1 < m && grid[i + 1][j] == 1) { depth_first_search(grid, i + 1, j); } if (i - 1 >= 0 && grid[i - 1][j] == 1) { depth_first_search(grid, i - 1, j); } if (j + 1 < n && grid[i][j + 1] == 1) { depth_first_search(grid, i, j + 1); } if (j - 1 >= 0 && grid[i][j - 1] == 1) { depth_first_search(grid, i, j - 1); } } int number_of_islands(std::vector<std::vector<int>>& grid) { int m = grid.size(); if (m == 0) { return 0; } int n = grid[0].size(); int total_islands = 0; for ( int i = 0; i < m; ++i) { for ( int j = 0; j < n; ++j) { if (grid[i][j] == 1) { ++total_islands; depth_first_search(grid, i, j); } } } return total_islands; } int main() { std::vector<std::vector<int>> grid = { {1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1} }; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { std::cout << grid[i][j] << " "; } std::cout << std::endl; } std::cout << "Total number of islands in the grid is :" << number_of_islands(grid) << std::endl; return 0; }
2,323
C++
.cpp
84
22.654762
76
0.529333
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,898
jumpGame.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/jumpGame.cpp
/** * Given an array of non-negative integers, you are initially positioned at the first index of the array. * * Each element in the array represents your maximum jump length at that position. * * Determine if you are able to reach the last index. * * For example: * A = [2,3,1,1,4], return true. * * A = [3,2,1,0,4], return false. * * Approach : Here we have to observe that array value represents *maximum* value, so we can always jump j index from index i as long as j < A[i]. * i.e. if A[i] = 3, we can jump either 1, 2, or 3 steps. * Now, We will use dynamic programing to solve this problem. Our subproblem is at any index i, what is the farthest index I can jump. If in the end * if the max value index we have gathered so far is bigger than array length, we have reached the last index. */ #include <iostream> #include <vector> bool canReach( std::vector<int> & vec ) { int n = vec.size(); if ( n == 0 ) { return false; } if ( n == 1 ) { return true; } int m = 0; for (int i = 0; i < n; ++i ) { if ( i <= m ) { m = std::max( m, vec[i] + i ); if ( m >= n-1) { return true; } } } return false; } void printRes( std::vector<int> & vec ) { std::cout << "VEC:"; for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; std::cout << (canReach(vec) ? "True" : "False"); std::cout << std::endl; } int main() { std::vector<int> vec1{ 2,3,1,1,4 }; std::vector<int> vec2{ 3,2,1,0,4 }; printRes(vec1); printRes(vec2); return 0; }
1,504
C++
.cpp
54
25.685185
148
0.632089
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,899
firstMissingPositiveNum.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/firstMissingPositiveNum.cpp
/** * Problem: Given an unsorted integer array, find the first missing positive integer. * * For example, * Given [1,2,0] return 3, * and [3,4,-1,1] return 2. * * Your algorithm should run in O(n) time and uses constant space. * * Approach : * Step 1 :Iterate through array and : * - Ignore non positive numbers. * - For a positive number, if we have A[i] = 'x', then in a sorted array in original scheme of things, * it should be placed at A[x-1] ( since array is 0 indexed), so we swap A[i] with A[x-1]. * Step 2: Iterate through array and now compare each value with their index, i.e. num[i] == i + 1. * - Whereever this check fails, that is the number at that index is missing, ( i.e. if A[i] is at wrong place, means i+1 is missing). */ #include <iostream> #include <vector> int firstMissingPositive(std::vector<int>& nums) { if( nums.size() == 0 ) { return 1; } size_t i = 0; for ( i = 0; i < nums.size(); ++i) { while(nums[i] > 0 && nums[i] < int(nums.size()) && nums[i] != int(i+1) && nums[i] != nums[nums[i] - 1]) { std::swap(nums[i], nums[nums[i]-1]); } } i = 0; while( i < nums.size() && nums[i] == int(i + 1)) { ++i; } return int(i+1); } void printVec(std::vector<int>& nums) { for ( auto num : nums ) { std::cout << num << " "; } std::cout << std::endl; } int main() { std::vector<int> vec1{ 1, 2, 0 }; std::cout << "Vector:"; printVec(vec1); std::cout << "First missing positive num :" << firstMissingPositive(vec1) << std::endl; std::vector<int> vec2{ 1000, -1 }; std::cout << "Vector:"; printVec(vec2); std::cout << "First missing positive num :" << firstMissingPositive(vec2) << std::endl; std::vector<int> vec3{ 3,4,-1,1 }; std::cout << "Vector:"; printVec(vec3); std::cout << "First missing positive num :" << firstMissingPositive(vec3) << std::endl; std::vector<int> vec4{ 0 }; std::cout << "Vector:"; printVec(vec4); std::cout << "First missing positive num :" << firstMissingPositive(vec4) << std::endl; std::vector<int> vec5{ 1 }; std::cout << "Vector:"; printVec(vec5); std::cout << "First missing positive num :" << firstMissingPositive(vec5) << std::endl; return 0; }
2,180
C++
.cpp
65
31.430769
137
0.631829
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,901
rotateList.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/rotateList.cpp
/** * Given a list, rotate the list to the right by k places, where k is non-negative. * For example: * Given 1->2->3->4->5->NULL and k = 2, * return 4->5->1->2->3->NULL */ #include <iostream> struct ListNode { int val; ListNode * next; ListNode(int x) : val(x), next(NULL) {} }; void printList(ListNode * node) { std::cout << "List: "; while( node ) { std::cout << node->val << " "; node = node->next; } std::cout << std::endl; } void insert(ListNode* & head, int data ) { ListNode * newNode = new ListNode(data); if ( head == nullptr ) { head = newNode; } else { ListNode * curr = head; while ( curr->next != nullptr ) { curr = curr->next; } curr->next = newNode; } } int length(ListNode * head) { int count = 0; while( head ) { head = head->next; ++count; } return count; } ListNode* rotateRight(ListNode* head, int k) { if ( head == nullptr || head->next == nullptr) { return head; } int len = length(head); k = k % len; if ( k == 0) { return head; } ListNode * ptr1 = head; ListNode * ptr2 = head; int c = 0; while( ptr1 && c < k ) { ptr1 = ptr1->next; c++; } if (!ptr1) { return nullptr; } while( ptr1 && ptr1->next != nullptr ) { ptr1 = ptr1->next; ptr2 = ptr2->next; } ListNode * newHead = ptr2->next; ptr2->next = nullptr; ptr1->next = head; return newHead; } int main() { ListNode * head = nullptr; insert( head, 1); insert( head, 2); insert( head, 3); insert( head, 4); insert( head, 5); printList(head); head = rotateRight(head, 2); printList(head); return 0; }
1,571
C++
.cpp
80
17.45
83
0.615541
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,902
maxArea.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/maxArea.cpp
/** * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). * Find two lines, which together with x-axis forms a container, such that the container contains the most water. * Note: You may not slant the container. */ #include <iostream> #include <vector> #include <limits> int maxArea(std::vector<int>& height) { size_t l = 0; size_t r = height.size() - 1; int maxAr = std::numeric_limits<int>::min(); while( l < r ) { int curAr = ( std::min(height[l], height[r]) * ( r - l )); if ( curAr > maxAr ) { maxAr = curAr; } if ( height[l] < height[r]) { l++; } else { r--; } } return maxAr; } void printVec( std::vector<int> & vec ) { std::cout << "Heights:"; for( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> heights{ 4, 5, 1 }; printVec(heights); std::cout << "Max possible area with above heights:" << maxArea(heights) << std::endl; return 0; }
1,080
C++
.cpp
40
24.85
113
0.630309
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,903
addDigits.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/addDigits.cpp
/** * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. * * For example: * * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. * * Follow up: * Could you do it without any loop/recursion in O(1) runtime? * * solution approach: * Look at the pattern which emerges when we sum the values and eventually reduce it to single digit. By observing carefully, we will see a pattern. * * This is calculating digital root of a number (https://en.wikipedia.org/wiki/Digital_root) * The formula is: * dr(n) = 0 if n = 0, * 9 if n != 0 and (n % 9 == 0) * n % 9 * */ #include <iostream> int sumDigits( int num ) { if ( num == 0 ) { return 0; } else if ( num % 9 == 0 ) { return 9; } return num % 9; } int main() { int n; std::cout << "Enter a number:"; std::cin >> n; std::cout << "Digital root of " << n << " is :" << sumDigits(n) << std::endl; return 0; }
992
C++
.cpp
36
25.527778
148
0.633018
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,904
combinationSum3.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/combinationSum3.cpp
/** * Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used * and each combination should be a unique set of numbers. * * Ensure that numbers within the set are sorted in ascending order. * Example: * Example 1: * * Input: k = 3, n = 7 * * Output: * [[1,2,4]] * * Input: k = 3, n = 9 * * Output: * [[1,2,6], [1,3,5], [2,3,4]] */ #include <iostream> #include <vector> void combination( std::vector<std::vector<int>> & results, std::vector<int> & curr, int k, int n, int idx ) { if ( k == 0 && n == 0 ) { results.push_back(curr); return; } for ( int i = idx; i <= 10 - k && i <= n; ++i ) { curr.push_back(i); combination(results, curr, k - 1, n - i, i + 1 ); curr.pop_back(); } } std::vector<std::vector<int>> combinationVec( int k, int n ) { std::vector<std::vector<int>> results; std::vector<int> curr; combination(results, curr, k, n, 1); return results; } void printVecVec( std::vector<std::vector<int>> & vec ) { for ( auto v : vec ) { std::cout << "[ "; for ( auto e : v ) { std::cout << e << " "; } std::cout << "]" << std::endl; } } int main() { std::vector<std::vector<int>> results; std::cout << "Combinations for k = 3, n = 7\n"; results = combinationVec(3,7); printVecVec(results); results.clear(); std::cout << "\nCombinations for k = 3, n = 9\n"; results = combinationVec(3,9); printVecVec(results); return 0; }
1,458
C++
.cpp
57
23.368421
121
0.614831
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,905
missing_number.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/missing_number.cpp
/** * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. * * For example, * Given nums = [0, 1, 3] return 2. */ #include <iostream> #include <vector> int missingNumber( std::vector<int>& nums ) { int missing_sum = 0; for ( auto n : nums ) { missing_sum += n; } int n = nums.size(); int expected_sum = 0; if ( n % 2 == 0 ) { expected_sum = (n/2) * (n + 1); } else { expected_sum = n * ( (n+1)/2 ); } return expected_sum - missing_sum; } void printVec( std::vector<int> & vec ) { std::cout << "Vec:"; for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{ 0, 1, 3 }; printVec(vec); std::cout << "Missing number in above vector is :" << missingNumber(vec) << std::endl; return 0; }
834
C++
.cpp
35
21.857143
120
0.598742
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,906
summary_ranges.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/summary_ranges.cpp
/* * Leet code problem - summary pages * Given a sorted integer array without duplicates, return the summary of its ranges. * For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. */ #include <iostream> #include <algorithm> #include <vector> #include <string> std::vector<std::string> summaryRanges(std::vector<int>& nums) { std::vector<std::string> ranges; if (nums.empty()) { return ranges; } std::string curr = std::to_string(nums[0]); int range_start = nums[0]; for( size_t i = 1; i < nums.size(); ++i ) { if (nums[i-1] + 1 == nums[i]) { continue; } else { if ( range_start != nums[i-1]) { curr += "->"; curr += std::to_string(nums[i-1]); ranges.push_back(curr); } else { ranges.push_back(curr); } curr = std::to_string(nums[i]); range_start = nums[i]; } } if (range_start != nums[nums.size() - 1]) { curr += "->"; curr += std::to_string(nums[nums.size() - 1]); } ranges.push_back(curr); return ranges; } void printVec( std::vector<std::string> ranges ) { for ( size_t i = 0; i < ranges.size(); ++i ) { if ( i != ranges.size() - 1 ) { std::cout << ranges[i] << ", "; } else { std::cout << ranges[i] << std::endl; } } } int main() { std::vector<int> nums{0,1,2,4,5,7}; std::vector<std::string> ranges = summaryRanges(nums); printVec(ranges); return 0; }
1,628
C++
.cpp
53
22.867925
85
0.495541
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,907
threeSumClosest.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/threeSumClosest.cpp
/** * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. * Return the sum of the three integers. You may assume that each input would have exactly one solution. * For example, given array S = {-1 2 1 -4}, and target = 1. * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ #include <iostream> #include <vector> #include <algorithm> int threeSumClosest(std::vector<int>& nums, int target) { int closestSum = (nums[0] + nums[1] + nums[2]); std::sort(nums.begin(), nums.end()); for ( size_t i = 0 ;i < nums.size() - 2; ++i ) { size_t k = nums.size() - 1; size_t j = i + 1; while( j < k ) { int currSum = (nums[i] + nums[j] + nums[k]); if ( currSum == target ) { return currSum; } if ( abs(target - closestSum) > abs(target - currSum)) { closestSum = currSum; } if ( currSum > target ) { --k; } else { ++j; } } } return closestSum; } int main() { std::vector<int> vec{ -1,2,1,-4 }; std::cout << "Vec:"; for ( auto c : vec ) { std::cout << c << " "; } std::cout << std::endl; std::cout << "Three sum closest to 1 in above vector is :" << threeSumClosest(vec, 1) << std::endl; return 0; }
1,233
C++
.cpp
42
26.642857
115
0.60371
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,908
minPath.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/minPath.cpp
/** * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. * * Note: You can only move either down or right at any point in time. * * Can we do it in O(1) space complexity? */ #include <iostream> #include <vector> #include <utility> int minPathSum(std::vector<std::vector<int>>& grid) { size_t m = grid.size(); size_t n = grid[0].size(); for ( size_t i = 1; i < m; ++i ) { grid[i][0] += grid[i-1][0]; } for ( size_t i = 1; i < n; ++i ) { grid[0][i] += grid[0][i-1]; } for ( size_t i = 1; i < m; ++i ) { for ( size_t j = 1; j < n; ++j ) { grid[i][j] += std::min( grid[i-1][j], grid[i][j-1]); } } return grid[m-1][n-1]; } int main() { std::vector<std::vector<int>> grid { { 1, 0, 5 }, { 2, 3, 1}, { 4, 1, 9} }; for ( size_t i = 0; i < grid.size(); ++i ) { for ( size_t j = 0; j < grid[0].size(); ++j ) { std::cout << grid[i][j] << " "; } std::cout << std::endl; } std::cout << "Min cost for above grid from moving top left to bottom right is " << minPathSum(grid) << std::endl; return 0; }
1,172
C++
.cpp
42
24.857143
152
0.549734
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,909
shortest_path_maze.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/shortest_path_maze.cpp
/* * Given a matrix with cell values 0 or 1. Find the length of the shortest path from (a1, b1) * to (a2, b2), such that: * Path can only be constructed through cells which have value 1. * You can only travel in 4 possible directions, i.e. left, right, up and down. * * For example: Given matrix: * Input: * mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, * {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, * {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, * {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, * {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, * {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, * {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, * {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, * {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; * Source = {0, 0}; * Destination = {3, 4}; * Output: * Shortest Path is 11 * * We will use breadth first search, we start from source cell (and distance 0) * and explore neighbors in all possible directions, and keep adding * distance from source node for each cell, so for a cell we reach, * its shortest path = shortest path of parent + 1. We stop when we have reached * destination. If we have explored all possible valid cells from source cell, * we return false, i.e. we do not have valid path from source. */ #include <iostream> #include <queue> #include <limits> struct Point { int x; int y; }; struct Node { Point point; int distance; }; bool valid(const std::vector<std::vector<int>>& matrix, int x, int y) { return (x >= 0 && x < matrix[0].size() && y >= 0 && y < matrix.size()); } int shortestPath(const std::vector<std::vector<int>>& matrix, const Point& source, const Point& destination) { // An auxiliary matrix to keep track of visited points // initially all cells are marked unvisited. // std::vector<std::vector<bool>> visited( matrix.size(), std::vector<bool>(matrix[0].size(), false)); // Possible moves from a cell. // std::vector<int> row = {-1, 0, 0, 1}; std::vector<int> col = {0, -1, 1, 0}; std::queue<Node> nodeQueue; // mark the source cell visited and push it to queue. // visited[source.x][source.y] = true; nodeQueue.push({source.x, source.y, 0}); while (!nodeQueue.empty()) { // pop the front of the queue. Node current = nodeQueue.front(); nodeQueue.pop(); Point point = current.point; // if we have reached destination return distance. if (point.x == destination.x && point.y == destination.y) { return current.distance; } for (int i = 0; i < 4; ++i) { int r = point.x + row[i]; int c = point.y + col[i]; if (valid(matrix, r, c) && matrix[r][c] && !visited[r][c]) { visited[r][c] = true; Node adjNode = {r, c, current.distance + 1}; nodeQueue.push(adjNode); } } } return std::numeric_limits<int>::max(); } int main() { const std::vector<std::vector<int>> matrix = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Point source = {0, 0}; Point destination = {3, 4}; int distance = shortestPath(matrix, source, destination); if (distance != std::numeric_limits<int>::max()) { std::cout << "The distance between (" << source.x << ", " << source.y << ") and destination (" << destination.x << ", " << destination.y << ") is " << distance << std::endl; } else { std::cout << "The path does not exist between (" << source.x << ", " << source.y << ") and destination (" << destination.x << ", " << destination.y << ") is " << distance << std::endl; } return 0; }
4,405
C++
.cpp
125
28.048
94
0.487972
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,910
product_except_self.cpp
mandliya_algorithms_and_data_structures/leet_code_problems/product_except_self.cpp
/* * Given an array of n integers where n > 1, nums, return an array output * such that output[i] is equal to the product of all the elements of nums except nums[i]. * Example: [1, 2, 3, 4] ==> [24, 12, 8, 6] * * Try to use constant space. (excluding result array) */ #include <iostream> #include <vector> /* * Idea is to maintain two product variables, one from beginning and * one from the end. * Each result variable in result array * would be touched twice, one from the left to right * and other right to left, thus producing desired result. */ std::vector<int> product_except_self(const std::vector<int>& nums) { int product_from_beginning = 1; int product_from_end = 1; unsigned int n = nums.size(); std::vector<int> result(n, 1); for (unsigned int i = 0; i < n; ++i) { result[i] *= product_from_beginning; product_from_beginning *= nums[i]; result[n-1-i] *= product_from_end; product_from_end *= nums[n-1-i]; } return result; } void print_vector(const std::vector<int>& vec) { for (auto n : vec) { std::cout << n << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{1, 2, 3, 4}; std::cout << "Input Vector: "; print_vector(vec); std::vector<int> result = product_except_self(vec); std::cout << "Output Vector: "; print_vector(result); }
1,385
C++
.cpp
46
26.434783
90
0.635682
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,911
find_odd_one_out.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/find_odd_one_out.cpp
/** * Given a vector of numbers, only one number occurs odd number of times, find the number * Example - { 1, 1, 2, 2, 2, 2, 3, 3, 3} ==> Answer 3 * Approach - XOR of number with itself is 0, so even numbers will cancel out * and we will be left with odd number. */ #include <iostream> #include <vector> int find_odd_one_out( const std::vector<int> & vec ) { int check = 0; for ( auto i : vec ) { check ^= i; } return check; } void printVector( const std::vector<int> & vec ) { for ( auto & i : vec ) { std::cout << i << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; std::cout << "Vector contains :" << std::endl; printVector( vec ); std::cout << "Number which occurs odd time in the above vector :" << find_odd_one_out( vec ) << std::endl; return 0; }
873
C++
.cpp
33
23.787879
90
0.599282
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,912
check_opposite_signs.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/check_opposite_signs.cpp
/* * Given two integers, using bit manipulations determine if they are of opposite signs. * Most Significant Bit (MSB) of number represents sign of the number. If it is 1, it represents * a negative value, if it is 0, it represents a positive value. * If MSB of two numbers are different, their XOR would be 1, otherwise it would be 0. * Thus, result of XOR of two numbers will have MSB 1 if they are of opposite signs, * 0 other wise, in other words, XOR of two numbers would be negative (MSB 1) if they are of * opposite signs. * Source : http://graphics.stanford.edu/~seander/bithacks.html */ #include <iostream> bool are_of_different_signs(int a, int b) { return ((a ^ b) < 0); } int main() { int a, b; std::cout << "Enter number 1: "; std::cin >> a; std::cout << "Enter number 2:"; std::cin >> b; if (are_of_different_signs(a, b)) { std::cout << a << " and " << b << " are of different signs" << std::endl; } else { std::cout << a << " and " << b << " are of same signs" << std::endl; } return 0; }
1,104
C++
.cpp
32
30.375
96
0.625234
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
25,913
multiply_by_7.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/multiply_by_7.cpp
/** * Problem : Muliply a number by 7 by using bit manipulation. * Approach : left shift n by 3 --> 8n * Therefore 7n = 8n - n; */ #include <iostream> int multiply_by_7( int number ) { return ((number << 3) - number); } int main() { std::cout << "Enter a number:"; int num; std::cin >> num; std::cout << "7 x " << num << " = " << multiply_by_7(num) << std::endl; return 0; }
405
C++
.cpp
19
18.736842
61
0.575521
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,915
addBin.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/addBin.cpp
/* * Add two binary numbers represented as string. * */ #include <iostream> #include <string> #include <sstream> #include <algorithm> std::string addBinary( const std::string & str1, const std::string & str2 ) { std::string s1 = ( str1.length() > str2.length() ? str1 : str2 ); std::string s2 = ( str1.length() > str2.length() ? str2 : str1 ); int diff = s1.length() - s2.length(); std::stringstream ss; while(diff) { ss << "0"; --diff; } s2 = ss.str() + s2; std::cout << s1 << std::endl; std::cout << s2 << std::endl; ss.str(std::string()); int i = s1.length() - 1; int carry = 0; while ( i >= 0 ) { int x = ( s1[i] - '0') + ( s2[i] - '0') + carry; if ( x == 2 ) { x = 0; carry = 1; } else if ( x == 3 ) { x = 1; carry = 1; } else { carry = 0; } ss << x; --i; } if ( carry == 1 ) ss << carry; std::string result = ss.str(); std::reverse(result.begin(), result.end()); return result; } int main() { std::string str1("1010"); std::string str2("1011"); std::cout << "Addition of " << str1 << " and " << str2 << " is :" << addBinary(str1, str2) << std::endl; return 0; }
1,313
C++
.cpp
52
19.538462
108
0.482484
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,917
reverseBitsOfAnInteger.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/reverseBitsOfAnInteger.cpp
/** * Problem : Reverse bits of an unsigned integer */ #include <iostream> #include <sstream> #include <cassert> #include <algorithm> /** * swapBits - utility function to swap bits at position i and j in unsigned int x * l represents bit at position i * r represents bit at position j * if l and r are same nothing needs to be done. * if l and r are different i.e. (l ^ r == 1), * we toggle bits at position i and j, and return new x. */ unsigned int swapBits(unsigned int x, unsigned int i, unsigned int j) { unsigned int l = ((x >> i) & 1); unsigned int r = ((x >> j) & 1); if ( l ^ r ) { x ^= ((1U << i) | (1U << j)); } return x; } /* reverseBits1 : we swap first bit with last, second with one before last and so on. */ unsigned int reverseBits1(int n) { unsigned bitCount = sizeof(n) * 8; for( unsigned int i = 0; i < bitCount/2; ++i) { n = swapBits(n, i, bitCount-i-1); } return n; } /** * Now, approach 2, divide and conquer: * * 01101001 * / \ * 0110 1001 * / \ / \ * 01 10 10 01 * /\ /\ /\ /\ * 0 1 1 0 1 0 0 1 * * Just like merge sort, swap at each level and you are done. * First swap all odd and even bits, and then consecutive pair of bits * and so on. * This below approach will work on assumption that unsigned int size is 4bytes * or 32 bits. * Lets say a is 10 = 00000000 00000000 00000000 00001010 * Step 1: swap all odd and even positions. * a = (a & 0x55555555) << 1 | (a & 0xAAAAAAAA) >> 1 * 0x55555555 = 01010101 01010101 01010101 01010101 * a = 00000000 00000000 00000000 00001010 * --------------------------------------------------- and * a & (0x5..) = 00000000 00000000 00000000 00000000 * a & (0x5..) << 1 = 00000000 00000000 00000000 00000000 * * 0xAAAAAAAA = 10101010 10101010 10101010 10101010 * a = 00000000 00000000 00000000 00001010 * ------------------------------------------------- and * a & (0xA..) = 00000000 00000000 00000000 00001010 * a & (0xA..) >> 1 = 00000000 00000000 00000000 00000101 * * (a & (0x5..)) << 1 | (x & (0xA..)) >> 1 * = 00000000 00000000 00000000 00000101 * a = 00000000 00000000 00000000 00000101 * *********************************************************** * * Step2 : swap two consecutive bits with next consecutive two bits. * a = ((a & 0x33333333) << 2) | ((a & 0xCCCCCCCC) >> 2) * 0x33333333 = 00110011 00110011 00110011 00110011 * a = 00000000 00000000 00000000 00000101 * ------------------------------------------------- and * a & (0x33..)= 00000000 00000000 00000000 00000001 * * a & (0x33.) << 2 = 00000000 00000000 00000000 00000100 * * 0xCCCCCCCC = 11001100 11001100 11001100 11001100 * a = 00000000 00000000 00000000 00000101 * ------------------------------------------------- and * a & (0xcc..)= 00000000 00000000 00000000 00000100 * a & (0xcc..) >> 2 = 00000000 00000000 00000000 00000001 * (a & (0x33..) << 2) | (a & (0xcc) >> 2 ) * = 00000000 00000000 00000000 00000101 * a = 00000000 00000000 00000000 00000101 * * ********************************************************** * * Step3 : Swap 4 consecutive bits with next 4 * a = ((a & 0x0F0F0F0F) << 4) | ((a & 0xF0F0F0F0) >> 4); * 0x0F0F0F0F = 00001111 00001111 00001111 00001111 * a = 00000000 00000000 00000000 00000101 * ------------------------------------------------ and * a & (0x0F..)= 00000000 00000000 00000000 00000101 * a & (0x0F..) << 4 = 00000000 00000000 00000000 01010000 * * 0xF0F0F0F0 = 11110000 11110000 11110000 11110000 * a = 00000000 00000000 00000000 00000101 * --------------------------------------------------- * a & (0xF0..)= 00000000 00000000 00000000 00000000 * a & (0xF0..) >> 4 = 00000000 00000000 00000000 00000000 * therefore a = ((a & 0x0F0F0F0F) << 4) | ((a & 0xF0F0F0F0) >> 4) * a = 00000000 00000000 00000000 01010000 * * *********************************************************** * * Step4 : Swap consecutive bytes with each other * a = ((a & 0x00FF00FF) << 8) | ((a & 0xFF00FF00) >> 8); * 0x00FF00FF = 00000000 11111111 00000000 11111111 * 0xFF00FF00 = 11111111 00000000 11111111 00000000 * Clearly same as above operations, our a will become * a = 00000000 00000000 01010000 00000000 * * ************************************************************ * step5 : Finally swap two consecutive bytes with next two i.e. swapping left * 16 bits with right * * a = ((a & 0x0000FFFF) << 16) | ((a & 0xFFFF0000) >> 16); * So we will end up with * a = 01010000 00000000 00000000 00000000 * Clearly which is reverse of how we started */ unsigned int reverseBits2( unsigned int num ) { assert(sizeof(num) == 4); // this method will work only for 32 bits num = ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1); num = ((num & 0x33333333) << 2) | ((num & 0xCCCCCCCC) >> 2); num = ((num & 0x0F0F0F0F) << 4) | ((num & 0xF0F0F0F0) >> 4); num = ((num & 0x00FF00FF) << 8) | ((num & 0xFF00FF00) >> 8); num = ((num & 0x0000FFFF) << 16) | ((num & 0xFFFF0000) >> 16); return num; } std::string printBinary(unsigned int n) { std::stringstream ss; std::string bin; int count = 0; while(n) { ss << (n % 2); n /= 2; ++count; } bin = ss.str(); bin.append(32-count, '0'); std::reverse(bin.begin(), bin.end()); return bin; } int main() { std::cout << "Enter an unsigned number:"; unsigned int n; std::cin >> n; std::cout << "Binary representation of entered number : " << printBinary(n) << std::endl; std::cout << "Reversing bits of entered number\n"; n = reverseBits1(n); std::cout << "Binary representation of number when bits are reversed: " << printBinary(n) << std::endl; std::cout << "Reversing bits again\n"; n = reverseBits2(n); std::cout << "Binary representation of number when bits are reversed: " << printBinary(n) << std::endl; return 0; }
6,026
C++
.cpp
171
32.818713
81
0.572357
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,918
check_if_power_of_4.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/check_if_power_of_4.cpp
/* * Check if a given number is power of 4 or not. * * Approach: If a value is power of 4, it has to be power of 2 and * it will have set bits at even position (as the number is power of 2, it will have * only one set bit.) For example: * 4 (0100) * 16 (0001 0000) * 64 (0100 0000) * If a number is power of 2 then it would have only one set bit and that set * bit would be reset by the expression (n & (n-1)), thus if (n & (n-1)) == 0, * means n is power of 2. * Now, since we have one set bit and if it is at even position it would be * power of 4, to check if set bit is at even position, we should AND it with * expression 1010 1010 1010 1010 1010 1010 1010 1010 i.e. 0xAAAAAAAA. Notice we have * set bits at all odd positions (it is 0 indexed), thus if expression * (n & 0xAAAAAAAA) == 0, then we have that set bit at even position. */ #include <iostream> bool isPowerOf4 (unsigned int n) { // The number should be power of 2, and should have set bit at even position // return (n && !(n & (n-1)) && !(n & 0xAAAAAAAA)); //note an alternative that avoids the last negation could be //return (n && !(n & (n-1)) && (n & 0x55555555)); } int main() { unsigned int n; std::cout << "Enter a number:"; std::cin >> n; if (isPowerOf4(n)) { std::cout << n << " is a power of 4.\n"; } else { std::cout << n << " is not a power of 4.\n"; } }
1,497
C++
.cpp
41
31.536585
86
0.604138
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,919
next_power_of_2.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/next_power_of_2.cpp
/* * Write a function that, for a given no n, finds a number p which is greater than or equal to n and is a power of 2. */ #include <iostream> int next_power_of_2( int num ) { //already a power of 2 if (num && !(num & (num-1))) { return num; } //count till msb set bit int count = 0; while ( num != 0 ) { num >>= 1; count++; } return (1 << count); } int main() { std::cout << "Enter a number:"; int num; std::cin >> num; std::cout << "Next power of 2 which is greater than or equal to " << num << " is: " << next_power_of_2(num) << std::endl; return 0; }
637
C++
.cpp
26
20.346154
118
0.553542
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
25,920
swapBits.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/swapBits.cpp
#include <iostream> #include <bitset> int swapBits(int n, int p, int q) { if (p == q) { return n; } // If bits are same, no point swapping. // Determine if bits are different // if (((n & (1 << p)) >> p) ^ ((n & (1 << q)) >> q)) { // toggle bits at p and q positions // n ^= (1 << p); n ^= (1 << q); } return n; } int main() { int n, p, q; std::cout << "Enter a number: "; std::cin >> n; std::cout << "Enter bit position 1:"; std::cin >> p; std::cout << "Enter bit position 2:"; std::cin >> q; int r = swapBits(n, p, q); std::cout << "Number before swap :" << n << " (" << std::bitset<8>(n).to_string() << ") " << std::endl << "Number after swapping bits at position " << p << " and " << q << " : " << r << " (" << std::bitset<8>(r) << ")" << std::endl; return 0; }
952
C++
.cpp
36
20.333333
94
0.434687
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,921
counter_game.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/counter_game.cpp
/* Louise and Richard play a game. They have a counter set to N. Louise gets the first turn and the turns alternate thereafter. In the game, they perform the following operations. If N is not a power of 2, reduce the counter by the largest power of 2 less than N. If N is a power of 2, reduce the counter by half of N. The resultant value is the new N which is again used for subsequent operations. The game ends when the counter reduces to 1, i.e., N == 1, and the last person to make a valid move wins. Given N, your task is to find the winner of the game. If they set counter to 1, Richard wins, because its Louise' turn and she cannot make a move. Input Format The first line contains an integer T, the number of testcases. T lines follow. Each line contains N, the initial number set in the counter. */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; bool isPowerOf2(unsigned long long int x) { return ( x && ((x &(x-1)) == 0)); } unsigned long long int lowerPowerof2( unsigned long long int x) { if (x == 0) { return 0; } x--; x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); x |= (x >> 32); return x - (x >> 1); } std::string winner( bool win ) { if (win) { return std::string("Louise"); } else { return std::string("Richard"); } } int main() { int T; unsigned long long int N; cin >> T; while(T) { cin >> N; if (N == 1) { std::cout << "Richard\n"; continue; } bool win = false; while(N > 1) { if (isPowerOf2(N)) { N = N/2; } else { N = N - lowerPowerof2(N); } win = !win; } std::cout << winner(win) << std::endl; --T; } return 0; }
1,938
C++
.cpp
65
24.138462
176
0.583514
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,922
power_of_2.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/power_of_2.cpp
/* * Given a number, determine if its power of 2 using bit manipulation in O(1) */ #include <iostream> bool powerOfTwo( int n ) { return (n > 0 && !( n & ( n - 1 ) )); } int main() { int n; std::cout << "Enter a number :"; std::cin >> n; if ( powerOfTwo(n) ) { std::cout << n << " is power of 2\n"; } else { std::cout << n << " is not power of 2\n"; } return 0; }
418
C++
.cpp
20
17.25
77
0.516456
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,923
addition_without_operators.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/addition_without_operators.cpp
/** * Addtion of two numbers without using any arithmatic operators. */ #include <iostream> int sum( int x, int y ) { int carry = 0; while( y != 0 ) { //if x and y don't have same bits at same position, XOR of x and y //gives us sum of x and y at those positions. // bits wont change at positions containing same bits, however, // we have to incorporate carry bits. AND of x and y gives all carry bits. // carry will be added from position 1 (not 0), so we need to shift carry // by 1. carry = x & y; x = x ^ y; y = carry << 1; } return x; } //recursive version int sum2( int x, int y ) { if ( y == 0 ) { return x; } return sum2( x ^ y, (x & y) << 1); } int main() { int x , y; std::cout << "Addition of two numbers without using arithmatic operators:\n"; std::cout << "Enter num 1 :" ; std::cin >> x; std::cout << "Enter num 2 :" ; std::cin >> y; std::cout << "Iterative version - Addition of " << x << " and " << y << " is " << sum(x, y) << std::endl; std::cout << "Recursive version - Addition of " << x << " and " << y << " is " << sum2(x, y) << std::endl; return 0; }
1,175
C++
.cpp
40
25.825
79
0.573828
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,925
right_most_set_bit.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/right_most_set_bit.cpp
/** * Problem : One line function to return the position of right most bit. * Approach : take 2's compliment and it with number. * And finally taking a log of 2 + 1 will give us the position */ #include <iostream> #include <cmath> int position_of_first_set_bit( int num ) { return log2(num & -num) + 1; } int main() { int num; std::cout << "Enter a number :"; std::cin >> num; std::cout << "Position of first set bit number in binary representation of " << num << " is " << position_of_first_set_bit( num ) << std::endl; return 0; }
582
C++
.cpp
21
24.571429
78
0.638489
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
25,926
swapSetOfBits.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/swapSetOfBits.cpp
/** * Problem - Given a number 'num' and two positions (p1 and p2 from right side) in binary representation of num, * write a function that swaps n bits at given two positions and returns the result. * It is also given that the two sets of bits do not overlap. */ #include <iostream> int swapBits(unsigned int num, unsigned int p1, unsigned int p2, unsigned int n ) { //Step1 lets form a number set1 by moving n bits at position p1 to the rightmost unsigned int set1 = (num >> p1 ) & ((1U << n) - 1); // Lets understand what we just did. // Part1 : (num >> p1), we just right shifted num so that bit at p1 position takes 0th postion. // Part2 : Remember we needed n bits from position p1(which has become position 0) // So, (1U << n) moves 1 to nth bit, i.e. it the value formed by this movement is 2^n // Now, If we substract 1 from the (2^n), it will give us all 1's for n positions. // For example (1U << 3) = 1000 // and (1U << 3) - 1 = 0111 // Part3 : Thus Part1 & Part2 will give as n bits which were at P1 (now moved to 0) //similarly for p2 unsigned int set2 = (num >> p2) & ((1U << n) - 1); // xor two sets ( we are doing similar to xor swap algorithm ) // https://en.wikipedia.org/wiki/XOR_swap_algorithm unsigned int xorSets = set1 ^ set2; // now moving back the xor'd sets to p1 and p2 xorSets = (xorSets << p1) | (xorSets << p2); unsigned int finalVal = xorSets ^ num; return finalVal; } int main() { std::cout << "Swaping bits in number 28, such that 2 bits starting from 0th bit and 2 bits " "starting from 3rd bit are swapped, 28 becomes " << swapBits(28, 0, 3, 2) << std::endl; std::cout << "Swaping bits in number 47, such that 3 bits starting from 1st bit(0 based counting) and 3 bits " "starting from 5th bit(0 based counting) are swapped, 47 becomes " << swapBits(47, 1, 5, 3) << std::endl; }
1,977
C++
.cpp
38
47.684211
112
0.645262
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,927
countNumberOfBitFlips.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/countNumberOfBitFlips.cpp
/** * Given two numbers A and B, count number of flips required to convert number A to B * Approach : Take XOR of A and B, the result will contain set bits only at positions * where A differed B. Therefore number of set bits in the result of A ^ B is the number * of flips required to convert A to B */ #include <iostream> int countSetBits( int x ) { int count = 0; while( x ) { ++count; x = x & (x - 1); } return count; } int countBitFlips( int a, int b ) { return countSetBits(a ^ b); } int main() { int x, y; std::cout << "Enter number 1 :"; std::cin >> x; std::cout << "Enter number 2 :"; std::cin >> y; std::cout << "Bit flips required to convert " << x << " to " << y << " is " << countBitFlips(x, y) << std::endl; return 0; }
790
C++
.cpp
31
22.774194
89
0.617219
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,928
reverseEndianness.cpp
mandliya_algorithms_and_data_structures/bit_manipulation/reverseEndianness.cpp
#include <iostream> #include <cstdio> enum endianess { LITTLE_ENDIAN_MACHINE = 0, BIG_ENDIAN_MACHINE }; endianess determine_endianess() { unsigned int num = 1; char * c = (char *) &num; if (*c == 1) { return LITTLE_ENDIAN_MACHINE; } else { return BIG_ENDIAN_MACHINE; } } void printBytes( char * start, int size) { for ( int i = 0; i < size; ++i ) { printf("%.2x ", start[i] ); } std::cout << std::endl; } int reverseEndianNess( int num ) { int byte1, byte2, byte3, byte4; byte1 = (num & 0x000000FF) >> 0; byte2 = (num & 0x0000FF00) >> 8; byte3 = (num & 0x00FF0000) >> 16; byte4 = (num & 0xFF000000) >> 24; return ((byte1 << 24) | (byte2 << 16) | (byte3 << 8) | (byte4 << 0)); } int main() { endianess sys_endianess = determine_endianess(); if (sys_endianess == LITTLE_ENDIAN_MACHINE) { std::cout << "System is little endian\n\n"; } else { std::cout << "System is big endian\n\n"; } int num = 0x01234567; std::cout << "Num in decimal: " << num << std::endl; std::ios::fmtflags f(std::cout.flags()); std::cout << "Num in hexadecimal:" << std::hex << num << std::endl; std::cout.flags( f ); std::cout << "Printing individual bytes:\n"; printBytes((char*)&num, sizeof(num)); std::cout << std::endl; std::cout << "Num in reversed endianness:\n"; int num1 = reverseEndianNess(num); std::cout << "Num in decimal :" << num1 << std::endl; f = std::cout.flags(); std::cout << "Num in hexadecimal:" << std::hex << num1 << std::endl; std::cout.flags( f ); std::cout << "Printing individual bytes:\n"; printBytes((char*)&num1, sizeof(num1)); return 0; }
1,720
C++
.cpp
57
26.140351
72
0.591103
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
25,929
1-2-edi5-reverseString.cpp
mandliya_algorithms_and_data_structures/cracking_the_coding_interview_problems/1-2-edi5-reverseString.cpp
/* * Cracking the coding interview edition *5* old one * 1.2 Reverse a string when you are a pass a null terminated C string. */ #include<iostream> #include<cstring> #include<generic.h> void reverse1( char * str) { int len = std::strlen(str); for ( int i = 0; i < len/2; ++i ) { algo::swap( str[i], str[len - i - 1] ); } } void reverse2( char *str ) { if ( !str ) return; char *p = str; char *q = str; while (*q) ++q; --q; //q now points to last char and p points to first char while ( p < q ) std::swap( *p++, *q-- ); } int main() { char str[] = "abcdefghijklmnopqrstuvwxyz"; reverse1(str); std::cout << "On reversing it once: " << str << std::endl; reverse2(str); std::cout << "On reversing it again: " << str << std::endl; return 0; }
837
C++
.cpp
34
20.764706
72
0.572682
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,930
1-3-edi5-removeDuplicates.cpp
mandliya_algorithms_and_data_structures/cracking_the_coding_interview_problems/1-3-edi5-removeDuplicates.cpp
/* * Cracking the coding interview, edition 5 * Problem 1.3 * Write an algorithm to remove duplicate chars from a string */ #include <iostream> #include <cstring> using std::string; using std::cin; using std::cout; using std::endl; /* * Function - removeDuplicates1 * Args - A string * Return - Arg string with no duplicate chars * Runtime - O(n) * Assumption - contains letter ( a - z ) */ string removeDuplicates1( const string & str ) { int len = str.length(); if ( len < 2 ) { return str; } int check = 0; string result(""); for ( auto & ch : str ) { int c = (int)( ch - 'a'); if ( (check & ( 1 << c )) == 0) { result += ch; check |= ( 1 << c); } } return result; } /* * Function - removeDuplicates2 * Args - A string * Return - Arg string with no duplicate chars * Runtime - O(n) * Assumption - ASCII extended char set */ string removeDuplicates2 ( const string & str ) { int len = str.length(); if ( len < 2 ) return str; string result(""); bool check[256]; for ( auto & ch : str ) { if ( !check[(int)ch] ) { check[(int)ch] = true; result += ch; } } return result; } /* * Function - removeDuplicates3 * Args - A string * Return - Arg string with no duplicate chars * Runtime - O(n^2) * Assumption - NONE */ string removeDuplicates3( string str ) { int len = str.length(); if ( len < 2 ) { return str; } string result(""); for ( int i = 0; i < len; ++i) { if ( str[i] != '\0' ) { result += str[i]; for ( int j = i + 1; j < len; ++j ) { if ( str[i] == str[j] ) { str[j] = '\0'; } } } } return result; } /* * Function - removeDuplicates4 * Args - A C string * Return - void, we change the char array we pass as arg * Runtime - O(n) * Assumption - contains letter ( a - z ) */ void removeDuplicates4( char * str ) { int len = std::strlen(str); if ( len < 2) { return; } int check = 0; int cindx = 0; for ( int i = 0; i < len; ++i) { int c = (int) ( str[i] - 'a'); if ( (check & ( 1 << c )) == 0 ) { str[cindx++] = str[i]; check |= ( 1 << c ); } } str[cindx] = '\0'; } /* * Function - removeDuplicates5 * Args - A c string * Return - void, we change the c-string we pass to function * Runtime - O(n^2) * Assumption - NONE */ void removeDuplicates5( char * str ) { int len = std::strlen(str); if ( len < 2 ) { return; } int idx = 0; for ( int i = 0; i < len; ++i) { if ( str[i] != '\0' ) { str[idx++] = str[i]; for ( int j = i + 1; j < len; ++j ) { if ( str[i] == str[j] ) { str[j] = '\0'; } } } } } /* * Function - removeDuplicates6 * Args - A c string * Return - void, we change the c-string we pass to function * Runtime - O(n) * Assumption - ASCII extended char set */ void removeDuplicates6 ( char *str ) { int len = std::strlen(str); if ( len < 2 ) return; bool check[256] = {false}; int idx = 0; for ( int i = 0; i < len; ++i ) { if ( !check[(int)str[i]] ) { check[(int)str[i]] = true; str[idx++] = str[i]; } } str[idx] = '\0'; } int main() { string str1("aaaabbbbbcddeffgheee"); string str2("abcd"); string str3("a"); string str4(""); cout << "For method 1:" << endl; cout << "original-string:" << str1 << " after removing duplicates:" << removeDuplicates1(str1) << endl; cout << "original-string:" << str2 << " after removing duplicates:" << removeDuplicates1(str2) << endl; cout << "original-string:" << str3 << " after removing duplicates:" << removeDuplicates1(str3) << endl; cout << "original-string:" << str4 << " after removing duplicates:" << removeDuplicates1(str4) << endl; cout << "\n\nFor method 2:" << endl; cout << "original-string:" << str1 << " after removing duplicates:" << removeDuplicates2(str1) << endl; cout << "original-string:" << str2 << " after removing duplicates:" << removeDuplicates2(str2) << endl; cout << "original-string:" << str3 << " after removing duplicates:" << removeDuplicates2(str3) << endl; cout << "original-string:" << str4 << " after removing duplicates:" << removeDuplicates2(str4) << endl; cout << "\n\nFor method 3:" << endl; cout << "original-string:" << str1 << " after removing duplicates:" << removeDuplicates3(str1) << endl; cout << "original-string:" << str2 << " after removing duplicates:" << removeDuplicates3(str2) << endl; cout << "original-string:" << str3 << " after removing duplicates:" << removeDuplicates3(str3) << endl; cout << "original-string:" << str4 << " after removing duplicates:" << removeDuplicates3(str4) << endl; cout << "\n\nFor method 4:" << endl; char str5[] = "aaaabbbbcccc"; char str6[] = "abcde"; char str7[] = "a"; char str8[] = ""; cout << endl; cout << "original-string:" << str5 << " after removing duplicates:"; removeDuplicates4(str5); cout << str5 << endl; cout << "original-string:" << str6 << " after removing duplicates:"; removeDuplicates4(str6); cout << str6 << endl; cout << "original-string:" << str7 << " after removing duplicates:"; removeDuplicates4(str7); cout << str7 << endl; cout << "original-string:" << str8 << " after removing duplicates:"; removeDuplicates4(str8); cout << str8 << endl; cout << "\n\nFor method 5:" << endl; char str9[] = "aaaabbbbccccdddeeefffaaabbb"; char str10[] = "abcdef"; char str11[] = "b"; char str12[] = ""; cout << endl; cout << "original-string:" << str9 << " after removing duplicates:"; removeDuplicates5(str9); cout << str9 << endl; cout << "original-string:" << str10 << " after removing duplicates:"; removeDuplicates5(str10); cout << str10 << endl; cout << "original-string:" << str11 << " after removing duplicates:"; removeDuplicates5(str11); cout << str11 << endl; cout << "original-string:" << str12 << " after removing duplicates:"; removeDuplicates5(str12); cout << str12 << endl; cout << "\n\nFor method 6:" << endl; char str13[] = "aaaabbbbccccdddeeefffaaabbb"; char str14[] = "abcdef"; char str15[] = "b"; char str16[] = ""; cout << endl; cout << "original-string:" << str13 << " after removing duplicates:"; removeDuplicates6(str13); cout << str13 << endl; cout << "original-string:" << str14 << " after removing duplicates:"; removeDuplicates6(str14); cout << str14 << endl; cout << "original-string:" << str15 << " after removing duplicates:"; removeDuplicates6(str15); cout << str15 << endl; cout << "original-string:" << str16 << " after removing duplicates:"; removeDuplicates6(str16); cout << str16 << endl; cout << endl; return 0; }
7,246
C++
.cpp
233
25.841202
108
0.556432
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,931
1-1-hasUniqueChars.cpp
mandliya_algorithms_and_data_structures/cracking_the_coding_interview_problems/1-1-hasUniqueChars.cpp
/* * Cracking the coding interview, edition 6 * Problem 1.1 * Write an algorithm to determine whether a string has unique characters or not * Can we do it without using additional data structures? */ #include <iostream> #include <cstring> /* * Function hasUniqueChars1 * Args - std::string * Output:: True if string has all characters which are unique * False if string has at least one repeated char. * Assumption:: ASCII chars, 256 chars. */ bool hasUniqueChars1( std::string str) { int len = str.length(); int check[8]; //represents 256 bits. std::memset( check, 0 , sizeof check ); int idx, v, shift; for ( int i = 0; i < len; ++i) { v = (int) str[i]; idx = v / 32; //identify which int bucket will represent this char shift = v % 32; //identify which bit in above int will represent the char if ( check[idx] & ( 1 << shift ) ) { return false; } check[idx] |= ( 1 << shift ); } return true; } /* * Function hasUniqueChars2 * Args - std::string * Output:: True if string has all characters which are unique * False if string has at least one repeated char. * Assumption:: string only contains (a..z), 26 chars. */ bool hasUniqueChars2( std::string str) { int check = 0; int len = str.length(); for (int i = 0; i < len; ++i) { int c = (int)(str[i] - 'a'); if ( check & ( 1 << c ) ) { return false; } check |= ( 1 << c); } return true; } int main () { std::string word1("copyrightable"); std::string word2("Dermatoglyphics!"); std::string word3("abiogenesis"); std::string word4("Centrobaric!"); //a word with unique chars (a-z) std::cout << "Does " << word1 << " has unique chars :" << hasUniqueChars2(word1) << std::endl; //a word with unique ASCII chars std::cout << "Does " << word2 << " has unique chars :" << hasUniqueChars1(word2) << std::endl; //a word with repeated chars (a-z) std::cout << "Does " << word3 << " has unique chars :" << hasUniqueChars2(word3) << std::endl; //a word with repeated AsCII chars std::cout << "Does " << word4 << " has unique chars :" << hasUniqueChars1(word4) << std::endl; return 0; }
2,297
C++
.cpp
69
28.724638
98
0.606431
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,936
2-4-partition.cpp
mandliya_algorithms_and_data_structures/cracking_the_coding_interview_problems/2-4-partition.cpp
/** * Cracking the coding interview edition 6 * Problem 2.4 Partition: * Write code to partition linked list around a value x, such that * nodes less than x come before all the nodes greater than or equal to x. * If x is in the list, the values of x only need to be after the elements less * than x. * Example * 3-->5-->8-->5-->10-->2-->1 (x = 5) * 3-->1-->2-->10-->5-->5-->8 * * Approach: * Start with first node, and add every thing bigger or equal to x at tail * and smaller values at head. */ #include <iostream> #include <random> struct Node { int data; Node * next; Node( int d ) : data{ d }, next{ nullptr } { } }; /** * [insert - helper routine to insert a new node with data] * @param head [head of the list] * @param data [data of the new node] */ void insert( Node * & head, int data ) { Node * newNode = new Node(data); if ( head == nullptr ) { head = newNode; } else { Node * curr = head; while( curr->next ) { curr = curr->next; } curr->next = newNode; } } /** * [printList - helper routine to print the list] * @param head [head of the list] */ void printList( Node * head ) { while ( head ) { std::cout << head->data << "-->"; head = head->next; } std::cout << "nullptr" << std::endl; } /** * [partition - routine to partition list around x] * @param head [head of the list] * @param x [data around which partition is being done] */ void partition( Node * & head , int x ) { Node * tail = head; Node * curr = head; while( curr != nullptr ) { Node * nextNode = curr->next; if ( curr->data < x ) { //insert at head curr->next = head; head = curr; } else { // insert at tail tail->next = curr; tail = curr; } curr = nextNode; } tail->next = nullptr; } /** * [random_range helper routine to generate a random number between min and max (including)] * @param min [min of range] * @param max [max of range] * @return [A random number between min and max] */ static inline int random_range(const int min, const int max) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> distribution(min, max); return distribution(mt); } int main() { Node * head = nullptr; for ( int i = 0; i < 10; ++i ) { insert(head, random_range(1,9)); } std::cout << "List before partition around 5:\n"; printList(head); partition(head, 5); std::cout << "List after partition around 5:\n"; printList(head); return 0; }
2,535
C++
.cpp
97
23.257732
92
0.623302
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false