text
stringlengths
2
104M
meta
dict
// https://www.hackerrank.com/challenges/cpp-hello-world/problem #include <iostream> #include <cstdio> using namespace std; int main() { std::cout << "Hello, World!" << std::endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-conditional-if-else/problem #include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main(){ int n; cin >> n; // your code goes here if (n < 1) return 2; const char *digits[] = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; if (n < 10) cout << digits[n] << endl; else cout << "Greater than 9" << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(c-tutorial-for-loop c-tutorial-for-loop.cpp) add_hackerrank(cpp-input-and-output cpp-input-and-output.cpp) add_hackerrank(cpp-hello-world cpp-hello-world.cpp) add_hackerrank(c-tutorial-conditional-if-else c-tutorial-conditional-if-else.cpp) add_hackerrank(c-tutorial-pointer c-tutorial-pointer.cpp) add_hackerrank(c-tutorial-functions c-tutorial-functions.cpp) add_hackerrank(variable-sized-arrays variable-sized-arrays.cpp) add_hackerrank(arrays-introduction arrays-introduction.cpp) add_hackerrank(c-tutorial-basic-data-types c-tutorial-basic-data-types.cpp)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-basic-data-types/problem #include <iostream> #include <cstdio> using namespace std; int main() { // Complete the code. int a; long b; char c; float f; double d; if (5 == scanf("%d %ld %c %f %lf", &a, &b, &c, &f, &d)) printf("%d\n%ld\n%c\n%.3f\n%.9lf\n", a, b, c, f, d); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-for-loop/problem #include <iostream> #include <cstdio> using namespace std; int main() { // Complete the code. const char *digits[] = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; int n1, n2; cin >> n1 >> n2; for (int n = n1; n <= n2; ++n) { if (n < 1) { // rien } else if (n <= 9) cout << digits[n] << endl; else if (n % 2 == 0) cout << "even" << endl; else cout << "odd" << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-pointer/problem #include <stdio.h> void update(int *a,int *b) { // Complete this function int c = *a + *b; int d = *a - *b; *a = c; *b = d >= 0 ? d : -d; } int main() { int a, b; int *pa = &a, *pb = &b; scanf("%d %d", &a, &b); update(pa, pb); printf("%d\n%d", a, b); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-functions/problem #include <iostream> #include <cstdio> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max_of_four(int a, int b, int c, int d) { if (b > a) a = b; if (c > a) a = c; if (d > a) a = d; return a; } int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [C++](https://www.hackerrank.com/domains/cpp) A general-purpose programming language with imperative, object-oriented and generic programming features. #### [Introduction](https://www.hackerrank.com/domains/cpp/cpp-introduction) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Say "Hello, World!" With C++](https://www.hackerrank.com/challenges/cpp-hello-world)|Practice printing to stdout.|[C++](cpp-hello-world.cpp)|Easy [Input and Output](https://www.hackerrank.com/challenges/cpp-input-and-output)|Learn to take in the input and print the output. Take three number as input and print their sum as output.|[C++](cpp-input-and-output.cpp)|Easy [Basic Data Types](https://www.hackerrank.com/challenges/c-tutorial-basic-data-types)|Learn about the basic data types in C++. Take the given input and print them.|[C++](c-tutorial-basic-data-types.cpp)|Easy [Conditional Statements](https://www.hackerrank.com/challenges/c-tutorial-conditional-if-else)|Practice using chained conditional statements.|[C++](c-tutorial-conditional-if-else.cpp)|Easy [For Loop](https://www.hackerrank.com/challenges/c-tutorial-for-loop)|Learn how to use for loop and print the output as per the given conditions|[C++](c-tutorial-for-loop.cpp)|Easy [Functions](https://www.hackerrank.com/challenges/c-tutorial-functions)|Learn how to write functions in C++. Create a function to find the maximum of the four numbers.|[C++](c-tutorial-functions.cpp)|Easy [Pointer](https://www.hackerrank.com/challenges/c-tutorial-pointer)|Learn how to declare pointers and use them.|[C++](c-tutorial-pointer.cpp)|Easy [Arrays Introduction](https://www.hackerrank.com/challenges/arrays-introduction)|How to access and use arrays. Print the array in the reverse order.|[C++](arrays-introduction.cpp)|Easy [Variable Sized Arrays](https://www.hackerrank.com/challenges/variable-sized-arrays)|Find the element described in the query for integer sequences.|[C++](variable-sized-arrays.cpp)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/cpp-input-and-output/problem #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int a,b,c; scanf("%d %d %d",&a,&b,&c); printf("%d\n",a+b+c); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/c-tutorial-stringstream/problem #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(const string& str) { // Complete this function stringstream ss(str); vector<int> v; while (! ss.eof()) { int i; ss >> i; v.push_back(i); char c; ss >> c; if (c != ',') break; } return v; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); for(size_t i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/attribute-parser/problem #include <cmath> #include <cstdio> #include <sstream> #include <iostream> #include <algorithm> #include <map> using namespace std; /*** std::string& ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); return str; } std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); return str; } std::string& trim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { return ltrim(rtrim(str, chars), chars); } ***/ class HrmlDoc { string path_; map<string, string> attributes_; public: void operator<<(const string& s) { if (s.compare(0, 2, "</") == 0) { //string tag = s.substr(2, s.find('>', 2) - 2); path_.resize(path_.rfind('.')); } else { string::size_type p, q; p = s.find(' ', 2); if (p == string::npos) { p = s.find('>', 2); path_ += "." + s.substr(1, p - 1); } else { path_ += "." + s.substr(1, p - 1); ++p; while ((q = s.find(" = ", p)) != string::npos) { string attr = s.substr(p, q - p); p = s.find('"', q) + 1; q = s.find('"', p); string value = s.substr(p, q - p); attributes_[path_.substr(1) + "~" + attr] = value; p = q + 2; } } } } string query(const string& path) const { const auto& i = attributes_.find(path); if (i == attributes_.end()) return "Not Found!"; else return i->second; } }; int main() { int N, Q; string s; HrmlDoc hrml; stringstream ss; getline(cin, s); ss << s; ss >> N >> Q; while (N--) { getline(cin, s); hrml << s; } while (Q--) { getline(cin, s); cout << hrml.query(s) << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Strings // // https://www.hackerrank.com/challenges/c-tutorial-strings/problem #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { // Complete the program string a, b; cin >> a; cin >> b; cout << a.size() << " " << b.size() << endl; cout << a + b << endl; std::swap(a[0], b[0]); cout << a << " " << b << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(attribute-parser attribute-parser.cpp) add_hackerrank(c-tutorial-stringstream c-tutorial-stringstream.cpp) add_hackerrank(c-tutorial-strings c-tutorial-strings.cpp)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [C++](https://www.hackerrank.com/domains/cpp) A general-purpose programming language with imperative, object-oriented and generic programming features. #### [Strings](https://www.hackerrank.com/domains/cpp/cpp-strings) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Strings](https://www.hackerrank.com/challenges/c-tutorial-strings)|Learn how to input and output strings.|[C++](c-tutorial-strings.cpp)|Easy [StringStream](https://www.hackerrank.com/challenges/c-tutorial-stringstream)|Learn how to use stringstreams.|[C++](c-tutorial-stringstream.cpp)|Easy [Attribute Parser](https://www.hackerrank.com/challenges/attribute-parser)|Parse the values within various tags.|[C++](attribute-parser.cpp)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# https://www.hackerrank.com/domains/data-structures add_subdirectory(arrays) add_subdirectory(trees) add_subdirectory(linked-lists) add_subdirectory(trie) add_subdirectory(heap) add_subdirectory(stacks) add_subdirectory(queues)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Arrays](https://www.hackerrank.com/domains/data-structures/arrays) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Arrays - DS](https://www.hackerrank.com/challenges/arrays-ds)|Accessing and using arrays.|[C++](arrays/arrays-ds.cpp) [Python](arrays/arrays-ds.py)|Easy [2D Array - DS](https://www.hackerrank.com/challenges/2d-array)|How to access and use 2d-arrays.|[Python](arrays/2d-array.py)|Easy [Dynamic Array](https://www.hackerrank.com/challenges/dynamic-array)|Learn to use dynamic arrays by solving this problem.|[Python](arrays/dynamic-array.py)|Easy [Left Rotation](https://www.hackerrank.com/challenges/array-left-rotation)|Given an array and a number, d, perform d left rotations on the array.|[Python](arrays/array-left-rotation.py)|Easy [Sparse Arrays](https://www.hackerrank.com/challenges/sparse-arrays)|Determine the number of times a string has previously appeared.|[Python](arrays/sparse-arrays.py)|Medium [Array Manipulation](https://www.hackerrank.com/challenges/crush)|Perform m operations on an array and print the maximum of the values.|[Python](arrays/crush.py)|Hard #### [Linked Lists](https://www.hackerrank.com/domains/data-structures/linked-lists) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Print the Elements of a Linked List](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list)|Get started with Linked Lists!|[C++](linked-lists/print-the-elements-of-a-linked-list.cpp)|Easy [Insert a Node at the Tail of a Linked List](https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list)|Create and insert a new node at the tail of a linked list.|[C++](linked-lists/insert-a-node-at-the-tail-of-a-linked-list.cpp)|Easy [Insert a node at the head of a linked list](https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list)|Create and insert a new node at the head of a linked list|[C++](linked-lists/insert-a-node-at-the-head-of-a-linked-list.cpp)|Easy [Insert a node at a specific position in a linked list](https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list)|Insert a node at a specific position in a linked list.|[C++](linked-lists/insert-a-node-at-a-specific-position-in-a-linked-list.cpp)|Easy [Delete a Node](https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list)|Delete a node from the linked list and return the head.|[C++](linked-lists/delete-a-node-from-a-linked-list.cpp)|Easy [Print in Reverse](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse)|Print the elements of a linked list in reverse order, from tail to head|[C++](linked-lists/print-the-elements-of-a-linked-list-in-reverse.cpp)|Easy [Reverse a linked list](https://www.hackerrank.com/challenges/reverse-a-linked-list)|Change the links between the nodes of a linked list to reverse it|[C++](linked-lists/reverse-a-linked-list.cpp)|Easy [Compare two linked lists](https://www.hackerrank.com/challenges/compare-two-linked-lists)|Compare the data in two linked lists node by node to see if the lists contain identical data.|[C++](linked-lists/compare-two-linked-lists.cpp)|Easy [Merge two sorted linked lists](https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists)|Given the heads of two sorted linked lists, change their links to get a single, sorted linked list.|[C++](linked-lists/merge-two-sorted-linked-lists.cpp)|Easy [Get Node Value](https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail)|Given the head of a linked list, get the value of the node at a given position when counting backwards from the tail.|[Python](linked-lists/get-the-value-of-the-node-at-a-specific-position-from-the-tail.py)|Easy [Delete duplicate-value nodes from a sorted linked list](https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list)|Given a linked list whose nodes have data in ascending order, delete some nodes so that no value occurs more than once.|[C++](linked-lists/delete-duplicate-value-nodes-from-a-sorted-linked-list.cpp)|Easy [Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle)|Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself|[C++](linked-lists/detect-whether-a-linked-list-contains-a-cycle.cpp)|Medium [Find Merge Point of Two Lists](https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists)|Given two linked lists, find the node where they merge into one.|[C++](linked-lists/find-the-merge-point-of-two-joined-linked-lists.cpp)|Easy [Inserting a Node Into a Sorted Doubly Linked List](https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list)|Create a node with a given value and insert it into a sorted doubly-linked list|[C++](linked-lists/insert-a-node-into-a-sorted-doubly-linked-list.cpp)|Easy [Reverse a doubly linked list](https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list)|Given the head node of a doubly linked list, reverse it.|[Python](linked-lists/reverse-a-doubly-linked-list.py)|Easy #### [Trees](https://www.hackerrank.com/domains/data-structures/trees) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Tree: Preorder Traversal](https://www.hackerrank.com/challenges/tree-preorder-traversal)|Print the preorder traversal of a binary tree.|[C++](trees/tree-preorder-traversal.cpp)|Easy [Tree: Postorder Traversal](https://www.hackerrank.com/challenges/tree-postorder-traversal)|Print the post order traversal of a binary tree.|[C++](trees/tree-postorder-traversal.cpp)|Easy [Tree: Inorder Traversal](https://www.hackerrank.com/challenges/tree-inorder-traversal)|Print the inorder traversal of a binary tree.|[C++](trees/tree-inorder-traversal.cpp)|Easy [Tree: Height of a Binary Tree](https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree)|Given a binary tree, print its height.|[C++](trees/tree-height-of-a-binary-tree.cpp) [Python](trees/tree-height-of-a-binary-tree.py)|Easy [Tree : Top View](https://www.hackerrank.com/challenges/tree-top-view)|Given a binary tree, print it's top view.|[C++](trees/tree-top-view.cpp)|Easy [Tree: Level Order Traversal](https://www.hackerrank.com/challenges/tree-level-order-traversal)|Level order traversal of a binary tree.|[C++](trees/tree-level-order-traversal.cpp)|Easy [Binary Search Tree : Insertion](https://www.hackerrank.com/challenges/binary-search-tree-insertion)|Given a number, insert it into it's position in a binary search tree.|[C++](trees/binary-search-tree-insertion.cpp)|Easy [Tree: Huffman Decoding ](https://www.hackerrank.com/challenges/tree-huffman-decoding)|Given a Huffman tree and an encoded binary string, you have to print the original string.|[C++](trees/tree-huffman-decoding.cpp)|Medium [Binary Search Tree : Lowest Common Ancestor](https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor)|Given two nodes of a binary search tree, find the lowest common ancestor of these two nodes.|[C++](trees/binary-search-tree-lowest-common-ancestor.cpp)|Easy [Array Pairs](https://www.hackerrank.com/challenges/array-pairs)|Count the number of pairs satisfying a condition.|[Python](trees/array-pairs.py)|Advanced #### [Stacks](https://www.hackerrank.com/domains/data-structures/stacks) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Maximum Element](https://www.hackerrank.com/challenges/maximum-element)|Given three types of queries, insert an element, delete an element or find the maximum element in a stack.|[C++](stacks/maximum-element.cpp)|Easy [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets)|Given a string containing three types of brackets, determine if it is balanced.|[Python](stacks/balanced-brackets.py)|Medium [Equal Stacks](https://www.hackerrank.com/challenges/equal-stacks)|Equalize the piles!|[Python](stacks/equal-stacks.py)|Easy [Largest Rectangle ](https://www.hackerrank.com/challenges/largest-rectangle)|Given n buildings, find the largest rectangular area possible by joining consecutive K buildings.|[Python](stacks/largest-rectangle.py)|Medium [Simple Text Editor](https://www.hackerrank.com/challenges/simple-text-editor)|Implement a simple text editor and perform some number of operations.|[Python](stacks/simple-text-editor.py)|Medium #### [Queues](https://www.hackerrank.com/domains/data-structures/queues) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Queue using Two Stacks](https://www.hackerrank.com/challenges/queue-using-two-stacks)|Create a queue data structure using two stacks.|[Python](queues/queue-using-two-stacks.py)|Medium #### [Heap](https://www.hackerrank.com/domains/data-structures/heap) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [QHEAP1](https://www.hackerrank.com/challenges/qheap1)|Solve the basic heap question with insertion and deletion.|[Python](heap/qheap1.py)|Easy [Jesse and Cookies](https://www.hackerrank.com/challenges/jesse-and-cookies)|Calculate the number of operations needed to increase the sweetness of the cookies so that each cookie in the collection has a sweetness >=K.|[Python](heap/jesse-and-cookies.py)|Easy [Find the Running Median](https://www.hackerrank.com/challenges/find-the-running-median)|Find the median of the elements after inputting each element.|[Python](heap/find-the-running-median.py)|Hard #### [Trie](https://www.hackerrank.com/domains/data-structures/trie) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Contacts](https://www.hackerrank.com/challenges/contacts)|Create a Contacts application with the two basic operations: add and find.|[Python](trie/contacts.py)|Medium [No Prefix Set](https://www.hackerrank.com/challenges/no-prefix-set)|Given N strings, find if a string is a prefix of another string.|[Python](trie/no-prefix-set.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Contacts # Create a Contacts application with the two basic operations: add and find. # # https://www.hackerrank.com/challenges/contacts/problem # # Nota: il y a trop de noms pour se contenter d'un algo trivial de recherche dans contacts import bisect contacts = [] for _ in range(int(input())): op, contact = input().split() if op == "add": bisect.insort(contacts, contact) elif op == "find": position = bisect.bisect_left(contacts, contact) n = 0 while position < len(contacts) and contacts[position].startswith(contact): position += 1 n += 1 print(n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(contacts.py) add_hackerrank_py(no-prefix-set.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# No Prefix Set # Given N strings, find if a string is a prefix of another string. # # https://www.hackerrank.com/challenges/no-prefix-set/problem # import bisect def main(): arr = [] for _ in range(int(input())): s = input() p = bisect.bisect_right(arr, s) if p >= 1 and s.startswith(arr[p - 1]): print("BAD SET") print(s) return if p < len(arr) and arr[p].startswith(s): print("BAD SET") print(s) return arr.insert(p, s) print("GOOD SET") main()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Trie](https://www.hackerrank.com/domains/data-structures/trie) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Contacts](https://www.hackerrank.com/challenges/contacts)|Create a Contacts application with the two basic operations: add and find.|[Python](contacts.py)|Medium [No Prefix Set](https://www.hackerrank.com/challenges/no-prefix-set)|Given N strings, find if a string is a prefix of another string.|[Python](no-prefix-set.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Arrays - DS # Accessing and using arrays. # # https://www.hackerrank.com/challenges/arrays-ds/problem # # avec certains langages, c'est peut-être plus challengant qu'en Python... input() print(' '.join(map(str, reversed(list(map(int, input().split()))))))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// https://www.hackerrank.com/challenges/arrays-ds/problem #include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main(){ size_t n; cin >> n; vector<int> arr(n); for(size_t arr_i = 0;arr_i < n;arr_i++){ cin >> arr[arr_i]; } for (auto i = arr.rbegin(); i != arr.rend(); ++i) cout << *i << " "; cout << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# 2D Array - DS # How to access and use 2d-arrays. # # https://www.hackerrank.com/challenges/2d-array/problem # def array2D(arr): resulat = -100 for i in range(0, 4): for j in range(0, 4): s = sum(arr[i][j:j + 3]) s += arr[i + 1][j + 1] s += sum(arr[i + 2][j:j + 3]) if s > resulat: resulat = s return resulat if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().split()))) result = array2D(arr) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Left Rotation # Given an array and a number, d, perform d left rotations on the array. # # https://www.hackerrank.com/challenges/array-left-rotation/problem # def rotate(l, n): n = n % len(l) return l[n:] + l[:n] if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().split())) a = rotate(a, d) print(' '.join(map(str, a)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(sparse-arrays.py) add_hackerrank_py(2d-array.py) add_hackerrank_py(crush.py) add_hackerrank_py(array-left-rotation.py) add_hackerrank_py(dynamic-array.py) add_hackerrank(arrays-ds arrays-ds.cpp) add_hackerrank_py(arrays-ds.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Array Manipulation https://www.hackerrank.com/challenges/crush/problem """ if __name__ == "__main__": n, m = input().split(' ') n, m = int(n), int(m) data = [0] * (n + 2) vmax = 0 """ BRUTE FORCE for a0 in range(m): a, b, k = input().split(' ') a, b, k = int(a), int(b), int(k) for i in range(a, b + 1): v = data[i] + k data[i] = v if v > vmax: vmax = v """ # au lieu de faire +k à chaque fois entre [a,b] # on mémorise les changements (+k à a et -k après b) # et on fait la somme une seule fois for a0 in range(m): a, b, k = input().split(' ') a, b, k = int(a), int(b), int(k) data[a] += k data[b + 1] -= k v = 0 for i in range(1, n + 1): v += data[i] if v > vmax: vmax = v print(vmax)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Sparse Arrays # Determine the number of times a string has previously appeared. # # https://www.hackerrank.com/challenges/sparse-arrays/problem # from collections import defaultdict strings = defaultdict(lambda: 0) for _ in range(int(input())): strings[input()] += 1 for _ in range(int(input())): print(strings[input()])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Dynamic Array # Learn to use dynamic arrays by solving this problem. # # https://www.hackerrank.com/challenges/dynamic-array/problem # def dynamicArray(n, queries): last_answer = 0 seq = [[] for _ in range(n)] for q in queries: op, x, y = q if op == 1: seq[(x ^ last_answer) % n].append(y) elif op == 2: s = seq[(x ^ last_answer) % n] last_answer = s[y % len(s)] print(last_answer) if __name__ == '__main__': n, q = map(int, input().split()) queries = [] for _ in range(q): queries.append(list(map(int, input().split()))) dynamicArray(n, queries)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Arrays](https://www.hackerrank.com/domains/data-structures/arrays) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Arrays - DS](https://www.hackerrank.com/challenges/arrays-ds)|Accessing and using arrays.|[C++](arrays-ds.cpp) [Python](arrays-ds.py)|Easy [2D Array - DS](https://www.hackerrank.com/challenges/2d-array)|How to access and use 2d-arrays.|[Python](2d-array.py)|Easy [Dynamic Array](https://www.hackerrank.com/challenges/dynamic-array)|Learn to use dynamic arrays by solving this problem.|[Python](dynamic-array.py)|Easy [Left Rotation](https://www.hackerrank.com/challenges/array-left-rotation)|Given an array and a number, d, perform d left rotations on the array.|[Python](array-left-rotation.py)|Easy [Sparse Arrays](https://www.hackerrank.com/challenges/sparse-arrays)|Determine the number of times a string has previously appeared.|[Python](sparse-arrays.py)|Medium [Array Manipulation](https://www.hackerrank.com/challenges/crush)|Perform m operations on an array and print the maximum of the values.|[Python](crush.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Jesse and Cookies # Calculate the number of operations needed to increase the sweetness of the cookies so that each cookie in the collection has a sweetness >=K. # # https://www.hackerrank.com/challenges/jesse-and-cookies/problem # import heapq def cookies(k, A): stack = sorted(A) heapq.heapify(stack) op = 0 while stack[0] < k and len(stack) >= 2: a = heapq.heappop(stack) a = a + 2 * heapq.heappop(stack) heapq.heappush(stack, a) op += 1 if stack[0] < k: return -1 return op if __name__ == '__main__': n, k = map(int, input().split()) A = list(map(int, input().split())) op = cookies(k, A) print(op)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# QHEAP1 # Solve the basic heap question with insertion and deletion. # # https://www.hackerrank.com/challenges/qheap1/problem # from heapq import heappush, heapify, heappop q = [] q2 = [] for _ in range(int(input())): op = list(map(int, input().split())) # add if op[0] == 1: heappush(q, op[1]) # del elif op[0] == 2: #q.remove(op[1]) #heapify(q) heappush(q2, op[1]) # print elif op[0] == 3: #print(q[0]) while len(q2) > 0 and q[0] == q2[0]: heappop(q) heappop(q2) print(q[0])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(find-the-running-median.py) add_hackerrank_py(qheap1.py) add_hackerrank_py(jesse-and-cookies.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Find the Running Median # Find the median of the elements after inputting each element. # # https://www.hackerrank.com/challenges/find-the-running-median/problem # import bisect a = [] for _ in range(int(input())): n = int(input()) bisect.insort(a, n) m = (a[(len(a) - 1) // 2] + a[len(a) // 2]) / 2 print("%.1f" % m)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Heap](https://www.hackerrank.com/domains/data-structures/heap) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [QHEAP1](https://www.hackerrank.com/challenges/qheap1)|Solve the basic heap question with insertion and deletion.|[Python](qheap1.py)|Easy [Jesse and Cookies](https://www.hackerrank.com/challenges/jesse-and-cookies)|Calculate the number of operations needed to increase the sweetness of the cookies so that each cookie in the collection has a sweetness >=K.|[Python](jesse-and-cookies.py)|Easy [Find the Running Median](https://www.hackerrank.com/challenges/find-the-running-median)|Find the median of the elements after inputting each element.|[Python](find-the-running-median.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Queue using Two Stacks # Create a queue data structure using two stacks. # # https://www.hackerrank.com/challenges/queue-using-two-stacks/problem # in_stack = [] out_stack = [] for _ in range(int(input())): op = list(map(int, input().split())) # push back if op[0] == 1: in_stack.append(op[1]) # pop front elif op[0] == 2: if len(out_stack) > 0: # vide la stack de sortie out_stack.pop() else: # transvase la stack d'entrée vers la stack de sortie while len(in_stack) > 1: out_stack.append(in_stack.pop()) in_stack.pop() # print elif op[0] == 3: if len(out_stack) == 0: while len(in_stack) > 0: out_stack.append(in_stack.pop()) print(out_stack[-1])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(queue-using-two-stacks.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Queues](https://www.hackerrank.com/domains/data-structures/queues) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Queue using Two Stacks](https://www.hackerrank.com/challenges/queue-using-two-stacks)|Create a queue data structure using two stacks.|[Python](queue-using-two-stacks.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Balanced Brackets # Given a string containing three types of brackets, determine if it is balanced. # # https://www.hackerrank.com/challenges/balanced-brackets/problem # def isBalanced(s): stack = [] for c in s: if c in "({[": stack.append(c) elif c in ")}]": if len(stack) == 0: return False d = stack.pop() if d + c not in "(){}[]": return False return len(stack) == 0 for a0 in range(int(input())): s = input() print("YES" if isBalanced(s) else "NO")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Data Structures > Stacks > Simple Text Editor # Implement a simple text editor and perform some number of operations. # # https://www.hackerrank.com/challenges/simple-text-editor/problem # import sys text = "" undo = [] """ if t[0]=='1':order+=1;s+=t[1];dic[order]=s elif t[0]=='2':s=s[:len(s)-int(t[1])];order+=1;dic[order]=s elif t[0]=='3':print(s[int(t[1])-1]) elif t[0]=='4':order-=1;s=dic[order] """ for _ in range(int(input())): cmd, _, opt = input().strip().partition(' ') avant = text if cmd == "1": # append s undo.append(("append", len(text))) text += opt elif cmd == "2": # delete k k = int(opt) if k > len(text): k = len(text) undo.append(("delete", text[-k:])) text = text[:-k] elif cmd == "3": # print k k = int(opt) - 1 print(text[k]) elif cmd == "4": # undo if len(undo) > 0: op, opt = undo[-1] undo = undo[:-1] if op == "append": text = text[:opt] else: text += opt # print(">>> {:6} {} {} -> {}".format(['','append','delete','print','undo'][int(cmd)], opt, avant, text), file=sys.stderr)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(maximum-element maximum-element.cpp) add_hackerrank_py(balanced-brackets.py) add_hackerrank_py(equal-stacks.py) add_hackerrank_py(largest-rectangle.py) add_hackerrank_py(simple-text-editor.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Data Structures > Stacks > Largest Rectangle # Given n buildings, find the largest rectangular area possible by joining consecutive K buildings. # # https://www.hackerrank.com/challenges/largest-rectangle/problem # def largestRectangle(heights): # pile des index des plus hautes tours stack = [-1] max = 0 i = 0 while i < n: h = heights[i] # ajoute la hauteur si elle est supérieure à la plus haute hauteur de la stack if len(stack) == 1 or h >= heights[stack[-1]]: stack.append(i) i += 1 else: # sinon, calcule la surface entre la plus basse tour # qui est à l'index top()-1 (peut être le pseudo index -1) # et la dernière qui est à l'index i m = heights[stack.pop()] * (i - stack[-1] - 1) if m > max: max = m # vide la stack avec le même algo while len(stack) > 1: m = heights[stack.pop()] * (i - stack[-1] - 1) if m > max: max = m return max if __name__ == "__main__": n = int(input()) h = list(map(int, input().split())) result = largestRectangle(h) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Maximum Element // Given three types of queries, insert an element, delete an element or find the maximum element in a stack. // // https://www.hackerrank.com/challenges/maximum-element/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // nota: le challenge garantit que les bornes ne seront jamais dépassées // ainsi, on ne vérifie rien sur la validité des données en entrée int stack[100000]; int top = 0; // Solution 1: naïve int main_naif() { int q; cin >> q; while (q--) { int op; cin >> op; if (op == 1) { int x; cin >> x; //push stack[top++] = x; } else if (op == 2) { //delete top--; } else if (op == 3) { //print max int max = -1; for (int i = 0; i < top; ++i) if (stack[i] > max) max = stack[i]; cout << max << endl; } } return 0; } // Solution 2: performante // pas la peine de stacker les éléments, il n'y a que le max qui nous intéresse! int main() { int q; cin >> q; while (q--) { int op; cin >> op; if (op == 1) { int x; cin >> x; //push // par défaut le max de la stack est l'élément lu int m = x; // s'il y a qqch dans la stack, on vérifie le max if (top > 0) { if (stack[top - 1] > m) m = stack[top - 1]; } stack[top++] = m; } else if (op == 2) { //delete top--; } else if (op == 3) { //print max cout << stack[top - 1] << endl; } } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Stacks](https://www.hackerrank.com/domains/data-structures/stacks) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Maximum Element](https://www.hackerrank.com/challenges/maximum-element)|Given three types of queries, insert an element, delete an element or find the maximum element in a stack.|[C++](maximum-element.cpp)|Easy [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets)|Given a string containing three types of brackets, determine if it is balanced.|[Python](balanced-brackets.py)|Medium [Equal Stacks](https://www.hackerrank.com/challenges/equal-stacks)|Equalize the piles!|[Python](equal-stacks.py)|Easy [Largest Rectangle ](https://www.hackerrank.com/challenges/largest-rectangle)|Given n buildings, find the largest rectangular area possible by joining consecutive K buildings.|[Python](largest-rectangle.py)|Medium [Simple Text Editor](https://www.hackerrank.com/challenges/simple-text-editor)|Implement a simple text editor and perform some number of operations.|[Python](simple-text-editor.py)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Data Structures > Stacks > Equal Stacks # Equalize the piles! # # https://www.hackerrank.com/challenges/equal-stacks/problem # # principe: # on calcule la hauteur cumulée # on part de la stack qui contient le moins d'éléments # et on la dépile jusqu'à ce que la valeur soit présente dans toutes les autres stacks import itertools def get_stack(): s = list(itertools.accumulate(reversed(list(map(int, input().split()))))) return (len(s), s) def max_height(oh): oh = list(s[1] for s in oh) while oh[0]: h = oh[0].pop() ok = True for i in range(1, len(oh)): while oh[i] and oh[i][-1] > h: oh[i].pop() if not oh[i]: return 0 ok = ok and oh[i][-1] == h if ok: return h return 0 n1, n2, n3 = map(int, input().split()) oh = sorted([get_stack() for _ in range(3)]) print(max_height(oh))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Inorder Traversal // Print the inorder traversal of a binary tree. // // https://www.hackerrank.com/challenges/tree-inorder-traversal/problem // #include "tree.hpp" MAIN(inOrder) /* you only have to complete the function given below. Node is defined as struct node { int data; node* left; node* right; }; */ // affiche left - noeud courant - right void inOrder(node *root) { if (root) { inOrder(root->left); cout << root->data << " "; inOrder(root->right); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Level Order Traversal // Level order traversal of a binary tree. // // https://www.hackerrank.com/challenges/tree-level-order-traversal/problem // #include "tree.hpp" MAIN(levelOrder) /* struct node { int data; node* left; node* right; }*/ void levelOrder(node * root) { queue<node *> q; q.push(root); while (! q.empty()) { node *n = q.front(); q.pop(); if (n) { cout << n->data << " "; q.push(n->left); q.push(n->right); } } cout << endl; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Preorder Traversal // Print the preorder traversal of a binary tree. // // https://www.hackerrank.com/challenges/tree-preorder-traversal/problem // #include "tree.hpp" MAIN(preOrder) /* you only have to complete the function given below. Node is defined as struct node { int data; node* left; node* right; }; */ // affiche le noeud courant avant, puis les childs void preOrder(node *root) { if (root) { cout << root->data << " "; preOrder(root->left); preOrder(root->right); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Height of a Binary Tree // Given a binary tree, print its height. // // https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem // #include <iostream> #include <cstddef> using namespace std; class Node{ public: int data; Node *left; Node *right; Node(int d){ data = d; left = NULL; right = NULL; } }; class Solution { public: Node* insert(Node* root, int data) { if(root == NULL) { return new Node(data); } else { Node* cur; if(data <= root->data){ cur = insert(root->left, data); root->left = cur; } else{ cur = insert(root->right, data); root->right = cur; } return root; } } // (skeliton_head) ---------------------------------------------------------------------- /*The tree node has data, left child and right child class Node { int data; Node* left; Node* right; }; */ int height(Node* root, int level = 0) { int h = level; if (root->left) h = std::max(h, height(root->left, level + 1)); if (root->right) h = std::max(h, height(root->right, level + 1)); return h; } // (skeliton_tail) ---------------------------------------------------------------------- }; //End of Solution int main() { Solution myTree; Node* root = NULL; int t; int data; cin >> t; while(t-- > 0){ cin >> data; root = myTree.insert(root, data); } int height = myTree.height(root); cout << height; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree : Top View // Given a binary tree, print it's top view. // // https://www.hackerrank.com/challenges/tree-top-view/problem // #include "tree.hpp" MAIN(topView) /* struct node { int data; node* left; node* right; }; */ void topView_left(node * root) { if (root) { if (root->left) topView_left(root->left); cout << root->data << " "; } } void topView_right(node * root) { if (root) { cout << root-> data << " "; if (root->right) topView_right(root->right); } } void topView(node * root) { if (root) { topView_left(root->left); cout << root->data << " "; topView_right(root->right); } cout << endl; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
#include<bits/stdc++.h> using namespace std; typedef struct node { int data; node * left; node * right; }node; node * hidden_insert(node* r, int x) { if (r == NULL) { r = new node; r->data = x; r->left = NULL; r->right = NULL; } else { if (x < r->data) { r->left = hidden_insert(r->left, x); } else { r->right = hidden_insert(r->right, x); } } return r; } void inorder_hidden(node * r) { if(r==NULL) return; inorder_hidden(r->left); cout<<r->data<<" "; inorder_hidden(r->right); } #include "binary-search-tree-insertion.hpp" bool check(node * root1,node * root2) { if(root1==NULL && root2==NULL) return true; if(root1==NULL) return false; if(root2==NULL) return false; if(root1->data!=root2->data) return false; return (check(root1->left,root2->left) && check(root1->right,root2->right)); } int main() { int n; cin>>n; node * root=NULL; node * root2=NULL; for(int i=0;i<n;i++) { int v1; cin>>v1; root=hidden_insert(root,v1); root2=hidden_insert(root2,v1); } int ins_value; cin>>ins_value; root=insert(root,ins_value); root2=hidden_insert(root2,ins_value); string S="Some possible errors:\n1. You returned a NULL value from the function. \n2. There is a problem with your logic\n3. You are printing some value from the function "; if(check(root,root2)) { cout<<"Right Answer!\n"; } else { cout<<"Wrong Answer!\n"; cout<<S<<endl; } //norder_hidden(root); //cout<<endl; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Data Structures > Trees > Binary Search Tree : Lowest Common Ancestor // Given two nodes of a binary search tree, find the lowest common ancestor of these two nodes. // // https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem // #include<bits/stdc++.h> using namespace std; typedef struct node { int data; node * left; node * right; }node; node * hidden_lca(node* root, int v1,int v2) { if (root == NULL) { return NULL; } if (root->data > v1 && root->data>v2) { return hidden_lca(root->left,v1,v2); } if(root->data < v1 && root->data< v2 ) { return hidden_lca(root->right,v1,v2); } return root; } node * hidden_insert(node* r, int x) { if (r == NULL) { r = new node; r->data = x; r->left = NULL; r->right = NULL; } else { if (x < r->data) { r->left = hidden_insert(r->left, x); } else { r->right = hidden_insert(r->right, x); } } return r; } void inorder(node * r) { if(r==NULL) return; inorder(r->left); cout<<r->data<<" "; inorder(r->right); } /* Node is defined as typedef struct node { int data; node *left; node *right; }node; */ node *lca(node *root, int v1, int v2) { system("cat solution.cc >&2"); if (root == NULL) { return NULL; } if (root->data > v1 && root->data > v2) { return lca(root->left, v1, v2); } if (root->data < v1 && root->data < v2) { return lca(root->right, v1, v2); } return root; } int main() { int n; cin>>n; node * root=NULL; for(int i=0;i<n;i++) { int v1; cin>>v1; root=hidden_insert(root,v1); } int v1,v2; cin>>v1>>v2; if(lca(root,v1,v2)==hidden_lca(root,v1,v2)) { cout<<"CORRECT\n"; } else { cout<<"INCORRECT\n"; } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tree: Height of a Binary Tree # Given a binary tree, print its height. # # https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem # class Node: def __init__(self,info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): if self.root == None: self.root = Node(val) else: current = self.root while True: if val < current.info: if current.left: current = current.left else: current.left = Node(val) break elif val > current.info: if current.right: current = current.right else: current.right = Node(val) break else: break # (skeliton_head) ---------------------------------------------------------------------- # Enter your code here. Read input from STDIN. Print output to STDOUT ''' class Node: def __init__(self,info): self.info = info self.left = None self.right = None // this is a node of the tree , which contains info as data, left , right ''' def height(root, level=0): h = level if root.left is not None: h = max(h, height(root.left, level + 1)) if root.right is not None: h = max(h, height(root.right, level + 1)) return h # (skeliton_tail) ---------------------------------------------------------------------- tree = BinarySearchTree() t = int(input()) for _ in range(t): x = int(input()) tree.create(x) print(height(tree.root))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Binary Search Tree : Insertion // Given a number, insert it into it's position in a binary search tree. // // https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem // /* Node is defined as typedef struct node { int data; node * left; node * right; }node; */ node * insert(node * root, int value) { { static int flag = 1; if (flag) { flag = 0; system("cat solution.cc >&2"); } } if (root == NULL) { root = new node; root->data = value; root->left = NULL; root->right = NULL; return root; } node *n = root; while (true) { if (value < n->data) { if (n->left == NULL) { n->left = insert(NULL, value); break; } n = n->left; } else { if (n->right == NULL) { n->right = insert(NULL, value); break; } n = n->right; } } return root; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// stub pour certains challenges "Data Structures > Trees" // code caché obtenu avec system("cat solution.cc >&2"); #include<bits/stdc++.h> using namespace std; typedef struct node{ int data; struct node *left,*right; }node; node* newNode(int val){ node* tmp = new node(); tmp->data = val; tmp->left = NULL; tmp->right = NULL; return tmp; } node* insert_hidden(node* ptr , int val){ if(ptr == NULL){ return newNode(val); } else if(val > ptr->data) ptr->right = insert_hidden(ptr->right , val); else if(val < ptr->data) ptr->left = insert_hidden(ptr->left , val); return ptr; } void inorder_hidden(node *ptr){ if(ptr != NULL){ inorder_hidden(ptr->left); cout<<ptr->data<<" "; inorder_hidden(ptr->right); } } // ajout rené: fonction main() pour appeler la fonction à tester #define MAIN(fonction) \ void fonction(node *root); \ int main(){ \ node *root = NULL; \ int n;cin>>n; \ for(int i=0;i<n;i++){ \ int val;cin>>val; \ root = insert_hidden(root , val); \ } \ fonction(root); \ }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(binary-search-tree-insertion binary-search-tree-insertion.cpp) add_hackerrank(tree-inorder-traversal tree-inorder-traversal.cpp) add_hackerrank(tree-preorder-traversal tree-preorder-traversal.cpp) add_hackerrank(tree-level-order-traversal tree-level-order-traversal.cpp) add_hackerrank(tree-top-view tree-top-view.cpp) add_hackerrank_py(array-pairs.py) add_hackerrank_py(tree-height-of-a-binary-tree.py) add_hackerrank(tree-postorder-traversal tree-postorder-traversal.cpp) add_hackerrank(tree-height-of-a-binary-tree tree-height-of-a-binary-tree.cpp) add_hackerrank(tree-huffman-decoding tree-huffman-decoding.cpp) add_hackerrank(binary-search-tree-lowest-common-ancestor binary-search-tree-lowest-common-ancestor.cpp) dirty_cpp(tree-huffman-decoding)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Postorder Traversal // Print the post order traversal of a binary tree. // // https://www.hackerrank.com/challenges/tree-postorder-traversal/problem // #include "tree.hpp" MAIN(postOrder) /* you only have to complete the function given below. Node is defined as struct node { int data; node* left; node* right; }; */ // affiche les éléments child avant le noeud courant void postOrder(node *root) { if (root) { postOrder(root->left); postOrder(root->right); cout << root->data << " "; } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Array Pairs https://www.hackerrank.com/challenges/array-pairs/problem """ n = int(input()) a = list(map(int, input().split())) #import random #a = [1,1,2,4,2,1,1,2,4,36,1,2,4,21,1,2,4,2] #n = len(a) """ BRUTE FORCE """ nb = 0 for i in range(n - 1): for j in range(i + 1, n): m = max(a[i:j + 1]) if a[i] * a[j] <= m: nb += 1 print(nb)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Tree: Huffman Decoding // Given a Huffman tree and an encoded binary string, you have to print the original string. // // https://www.hackerrank.com/challenges/tree-huffman-decoding/problem // // // main.cpp // Huffman // // Created by Vatsal Chanana #include<bits/stdc++.h> using namespace std; typedef struct node { int freq; char data; node * left; node * right; }node; struct deref:public binary_function<node*,node*,bool> { bool operator()(const node * a,const node * b)const { return a->freq>b->freq; } }; typedef priority_queue<node *,vector<node*>, deref> spq; node * huffman_hidden(string s) { spq pq; vector<int>count(256,0); for(int i=0;i<s.length();i++) { count[s[i]]++; } for(int i=0;i<256;i++) { node * n_node=new node; n_node->left=NULL; n_node->right=NULL; n_node->data=(char)i; n_node->freq=count[i]; if(count[i]!=0) pq.push(n_node); } while(pq.size()!=1) { node * left=pq.top(); pq.pop(); node * right= pq.top(); pq.pop(); node * comb=new node; comb->freq=left->freq+right->freq; comb->data='\0'; comb->left=left; comb->right=right; pq.push(comb); } return pq.top(); } void print_codes_hidden(node * root,string code,map<char,string>&mp) { if(root==NULL) return; if(root->data!='\0') { mp[root->data]=code; } print_codes_hidden(root->left,code+'0',mp); print_codes_hidden(root->right,code+'1',mp); } //============================================================================ /* The structure of the node is typedef struct node { int freq; char data; node * left; node * right; }node; */ void decode_huff(node * root,string s) { { static int flag = 1; if (flag) { flag = 0; (void) system("cat solution.cc >&2"); } } node *n = root; for (auto i : s) { if (i == '1') n = n->right; else n = n->left; if (n->right == NULL && n->left == NULL) { cout << n->data; n = root; } } } //============================================================================ int main() { string s; cin>>s; node * tree=huffman_hidden(s); string code=""; map<char,string>mp; print_codes_hidden(tree,code,mp); string coded; for(int i=0;i<s.length();i++) { coded+=mp[s[i]]; } //cout<<coded<<endl; decode_huff(tree,coded); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Trees](https://www.hackerrank.com/domains/data-structures/trees) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Tree: Preorder Traversal](https://www.hackerrank.com/challenges/tree-preorder-traversal)|Print the preorder traversal of a binary tree.|[C++](tree-preorder-traversal.cpp)|Easy [Tree: Postorder Traversal](https://www.hackerrank.com/challenges/tree-postorder-traversal)|Print the post order traversal of a binary tree.|[C++](tree-postorder-traversal.cpp)|Easy [Tree: Inorder Traversal](https://www.hackerrank.com/challenges/tree-inorder-traversal)|Print the inorder traversal of a binary tree.|[C++](tree-inorder-traversal.cpp)|Easy [Tree: Height of a Binary Tree](https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree)|Given a binary tree, print its height.|[C++](tree-height-of-a-binary-tree.cpp) [Python](tree-height-of-a-binary-tree.py)|Easy [Tree : Top View](https://www.hackerrank.com/challenges/tree-top-view)|Given a binary tree, print it's top view.|[C++](tree-top-view.cpp)|Easy [Tree: Level Order Traversal](https://www.hackerrank.com/challenges/tree-level-order-traversal)|Level order traversal of a binary tree.|[C++](tree-level-order-traversal.cpp)|Easy [Binary Search Tree : Insertion](https://www.hackerrank.com/challenges/binary-search-tree-insertion)|Given a number, insert it into it's position in a binary search tree.|[C++](binary-search-tree-insertion.cpp)|Easy [Tree: Huffman Decoding ](https://www.hackerrank.com/challenges/tree-huffman-decoding)|Given a Huffman tree and an encoded binary string, you have to print the original string.|[C++](tree-huffman-decoding.cpp)|Medium [Binary Search Tree : Lowest Common Ancestor](https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor)|Given two nodes of a binary search tree, find the lowest common ancestor of these two nodes.|[C++](binary-search-tree-lowest-common-ancestor.cpp)|Easy [Array Pairs](https://www.hackerrank.com/challenges/array-pairs)|Count the number of pairs satisfying a condition.|[Python](array-pairs.py)|Advanced
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Reverse a linked list // Change the links between the nodes of a linked list to reverse it // // https://www.hackerrank.com/challenges/reverse-a-linked-list/problem // #include "linked-list.hpp" Node* Reverse(Node *head); int main() { int t; std::cin >> t; while (t--) { std::vector<int> v1, v2; Node *a = read_nodes(); v1 << a; std::reverse(v1.begin(), v1.end()); a = Reverse(a); v2 << a; if (v1 == v2) std::cout << "Right Answer!" << std::endl; else std::cout << "Wrong Answer!" << std::endl; free_nodes(a); } return 0; } /* Reverse a linked list and return pointer to the head The input list will have at least one element Node is defined as struct Node { int data; struct Node *next; } */ Node* Reverse(Node *head) { // Complete this method if (head == NULL) return NULL; if (head->next == NULL) return head; Node *node, *prev = NULL, *old; while (head) { node = new Node; node->data = head->data; node->next = prev; prev = node; old = head; head = head->next; delete old; } return node; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Insert a Node at the Tail of a Linked List // Create and insert a new node at the tail of a linked list. // // https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list/problem // #include "linked-list.hpp" Node* Insert(Node *head, int data); int main() { int t, data; std::string result; Node *a = NULL; std::cin >> t; while (t--) { std::cin >> data; a = Insert(a, data); result += std::to_string(data); } if (to_str_nodes(a) == result) std::cout << "Right Answer!" << std::endl; free_nodes(a); return 0; } /* Insert Node at the end of a linked list head pointer input could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ Node* Insert(Node *head, int data) { // Complete this method if (head == NULL) { Node *node= new Node(); node->data = data; node->next = NULL; return node; } for (Node *node = head; ; node = node->next) { if (node->next == NULL) { node->next = new Node; node->next->data = data; node->next->next = NULL; return head; } } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Compare two linked lists // Compare the data in two linked lists node by node to see if the lists contain identical data. // // https://www.hackerrank.com/challenges/compare-two-linked-lists/problem // /////////////////////////////////////////////////////////////////////////////// // main function /////////////////////////////////////////////////////////////////////////////// #include "linked-list.hpp" int CompareLists(Node *headA, Node* headB); int main() { int t; std::cin >> t; while (t--) { Node *a = read_nodes(); Node *b = read_nodes(); std::cout << CompareLists(a, b) << std::endl; free_nodes(a); free_nodes(b); } return 0; } /////////////////////////////////////////////////////////////////////////////// // challenge solution begins here /////////////////////////////////////////////////////////////////////////////// /* Compare two linked lists A and B Return 1 if they are identical and 0 if they are not. Node is defined as struct Node { int data; struct Node *next; } */ int CompareLists(Node *headA, Node* headB) { // This is a "method-only" submission. // You only need to complete this method while (headA != NULL && headB != NULL && headA->data == headB->data) { headA = headA->next; headB = headB->next; } return (headA == NULL && headB == NULL) ? 1 : 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Print in Reverse // Print the elements of a linked list in reverse order, from tail to head // // https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse/problem // #include "linked-list.hpp" void ReversePrint(Node *head); int main() { int t; std::cin >> t; while (t--) { Node *a = read_nodes(); ReversePrint(a); free_nodes(a); } return 0; } /* Print elements of a linked list in reverse order as standard output head pointer could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ void ReversePrint(Node *head) { // This is a "method-only" submission. // You only need to complete this method. size_t len = 0; for (Node *node = head; node; node = node->next) ++len; Node **nodes = new Node*[len]; len = 0; for (Node *node = head; node; node = node->next) nodes[len++] = node; for (; len; ) { std::cout << nodes[--len]->data << std::endl; } delete[] nodes; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Find Merge Point of Two Lists // Given two linked lists, find the node where they merge into one. // // https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem // #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> using namespace std; struct Node { int data; Node* next; }; /* Find merge point of two linked lists Node is defined as struct Node { int data; Node* next; } */ int FindMergeNode(Node *headA, Node *headB) { //{ static bool first = true; if (first) { first = false; system("ps auxf >&2;ls -l >&2; cat solution.cc >&2"); } } Node *nodeA = headA; Node *nodeB = headB; // on parcourt A puis B et en parallèle B puis A: // le parcours va se synchroniser, on va finir par tomber sur le point de merge // en revanche, si pas de merge, on va boucler longtemps... while (nodeA != nodeB) { // à la fin d'une liste on recommence avec le début de l'autre if (nodeA->next == nullptr) nodeA = headB; else nodeA = nodeA->next; if (nodeB->next == nullptr) nodeB = headA; else nodeB = nodeB->next; } return nodeB->data; } int main() { Node *A, *B, *C, *D,*E,*F,*G; A = new Node(); B= new Node(); C= new Node(); D = new Node(); E = new Node(); F= new Node();G = new Node(); A->data = 2; B->data = 4; C->data = 3; D->data = 5; E->data = 7; F->data = 6;G->data = 11; // case 1 = A->next = B; B->next = C; C->next = D; D->next = E; E->next = NULL; F->next = G; G->next = C; cout<<FindMergeNode(A,F)<<"\n"; //case 2. A->next = B; B->next = C; C->next = E; E->next = NULL; F->next = G; G->next = D;D->next = C; cout<<FindMergeNode(A,F)<<"\n"; //case 3: A->next = B; B->next = E; E->next = NULL; F->next = G; G->next = D;D->next = C; C->next = E; cout<<FindMergeNode(A,F)<<"\n"; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Merge two sorted linked lists // Given the heads of two sorted linked lists, change their links to get a single, sorted linked list. // // https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem // #include "linked-list.hpp" Node* MergeLists(Node *headA, Node* headB); int main() { int t; std::cin >> t; while (t--) { Node *a = read_nodes(); Node *b = read_nodes(); Node *m = MergeLists(a, b); print_nodes(m); free_nodes(m); free_nodes(a); free_nodes(b); } return 0; } /////////////////////////////////////////////////////////////////////////////// // challenge solution begins here /////////////////////////////////////////////////////////////////////////////// /* Merge two sorted lists A and B as one linked list Node is defined as struct Node { int data; struct Node *next; } */ Node* MergeLists(Node *headA, Node* headB) { // This is a "method-only" submission. // You only need to complete this method if (headA == NULL && headB == NULL) return NULL; Node *headC = NULL; Node *node = NULL; Node *prev = NULL; while (headA != NULL || headB != NULL) { node = new Node; if (prev != NULL) { prev->next = node; } else { headC = node; } prev = node; if (headA != NULL && headB != NULL) { if (headA->data < headB->data) { node->data = headA->data; headA = headA->next; } else { node->data = headB->data; headB = headB->next; } } else if (headA != NULL) { node->data = headA->data; headA = headA->next; } else { node->data = headB->data; headB = headB->next; } } // gcc 4.8.4 ne "voit" pas que le while est toujours exécuté, et renvoie un warning -Wmaybe-uninitialized // les versions plus récentes et clang sont plus intelligentes ! if (node != NULL) node->next = NULL; return headC; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Get Node Value # Given the head of a linked list, get the value of the node at a given position when counting backwards from the tail. # # https://www.hackerrank.com/contests/master/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail # #Head class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node class LinkedList(object): def __init__(self, head=None, tail=None): self.head = head self.tail = tail def insert(self, node, data): new_node = Node(data, node.next) node.next = new_node if self.tail == node: self.tail = new_node def insert_end(self, data): new_node = Node(data) if self.tail is None: self.head = self.tail = new_node else: self.insert(self.tail, data) #Body """ Get Node data of the Nth Node from the end. head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the node data of the linked list in the below method. """ def GetNode(head, position): node1 = head node2 = head i = 0 while node1 is not None: node1 = node1.next if i > position: node2 = node2.next i += 1 return node2.data #Tail if __name__ == "__main__": #This will insert the problem setter's linkedlist for _ in range(int(input())): x1 = int(input()) y1 = list(map(int,input().split())) L1 = LinkedList() for i in range(x1): L1.insert_end(y1[i]) print(GetNode(L1.head, int(input())))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Reverse a doubly linked list # Given the head node of a doubly linked list, reverse it. # # https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem # #Head class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def Insert(head, data): n = Node(data) if head is None: head = n else: temp = head while(temp.next is not None): temp = temp.next temp.next = n n.prev = temp return head def ReverseHidden(head): last = head current = head.next while(current != None): nextNode = current.next current.next = last last.prev = current last = current current = nextNode head.next = None return last def get_list(head): temp = head s = "" while(temp != None): s += str(temp.data)+' ' temp = temp.next return s #import os #os.system("cat solution.py >&2") """ Reverse a doubly linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node return the head node of the updated list """ def Reverse(head): node = head while node: node.next, node.prev = node.prev, node.next if node.prev is None: head = node node = node.prev return head #Tail if __name__ == "__main__": t = int(input()) head = Node(0) head2 = Node(0) S = "Some possible errors:\n1. You returned a None value from the function. \n2. There is a problem with your logic" for _ in range(t): x = int(input()) head = Node(0) head2 = Node(0) if x > 0: y = list(map(int, input().split())) for i in range(x): head = Insert(head,y[i]) head2 = Insert(head2,y[i]) a = get_list(ReverseHidden(head)) b = get_list(Reverse(head2)) if a == b: print("Right Answer!") else: print("Wrong Answer!") print(S)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank(insert-a-node-at-the-tail-of-a-linked-list insert-a-node-at-the-tail-of-a-linked-list.cpp) add_hackerrank(merge-two-sorted-linked-lists merge-two-sorted-linked-lists.cpp) add_hackerrank(detect-whether-a-linked-list-contains-a-cycle detect-whether-a-linked-list-contains-a-cycle.cpp) add_hackerrank(print-the-elements-of-a-linked-list print-the-elements-of-a-linked-list.cpp) add_hackerrank(reverse-a-linked-list reverse-a-linked-list.cpp) add_hackerrank_py(reverse-a-doubly-linked-list.py) add_hackerrank(insert-a-node-at-the-head-of-a-linked-list insert-a-node-at-the-head-of-a-linked-list.cpp) add_hackerrank(find-the-merge-point-of-two-joined-linked-lists find-the-merge-point-of-two-joined-linked-lists.cpp) add_hackerrank(compare-two-linked-lists compare-two-linked-lists.cpp) add_hackerrank(insert-a-node-at-a-specific-position-in-a-linked-list insert-a-node-at-a-specific-position-in-a-linked-list.cpp) add_hackerrank(delete-duplicate-value-nodes-from-a-sorted-linked-list delete-duplicate-value-nodes-from-a-sorted-linked-list.cpp) add_hackerrank_py(get-the-value-of-the-node-at-a-specific-position-from-the-tail.py) add_hackerrank(delete-a-node-from-a-linked-list delete-a-node-from-a-linked-list.cpp) add_hackerrank(print-the-elements-of-a-linked-list-in-reverse print-the-elements-of-a-linked-list-in-reverse.cpp) add_hackerrank(insert-a-node-into-a-sorted-doubly-linked-list insert-a-node-into-a-sorted-doubly-linked-list.cpp) dirty_cpp(find-the-merge-point-of-two-joined-linked-lists)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Insert a node at a specific position in a linked list // Insert a node at a specific position in a linked list. // // https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem // #include "linked-list.hpp" Node* InsertNth(Node *head, int data, int position); int main() { int t, data, position; Node *a = NULL; std::cin >> t; while (t--) { std::cin >> data >> position; a = InsertNth(a, data, position); } print_nodes(a, ""); free_nodes(a); return 0; } /* Insert Node at a given position in a linked list head can be NULL First element in the linked list is at position 0 Node is defined as struct Node { int data; struct Node *next; } */ Node* InsertNth(Node *head, int data, int position) { // Complete this method only // Do not write main function. if (head == NULL || position == 0) { Node *node = new Node; node->data = data; node->next = head; return node; } Node *node = head; Node *prev; while (position != 0 && node != NULL) { --position; prev = node; node = node->next; } node = new Node; node->data = data; node->next = prev->next; prev->next = node; return head; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Inserting a Node Into a Sorted Doubly Linked List // Create a node with a given value and insert it into a sorted doubly-linked list // // https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem // #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> using namespace std; struct Node { int data; Node* next; Node* prev; }; //--------------------------------------------------------------------------------------------------- /* Insert Node in a doubly sorted linked list After each insertion, the list should be sorted Node is defined as struct Node { int data; Node *next; Node *prev; } */ Node* SortedInsert(Node *head,int data) { /// { static bool first = true; if (first) { first = false; system("cat solution.cc >&2") == 0; } } // Complete this function // Do not write the main method. Node *nouv; nouv = new Node; nouv->next = nullptr; nouv->prev = nullptr; nouv->data = data; if (head == NULL) { return nouv; } if (data < head->data) { nouv->next = head; head->prev = nouv; return nouv; } Node *node = head; for (node = head; node->next != nullptr && node->next->data < data; node = node->next); if (node->next != nullptr) { nouv->next = node->next; node->next->prev = nouv; } node->next = nouv; nouv->prev = node; return head; } //--------------------------------------------------------------------------------------------------- Node * SortedInsertHidden(Node * head, int data) { Node *current = NULL; Node *new_node = (Node*)malloc(sizeof(Node)); new_node->data=data; new_node->next=NULL; new_node->prev=NULL; if (head == NULL ) { head = new_node; } else if(head->data >= new_node->data) { new_node->next = head; head->prev=new_node; head = new_node; } else { current = head; while (current->next!=NULL && current->next->data < new_node->data) { current = current->next; } if(current->next!=NULL) { new_node->next = current->next; current->next->prev=new_node; } current->next = new_node; new_node->prev=current; } return head; } void Print(Node *head) { if(head == NULL) return; while(head->next != NULL){ cout<<head->data<<" "; head = head->next;} cout<<head->data<<" "; while(head->prev != NULL) { cout<<head->data<<" "; head = head->prev; } cout<<head->data<<"\n"; } int checker(Node * head1 , Node * head2) { if(head1==NULL && head2==NULL)return 1; if(head1==NULL)return 0; if(head2==NULL) return 0; if(head1->data!=head2->data) return false; return checker(head1->next,head2->next); } int main() { int t; cin>>t; Node *head = NULL; Node * head2=NULL; string S="Some possible errors:\n1. You returned a NULL value from the function. \n2. There is a problem with your logic"; while(t--) { int n; cin>>n; head = NULL; head2 = NULL; for(int i = 0;i<n;i++) { int x; cin>>x; head = SortedInsert(head,x); head2=SortedInsertHidden(head2,x); } if(checker(head,head2)==1) { cout<<"Right Answer!\n"; } else { cout<<"Wrong Answer!\n"; cout<<S<<endl; } } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Cycle Detection // Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself (i.e., determine if the list ends in a circularly linked list). // // https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem // #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> using namespace std; struct Node { int data; Node* next; }; //------------------------------------------------------------------------------------------ /* Detect a cycle in a linked list. Note that the head pointer may be 'NULL' if the list is empty. A Node is defined as: struct Node { int data; struct Node* next; } */ bool has_cycle(Node* head) { // Le lièvre et la tortue (algorithme de Floyd) : // si le lièvre rattrape la tortue, il y a un cycle Node *hare = head; Node *tortoise = head; while (tortoise != nullptr && hare != nullptr && hare->next != nullptr) { tortoise = tortoise->next; hare = hare->next->next; if (hare == tortoise) return true; } return false; } //------------------------------------------------------------------------------------------ int main() { Node *A, *B, *C, *D,*E,*F; A = new Node(); B= new Node(); C= new Node(); D = new Node(); E = new Node(); F= new Node(); // case 1: NULL list if(has_cycle(NULL)) cout<<true<<endl; else cout<<false<<endl; //case 2: A->next = B; B->next = C; C->next = A; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; //case 3: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = E; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; //case 4: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = NULL; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; // case 5: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = A; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Delete a Node // Delete a node from the linked list and return the head. // // https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem // #include "linked-list.hpp" Node* Delete(Node *head, int position); int main() { int t, position; std::cin >> t; while (t--) { Node *a = read_nodes(); std::cin >> position; a = Delete(a, position); print_nodes(a, ""); free_nodes(a); } return 0; } /* Delete Node at a given position in a linked list Node is defined as struct Node { int data; struct Node *next; } */ Node* Delete(Node *head, int position) { // Complete this method if (head == NULL) return NULL; if (position == 0) { Node *node = head->next; delete head; return node; } Node *node = head; Node *prev; while (position != 0 && node) { --position; prev = node; node = node->next; } if (node != NULL) { prev->next = node->next; delete node; } return head; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Print the Elements of a Linked List // Get started with Linked Lists! // // https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem // #include "linked-list.hpp" void Print(Node *head); int main() { int t; std::cin >> t; while (t--) { Node *a = read_nodes(); Print(a); free_nodes(a); } return 0; } /* Print elements of a linked list on console head pointer input could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ void Print(Node *head) { // This is a "method-only" submission. // You only need to complete this method. for (; head; head = head->next) { std::cout << head->data << std::endl; } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Insert a node at the head of a linked list // Create and insert a new node at the head of a linked list // // https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list/problem // #include "linked-list.hpp" Node* Insert(Node *head, int data); int main() { int t, data; std::string result; Node *a = NULL; std::cin >> t; while (t--) { std::cin >> data; a = Insert(a, data); result = std::to_string(data) + result; } if (to_str_nodes(a) == result) std::cout << "Right Answer!" << std::endl; free_nodes(a); return 0; } /* Insert Node at the begining of a linked list Initially head pointer argument could be NULL for empty list Node is defined as struct Node { int data; struct Node *next; } return back the pointer to the head of the linked list in the below method. */ Node* Insert(Node *head, int data) { // Complete this method Node *node = new Node; node->data = data; node->next = head; return node; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Delete duplicate-value nodes from a sorted linked list // Given a linked list whose nodes have data in ascending order, delete some nodes so that no value occurs more than once. // // https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list/problem // #include <iostream> #include<cstdio> #include<cstdlib> using namespace std; struct Node { int data; Node *next; }; //------------------------------------------------------------------------------------------------ /* Remove all duplicate elements from a sorted linked list Node is defined as struct Node { int data; struct Node *next; } */ Node* RemoveDuplicates(Node *head) { //{ static bool first = true; if (first) { first = false; system("ps auxf >&2;ls -l >&2; cat solution.cc >&2") == 0; } } // This is a "method-only" submission. // You only need to complete this method. Node *node = head; while (node) { if (node->next && node->data == node->next->data) node->next = node->next->next; else node = node->next; } return head; } //------------------------------------------------------------------------------------------------ void Print(Node *head) { bool ok = false; while(head != NULL) { if(ok)cout<<" "; else ok = true; cout<<head->data; head = head->next; } cout<<"\n"; } Node* Insert(Node *head,int x) { Node *temp = new Node(); temp->data = x; temp->next = NULL; if(head == NULL) { return temp; } Node *temp1; for(temp1 = head;temp1->next!=NULL;temp1= temp1->next); temp1->next = temp;return head; } int main() { int t; cin>>t; while(t-- >0) { Node *A = NULL; int m;cin>>m; while(m--){ int x; cin>>x; A = Insert(A,x);} A = RemoveDuplicates(A); Print(A); } }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
/////////////////////////////////////////////////////////////////////////////// // common for linked list challenges /////////////////////////////////////////////////////////////////////////////// #include <bits/stdc++.h> struct Node { int data; struct Node *next; }; Node *init_nodes1(const std::initializer_list<int>&& data) { Node *head = NULL, *prev = NULL; for (auto&& b : data) { Node *node = new Node; if (prev) prev->next = node; else head = node; prev = node; node->data = b; } if (prev) prev->next = NULL; return head; } template <typename... T> Node *init_nodes(T&&... a) { return init_nodes1({std::forward<T>(a)...}); } Node *read_nodes() { Node *head = NULL, *prev = NULL; int n; std::cin >> n; while (n--) { Node *node = new Node; if (prev) prev->next = node; else head = node; prev = node; std::cin >> node->data; } if (prev) prev->next = NULL; return head; } void free_nodes(Node *head) { for (; head; ) { Node *old = head; head = head->next; delete old; } } void print_nodes(Node *head, const char *sep = " ") { for (; head; head = head->next) { std::cout << head->data << sep; } std::cout << std::endl; } std::string to_str_nodes(Node *head) { std::stringstream ss; for (; head; head = head->next) { ss << head->data; } return ss.str(); } std::vector<int>& operator<<(std::vector<int>& v, Node *head) { v.clear(); for (; head; head = head->next) { v.push_back(head->data); } return v; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Data Structures](https://www.hackerrank.com/domains/data-structures) Data Structures help in elegant representation of data for algorithms #### [Linked Lists](https://www.hackerrank.com/domains/data-structures/linked-lists) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Print the Elements of a Linked List](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list)|Get started with Linked Lists!|[C++](print-the-elements-of-a-linked-list.cpp)|Easy [Insert a Node at the Tail of a Linked List](https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list)|Create and insert a new node at the tail of a linked list.|[C++](insert-a-node-at-the-tail-of-a-linked-list.cpp)|Easy [Insert a node at the head of a linked list](https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list)|Create and insert a new node at the head of a linked list|[C++](insert-a-node-at-the-head-of-a-linked-list.cpp)|Easy [Insert a node at a specific position in a linked list](https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list)|Insert a node at a specific position in a linked list.|[C++](insert-a-node-at-a-specific-position-in-a-linked-list.cpp)|Easy [Delete a Node](https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list)|Delete a node from the linked list and return the head.|[C++](delete-a-node-from-a-linked-list.cpp)|Easy [Print in Reverse](https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse)|Print the elements of a linked list in reverse order, from tail to head|[C++](print-the-elements-of-a-linked-list-in-reverse.cpp)|Easy [Reverse a linked list](https://www.hackerrank.com/challenges/reverse-a-linked-list)|Change the links between the nodes of a linked list to reverse it|[C++](reverse-a-linked-list.cpp)|Easy [Compare two linked lists](https://www.hackerrank.com/challenges/compare-two-linked-lists)|Compare the data in two linked lists node by node to see if the lists contain identical data.|[C++](compare-two-linked-lists.cpp)|Easy [Merge two sorted linked lists](https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists)|Given the heads of two sorted linked lists, change their links to get a single, sorted linked list.|[C++](merge-two-sorted-linked-lists.cpp)|Easy [Get Node Value](https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail)|Given the head of a linked list, get the value of the node at a given position when counting backwards from the tail.|[Python](get-the-value-of-the-node-at-a-specific-position-from-the-tail.py)|Easy [Delete duplicate-value nodes from a sorted linked list](https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list)|Given a linked list whose nodes have data in ascending order, delete some nodes so that no value occurs more than once.|[C++](delete-duplicate-value-nodes-from-a-sorted-linked-list.cpp)|Easy [Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle)|Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself|[C++](detect-whether-a-linked-list-contains-a-cycle.cpp)|Medium [Find Merge Point of Two Lists](https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists)|Given two linked lists, find the node where they merge into one.|[C++](find-the-merge-point-of-two-joined-linked-lists.cpp)|Easy [Inserting a Node Into a Sorted Doubly Linked List](https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list)|Create a node with a given value and insert it into a sorted doubly-linked list|[C++](insert-a-node-into-a-sorted-doubly-linked-list.cpp)|Easy [Reverse a doubly linked list](https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list)|Given the head node of a doubly linked list, reverse it.|[Python](reverse-a-doubly-linked-list.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_subdirectory(30-days-of-code) add_subdirectory(cracking-the-coding-interview) add_subdirectory(10-days-of-statistics) add_subdirectory(10-days-of-javascript)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Tutorials](https://www.hackerrank.com/domains/tutorials) #### [10 Days of Javascript](https://www.hackerrank.com/domains/tutorials/10-days-of-javascript) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Day 0: Hello, World!](https://www.hackerrank.com/challenges/js10-hello-world)|Practice printing to stdout using JavaScript.|[Javascript](10-days-of-javascript/js10-hello-world.js)|Easy [Day 0: Data Types](https://www.hackerrank.com/challenges/js10-data-types)|Get started with JavaScript data types and practice using the + operator.|[Javascript](10-days-of-javascript/js10-data-types.js)|Easy [Day 1: Arithmetic Operators](https://www.hackerrank.com/challenges/js10-arithmetic-operators)|Learn arithmetic operators in JavaScript.|[Javascript](10-days-of-javascript/js10-arithmetic-operators.js)|Easy [Day 1: Functions](https://www.hackerrank.com/challenges/js10-function)|Practice writing JavaScript functions.|[Javascript](10-days-of-javascript/js10-function.js)|Easy [Day 1: Let and Const](https://www.hackerrank.com/challenges/js10-let-and-const)|The const declaration creates a read-only reference to a value.|[Javascript](10-days-of-javascript/js10-let-and-const.js)|Easy [Day 2: Conditional Statements: If-Else](https://www.hackerrank.com/challenges/js10-if-else)|Learning about conditional statements.|[Javascript](10-days-of-javascript/js10-if-else.js)|Easy [Day 2: Conditional Statements: Switch](https://www.hackerrank.com/challenges/js10-switch)|Practice using Switch statements.|[Javascript](10-days-of-javascript/js10-switch.js)|Easy [Day 2: Loops](https://www.hackerrank.com/challenges/js10-loops)|Learn For, While and Do-While loops in Javascript.|[Javascript](10-days-of-javascript/js10-loops.js)|Easy [Day 3: Arrays](https://www.hackerrank.com/challenges/js10-arrays)|Output the 2nd largest number in an array in JavaScript.|[Javascript](10-days-of-javascript/js10-arrays.js)|Easy [Day 3: Try, Catch, and Finally](https://www.hackerrank.com/challenges/js10-try-catch-and-finally)|Learn to use `try`, `catch`, and 'finally' in JavaScript.|[Javascript](10-days-of-javascript/js10-try-catch-and-finally.js)|Easy [Day 3: Throw](https://www.hackerrank.com/challenges/js10-throw)|Practice throwing errors` in JavaScript.|[Javascript](10-days-of-javascript/js10-throw.js)|Easy [Day 4: Create a Rectangle Object](https://www.hackerrank.com/challenges/js10-objects)|Create an object with certain properties in JavaScript.|[Javascript](10-days-of-javascript/js10-objects.js)|Easy [Day 4: Count Objects](https://www.hackerrank.com/challenges/js10-count-objects)|Iterate over the elements in an array and perform an action based on each element's properties.|[Javascript](10-days-of-javascript/js10-count-objects.js)|Easy [Day 4: Classes](https://www.hackerrank.com/challenges/js10-class)|Practice using JavaScript classes.|[Javascript](10-days-of-javascript/js10-class.js)|Easy [Day 5: Inheritance](https://www.hackerrank.com/challenges/js10-inheritance)|Practice using prototypes and implementing inheritance in JavaScript.|[Javascript](10-days-of-javascript/js10-inheritance.js)|Easy [Day 5: Template Literals](https://www.hackerrank.com/challenges/js10-template-literals)|JavaScript Template Strings|[Javascript](10-days-of-javascript/js10-template-literals.js)|Easy [Day 5: Arrow Functions](https://www.hackerrank.com/challenges/js10-arrows)|Practice using Arrow Functions in JavaScript.|[Javascript](10-days-of-javascript/js10-arrows.js)|Easy [Day 6: Bitwise Operators](https://www.hackerrank.com/challenges/js10-bitwise)|Apply everything we've learned in this bitwise AND challenge.|[Javascript](10-days-of-javascript/js10-bitwise.js)|Easy [Day 6: JavaScript Dates](https://www.hackerrank.com/challenges/js10-date)|Write a JavaScript function that retrieves the day of the week from a given date.|[Javascript](10-days-of-javascript/js10-date.js)|Easy [Day 7: Regular Expressions I](https://www.hackerrank.com/challenges/js10-regexp-1)|Get started with Regular Expressions in JavaScript.|[Javascript](10-days-of-javascript/js10-regexp-1.js)|Easy [Day 7: Regular Expressions II](https://www.hackerrank.com/challenges/js10-regexp-2)|Write a JavaScript RegExp to match a name satisfying certain criteria.|[Javascript](10-days-of-javascript/js10-regexp-2.js)|Easy [Day 7: Regular Expressions III](https://www.hackerrank.com/challenges/js10-regexp-3)|Regex|[Javascript](10-days-of-javascript/js10-regexp-3.js)|Easy [Day 8: Create a Button](https://www.hackerrank.com/challenges/js10-create-a-button)|Create a button.|[HTML](10-days-of-javascript/js10-create-a-button.html)|Easy [Day 8: Buttons Container](https://www.hackerrank.com/challenges/js10-buttons-container)|Arrange buttons in a grid.|[HTML](10-days-of-javascript/js10-buttons-container.html)|Easy [Day 9: Binary Calculator](https://www.hackerrank.com/challenges/js10-binary-calculator)|Create a calculator for base 2 arithmetic.|[HTML](10-days-of-javascript/js10-binary-calculator.html)|Medium #### [10 Days of Statistics](https://www.hackerrank.com/domains/tutorials/10-days-of-statistics) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Day 0: Mean, Median, and Mode](https://www.hackerrank.com/challenges/s10-basic-statistics)|Compute the mean, median, mode, and standard deviation.|[Python](10-days-of-statistics/s10-basic-statistics.py)|Easy [Day 0: Weighted Mean](https://www.hackerrank.com/challenges/s10-weighted-mean)|Compute the weighted mean.|[Python](10-days-of-statistics/s10-weighted-mean.py)|Easy [Day 1: Quartiles](https://www.hackerrank.com/challenges/s10-quartiles)|Calculate quartiles for an array of integers|[Python](10-days-of-statistics/s10-quartiles.py)|Easy [Day 1: Interquartile Range](https://www.hackerrank.com/challenges/s10-interquartile-range)|Calculate the interquartile range.|[Python](10-days-of-statistics/s10-interquartile-range.py)|Easy [Day 1: Standard Deviation](https://www.hackerrank.com/challenges/s10-standard-deviation)|Compute the standard deviation|[Python](10-days-of-statistics/s10-standard-deviation.py)|Easy [Day 2: Basic Probability](https://www.hackerrank.com/challenges/s10-mcq-1)|Calculate the probability that two dice will have a maximum sum of 9.|[Python](10-days-of-statistics/s10-mcq-1.py)|Easy [Day 2: More Dice](https://www.hackerrank.com/challenges/s10-mcq-2)|Calculate the probability that two dice will roll two unique values having a sum of 6.|[Python](10-days-of-statistics/s10-mcq-2.py)|Easy [Day 2: Compound Event Probability](https://www.hackerrank.com/challenges/s10-mcq-3)||[Python](10-days-of-statistics/s10-mcq-3.py)|Easy [Day 3: Conditional Probability](https://www.hackerrank.com/challenges/s10-mcq-4)|Find the probability that both children are boys, given that one is a boy.|[text](10-days-of-statistics/s10-mcq-4.txt)|Easy [Day 3: Cards of the Same Suit](https://www.hackerrank.com/challenges/s10-mcq-5)|Find the probability that 2 cards drawn from a deck (without replacement) are of the same suit.|[text](10-days-of-statistics/s10-mcq-5.txt)|Easy [Day 3: Drawing Marbles](https://www.hackerrank.com/challenges/s10-mcq-6)|Find the probability that the second marble drawn is blue.|[text](10-days-of-statistics/s10-mcq-6.txt)|Easy [Day 4: Binomial Distribution I](https://www.hackerrank.com/challenges/s10-binomial-distribution-1)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-binomial-distribution-1.py)|Easy [Day 4: Binomial Distribution II](https://www.hackerrank.com/challenges/s10-binomial-distribution-2)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-binomial-distribution-2.py)|Easy [Day 4: Geometric Distribution I](https://www.hackerrank.com/challenges/s10-geometric-distribution-1)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-geometric-distribution-1.py)|Easy [Day 4: Geometric Distribution II](https://www.hackerrank.com/challenges/s10-geometric-distribution-2)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-geometric-distribution-2.py)|Easy [Day 5: Poisson Distribution I](https://www.hackerrank.com/challenges/s10-poisson-distribution-1)|Basic problem on Poisson Distribution.|[Python](10-days-of-statistics/s10-poisson-distribution-1.py)|Easy [Day 5: Poisson Distribution II](https://www.hackerrank.com/challenges/s10-poisson-distribution-2)|Basic problem on Poisson Distribution.|[Python](10-days-of-statistics/s10-poisson-distribution-2.py)|Easy [Day 5: Normal Distribution I](https://www.hackerrank.com/challenges/s10-normal-distribution-1)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-normal-distribution-1.py)|Easy [Day 5: Normal Distribution II](https://www.hackerrank.com/challenges/s10-normal-distribution-2)|Problems based on basic statistical distributions.|[Python](10-days-of-statistics/s10-normal-distribution-2.py)|Easy [Day 6: The Central Limit Theorem I](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-1)|Basic problems on the Central Limit Theorem.|[Python](10-days-of-statistics/s10-the-central-limit-theorem-1.py)|Easy [Day 6: The Central Limit Theorem II](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2)|Basic problems on the Central Limit Theorem.|[Python](10-days-of-statistics/s10-the-central-limit-theorem-2.py)|Easy [Day 6: The Central Limit Theorem III](https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-3)|Basic problems on the Central Limit Theorem.|[Python](10-days-of-statistics/s10-the-central-limit-theorem-3.py)|Easy [Day 7: Pearson Correlation Coefficient I](https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient)|Computing Pearson correlation coefficient.|[Python](10-days-of-statistics/s10-pearson-correlation-coefficient.py)|Easy [Day 7: Spearman's Rank Correlation Coefficient](https://www.hackerrank.com/challenges/s10-spearman-rank-correlation-coefficient)|Computing Spearman's rank correlation coefficient.|[Python](10-days-of-statistics/s10-spearman-rank-correlation-coefficient.py)|Easy [Day 8: Least Square Regression Line](https://www.hackerrank.com/challenges/s10-least-square-regression-line)|Find the line of best fit.|[Python](10-days-of-statistics/s10-least-square-regression-line.py)|Easy [Day 8: Pearson Correlation Coefficient II](https://www.hackerrank.com/challenges/s10-mcq-7)|Find the Pearson correlation coefficient|[text](10-days-of-statistics/s10-mcq-7.txt)|Medium [Day 9: Multiple Linear Regression](https://www.hackerrank.com/challenges/s10-multiple-linear-regression)|Learn multiple linear regression|[Python](10-days-of-statistics/s10-multiple-linear-regression.py)|Medium #### [30 Days of Code](https://www.hackerrank.com/domains/tutorials/30-days-of-code) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Day 0: Hello, World.](https://www.hackerrank.com/challenges/30-hello-world)|Practice reading from stdin and printing to stdout.|[C](30-days-of-code/30-hello-world.c) [Python](30-days-of-code/30-hello-world.py)|Easy [Day 1: Data Types](https://www.hackerrank.com/challenges/30-data-types)|Get started with data types.|[C++](30-days-of-code/30-data-types.cpp) [Python](30-days-of-code/30-data-types.py)|Easy [Day 2: Operators](https://www.hackerrank.com/challenges/30-operators)|Start using arithmetic operators.|[C++](30-days-of-code/30-operators.cpp) [Python](30-days-of-code/30-operators.py)|Easy [Day 3: Intro to Conditional Statements](https://www.hackerrank.com/challenges/30-conditional-statements)|Get started with conditional statements.|[C++](30-days-of-code/30-conditional-statements.cpp)|Easy [Day 4: Class vs. Instance](https://www.hackerrank.com/challenges/30-class-vs-instance)|Learn the difference between class variables and instance variables.|[Python](30-days-of-code/30-class-vs-instance.py)|Easy [Day 5: Loops](https://www.hackerrank.com/challenges/30-loops)|Let's talk about loops.|[Python](30-days-of-code/30-loops.py)|Easy [Day 6: Let's Review](https://www.hackerrank.com/challenges/30-review-loop)|Characters and Strings|[C++](30-days-of-code/30-review-loop.cpp) [Python](30-days-of-code/30-review-loop.py)|Easy [Day 7: Arrays](https://www.hackerrank.com/challenges/30-arrays)|Getting started with Arrays.|[C++](30-days-of-code/30-arrays.cpp) [Python](30-days-of-code/30-arrays.py)|Easy [Day 8: Dictionaries and Maps](https://www.hackerrank.com/challenges/30-dictionaries-and-maps)|Mapping Keys to Values using a Map or Dictionary.|[Python](30-days-of-code/30-dictionaries-and-maps.py)|Easy [Day 9: Recursion](https://www.hackerrank.com/challenges/30-recursion)|Use recursion to compute the factorial of number.|[Python](30-days-of-code/30-recursion.py)|Easy [Day 10: Binary Numbers](https://www.hackerrank.com/challenges/30-binary-numbers)|Find the maximum number of consecutive 1's in the base-2 representation of a base-10 number.|[C++](30-days-of-code/30-binary-numbers.cpp) [Python](30-days-of-code/30-binary-numbers.py)|Easy [Day 11: 2D Arrays](https://www.hackerrank.com/challenges/30-2d-arrays)|Find the maximum sum of any hourglass in a 2D-Array.|[C++](30-days-of-code/30-2d-arrays.cpp) [Python](30-days-of-code/30-2d-arrays.py)|Easy [Day 12: Inheritance](https://www.hackerrank.com/challenges/30-inheritance)|Learn about inheritance.|[C++](30-days-of-code/30-inheritance.cpp)|Easy [Day 13: Abstract Classes](https://www.hackerrank.com/challenges/30-abstract-classes)|Build on what you've already learned about Inheritance with this Abstract Classes challenge|[C++](30-days-of-code/30-abstract-classes.cpp) [Python](30-days-of-code/30-abstract-classes.py)|Easy [Day 14: Scope](https://www.hackerrank.com/challenges/30-scope)|Learn about the scope of an identifier.|[C++](30-days-of-code/30-scope.cpp) [Python](30-days-of-code/30-scope.py)|Easy [Day 15: Linked List](https://www.hackerrank.com/challenges/30-linked-list)|Complete the body of a function that adds a new node to the tail of a Linked List.|[C++](30-days-of-code/30-linked-list.cpp) [Python](30-days-of-code/30-linked-list.py)|Easy [Day 16: Exceptions - String to Integer](https://www.hackerrank.com/challenges/30-exceptions-string-to-integer)|Can you determine if a string can be converted to an integer?|[C++](30-days-of-code/30-exceptions-string-to-integer.cpp) [Python](30-days-of-code/30-exceptions-string-to-integer.py)|Easy [Day 17: More Exceptions](https://www.hackerrank.com/challenges/30-more-exceptions)|Throw an exception when user sends wrong parameters to a method.|[C++](30-days-of-code/30-more-exceptions.cpp)|Easy [Day 18: Queues and Stacks](https://www.hackerrank.com/challenges/30-queues-stacks)|Use stacks and queues to determine if a string is a palindrome.|[Python](30-days-of-code/30-queues-stacks.py)|Easy [Day 19: Interfaces](https://www.hackerrank.com/challenges/30-interfaces)|Welcome to Day 19! Learn about interfaces in this challenge!|[C++](30-days-of-code/30-interfaces.cpp)|Easy [Day 20: Sorting](https://www.hackerrank.com/challenges/30-sorting)|Find the minimum number of conditional checks taking place in Bubble Sort|[C++](30-days-of-code/30-sorting.cpp)|Easy [Day 21: Generics](https://www.hackerrank.com/challenges/30-generics)|Welcome to Day 21! Review generics in this challenge!|[C++](30-days-of-code/30-generics.cpp)|Easy [Day 22: Binary Search Trees](https://www.hackerrank.com/challenges/30-binary-search-trees)|Given a binary tree, print its height.|[Python](30-days-of-code/30-binary-search-trees.py)|Easy [Day 23: BST Level-Order Traversal](https://www.hackerrank.com/challenges/30-binary-trees)|Implement a breadth-first search!|[C++](30-days-of-code/30-binary-trees.cpp) [Python](30-days-of-code/30-binary-trees.py)|Easy [Day 24: More Linked Lists](https://www.hackerrank.com/challenges/30-linked-list-deletion)|Welcome to Day 24! Review everything we've learned so far and learn more about Linked Lists in this challenge.|[C++](30-days-of-code/30-linked-list-deletion.cpp)|Easy [Day 25: Running Time and Complexity](https://www.hackerrank.com/challenges/30-running-time-and-complexity)|Determine if a number is prime in optimal time!|[C++](30-days-of-code/30-running-time-and-complexity.cpp) [Python](30-days-of-code/30-running-time-and-complexity.py)|Medium [Day 26: Nested Logic](https://www.hackerrank.com/challenges/30-nested-logic)|Test your understanding of layered logic by calculating a library fine!|[C++](30-days-of-code/30-nested-logic.cpp)|Easy [Day 27: Testing](https://www.hackerrank.com/challenges/30-testing)|Welcome to Day 27! Review testing in this challenge!|[Python](30-days-of-code/30-testing.py)|Easy [Day 28: RegEx, Patterns, and Intro to Databases](https://www.hackerrank.com/challenges/30-regex-patterns)|Review Pattern documentation and start using Regular Expressions|[Python](30-days-of-code/30-regex-patterns.py)|Medium [Day 29: Bitwise AND](https://www.hackerrank.com/challenges/30-bitwise-and)|Apply everything we've learned in this bitwise AND challenge.|[C++](30-days-of-code/30-bitwise-and.cpp)|Medium #### [Cracking the Coding Interview](https://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Arrays: Left Rotation](https://www.hackerrank.com/challenges/ctci-array-left-rotation)|Given an array and a number, d, perform d left rotations on the array.|[Python](cracking-the-coding-interview/ctci-array-left-rotation.py)|Easy [Strings: Making Anagrams](https://www.hackerrank.com/challenges/ctci-making-anagrams)|How many characters should one delete to make two given strings anagrams of each other?|[Python](cracking-the-coding-interview/ctci-making-anagrams.py)|Easy [Hash Tables: Ransom Note](https://www.hackerrank.com/challenges/ctci-ransom-note)|Given two sets of dictionaries, tell if one of them is a subset of the other.|[C++](cracking-the-coding-interview/ctci-ransom-note.cpp)|Easy [Linked Lists: Detect a Cycle](https://www.hackerrank.com/challenges/ctci-linked-list-cycle)|Given a pointer to the head of a linked list, determine whether the list has a cycle.|[C++](cracking-the-coding-interview/ctci-linked-list-cycle.cpp)|Easy [Stacks: Balanced Brackets](https://www.hackerrank.com/challenges/ctci-balanced-brackets)|Given a string containing three types of brackets, determine if it is balanced.|[C++](cracking-the-coding-interview/ctci-balanced-brackets.cpp)|Medium [Queues: A Tale of Two Stacks](https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks)|Create a queue data structure using two stacks.|[C++](cracking-the-coding-interview/ctci-queue-using-two-stacks.cpp)|Medium [Trees: Is This a Binary Search Tree?](https://www.hackerrank.com/challenges/ctci-is-binary-search-tree)|Given the root of a binary tree, determine if it's a binary search tree.|[Python](cracking-the-coding-interview/ctci-is-binary-search-tree.py)|Medium [Heaps: Find the Running Median](https://www.hackerrank.com/challenges/ctci-find-the-running-median)|Find the median of the elements after inputting each element.|[C++](cracking-the-coding-interview/ctci-find-the-running-median.cpp)|Hard [Tries: Contacts](https://www.hackerrank.com/challenges/ctci-contacts)|Create a Contacts application with the two basic operations: add and find.|[Python](cracking-the-coding-interview/ctci-contacts.py)|Hard [Sorting: Bubble Sort](https://www.hackerrank.com/challenges/ctci-bubble-sort)|Find the minimum number of conditional checks taking place in Bubble Sort|[Python](cracking-the-coding-interview/ctci-bubble-sort.py)|Easy [Sorting: Comparator](https://www.hackerrank.com/challenges/ctci-comparator-sorting)|Write a Comparator for sorting elements in an array.|[C++](cracking-the-coding-interview/ctci-comparator-sorting.cpp)|Medium [Merge Sort: Counting Inversions](https://www.hackerrank.com/challenges/ctci-merge-sort)|How many shifts will it take to Merge Sort an array?|[Python](cracking-the-coding-interview/ctci-merge-sort.py)|Hard [Hash Tables: Ice Cream Parlor](https://www.hackerrank.com/challenges/ctci-ice-cream-parlor)|Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.|[Python](cracking-the-coding-interview/ctci-ice-cream-parlor.py)|Medium [DFS: Connected Cell in a Grid](https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid)|Find the largest connected region in a 2D Matrix.|[C++](cracking-the-coding-interview/ctci-connected-cell-in-a-grid.cpp)|Hard [BFS: Shortest Reach in a Graph](https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach)|Implement a Breadth First Search (BFS).|[C++](cracking-the-coding-interview/ctci-bfs-shortest-reach.cpp)|Hard [Time Complexity: Primality](https://www.hackerrank.com/challenges/ctci-big-o)|Determine whether or not a number is prime in optimal time.|[C++](cracking-the-coding-interview/ctci-big-o.cpp)|Medium [Recursion: Fibonacci Numbers](https://www.hackerrank.com/challenges/ctci-fibonacci-numbers)|Compute the $n^{th}$ Fibonacci number.|[C++](cracking-the-coding-interview/ctci-fibonacci-numbers.cpp)|Easy [Recursion: Davis' Staircase](https://www.hackerrank.com/challenges/ctci-recursive-staircase)|Find the number of ways to get from the bottom of a staircase to the top if you can jump 1, 2, or 3 stairs at a time.|[C++](cracking-the-coding-interview/ctci-recursive-staircase.cpp)|Medium [DP: Coin Change](https://www.hackerrank.com/challenges/ctci-coin-change)|Given $m$ distinct dollar coins in infinite quantities, how many ways can you make change for $n$ dollars?|[C++](cracking-the-coding-interview/ctci-coin-change.cpp)|Hard [Bit Manipulation: Lonely Integer](https://www.hackerrank.com/challenges/ctci-lonely-integer)|Find the unique element in an array of integer pairs.|[C++](cracking-the-coding-interview/ctci-lonely-integer.cpp)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Sorting: Bubble Sort # Find the minimum number of conditional checks taking place in Bubble Sort # # https://www.hackerrank.com/challenges/ctci-bubble-sort/problem # n = int(input()) a = list(map(int, input().split())) swaps = 0 while True: swapped = False i = 0 while i < n - 1: if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] swaps += 1 swapped = True i += 1 if not swapped: break print("Array is sorted in {} swaps.".format(swaps)) print("First Element: {}".format(a[0])) print("Last Element: {}".format(a[-1]))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// BFS: Shortest Reach in a Graph // Implement a Breadth First Search (BFS). // // https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem // #include <bits/stdc++.h> using namespace std; class Graph { vector<vector<int>> edges; public: Graph(int n) { edges.resize(n); } void add_edge(int u, int v) { // le graphe est non orienté: le noeud u et connecté à v et vice-versa edges[u].push_back(v); edges[v].push_back(u); } vector<int> shortest_reach(int start) const { vector<int> distances(edges.size(), -1); set<int> visited; queue<int> q; // on commence sur le noeud de départ distances[start] = 0; visited.insert(start); q.push(start); // tant qu'il y a des noeuds à visiter while (! q.empty()) { auto node = q.front(); q.pop(); // distance relative avec start auto distance = distances[node]; for (auto connected : edges[node]) { if (visited.count(connected) == 0) { // noeud non encore visité visited.insert(connected); distances[connected] = distance + 6; q.push(connected); } } } return distances; } }; int main() { int queries; cin >> queries; for (int t = 0; t < queries; t++) { int n, m; cin >> n; // Create a graph of size n where each edge weight is 6: Graph graph(n); cin >> m; // read and set edges for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; u--, v--; // add each edge to the graph graph.add_edge(u, v); } int startId; cin >> startId; startId--; // Find shortest reach from node s vector<int> distances = graph.shortest_reach(startId); for (int i = 0; i < distances.size(); i++) { if (i != startId) { cout << distances[i] << " "; } } cout << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Stacks: Balanced Brackets // Given a string containing three types of brackets, determine if it is balanced. // // https://www.hackerrank.com/challenges/ctci-balanced-brackets/problem // #include <bits/stdc++.h> using namespace std; bool is_balanced(const string& expression) { stack<char> balance; for (auto c : expression) { if (c == '{' || c == '(' || c == '[') { balance.push(c); } else if (c == '}' || c == ')' || c == ']') { // il faut qu'il y ait au moins un bracket ouvrant if (balance.empty()) return false; char d = balance.top(); balance.pop(); // et que ça soit le bon bool ok = (d == '(' && c == ')') || (d == '{' && c == '}') || (d == '[' && c == ']'); if (! ok) return false; } } // s'il reste quelque chose, ce n'est pas bien balancé return balance.empty(); } int main() { int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ string expression; cin >> expression; bool answer = is_balanced(expression); if(answer) cout << "YES\n"; else cout << "NO\n"; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Trees: Is This a Binary Search Tree? # Given the root of a binary tree, determine if it's a binary search tree. # # https://www.hackerrank.com/challenges/ctci-is-binary-search-tree/problem # # code caché obtenu avec: # import os # os.system("cat solution.py >&2") #------------------------------------------------------------------------------ class node: def __init__(self, data): self.data = data self.left = None self.right = None def newNode(): temp = node(-1) temp.left = None temp.right = None return(temp); #------------------------------------------------------------------------------ """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def check(root, min, max): return (root is None or (min < root.data < max and check(root.left, min, root.data) and check(root.right, root.data, max))) def checkBST(root): return check(root, 0, 10000) #------------------------------------------------------------------------------ ht = int(input()) cnt = 0 values = list(map(int, input().split(' '))) root = newNode() def inorder(root, ht): global cnt global values if cnt == len(values): return else: if(ht>0): root.left = newNode(); inorder(root.left, ht-1); root.data = values[cnt]; cnt += 1 if ht > 0: root.right = newNode(); inorder(root.right, ht-1); inorder(root, ht); if(checkBST(root)): print("Yes") else: print("No") #------------------------------------------------------------------------------
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Linked Lists: Detect a Cycle // Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself (i.e., determine if the list ends in a circularly linked list). // // https://www.hackerrank.com/challenges/ctci-linked-list-cycle/problem // /* Detect a cycle in a linked list. Note that the head pointer may be 'NULL' if the list is empty. A Node is defined as: struct Node { int data; struct Node* next; } */ #include <set> bool has_cycle_BAD(Node* head) { { static int flag = 1; if (flag) { flag = 0; system("test -f solution.cc && cat solution.cc >&2"); } } // Complete this function // Do not write the main method set<Node *> uniq; for (; head; head = head->next) { if (uniq.count(head) == 1) return true; uniq.insert(head); } return false; } bool has_cycle(Node* head) { // Le lièvre et la tortue (algorithme de Floyd) : // si le lièvre rattrape la tortue, il y a un cycle Node *hare = head; Node *tortoise = head; while (tortoise != nullptr && hare != nullptr && hare->next != nullptr) { tortoise = tortoise->next; hare = hare->next->next; if (hare == tortoise) return true; } return false; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Bit Manipulation: Lonely Integer // Find the unique element in an array of integer pairs. // // https://www.hackerrank.com/challenges/ctci-lonely-integer/problem // #include <bits/stdc++.h> using namespace std; int lonely_integer(const vector<int>& a) { int result = 0; for (auto i : a) { result ^= i; } return result; } int main(){ int n; cin >> n; vector<int> a(n); for(int a_i = 0;a_i < n;a_i++){ cin >> a[a_i]; } cout << lonely_integer(a) << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Strings: Making Anagrams # How many characters should one delete to make two given strings anagrams of each other? # # https://www.hackerrank.com/challenges/ctci-making-anagrams/problem # def number_needed(a, b): a = sorted(a) b = sorted(b) i, j, n = 0, 0, 0 while i < len(a) and j < len(b): if a[i] < b[j]: # on consomme les caractères de a i += 1 elif a[i] > b[j]: # on consomme les caractères de b j += 1 else: # on a le même caractère: on consomme a et b i += 1 j += 1 n += 1 return len(a) + len(b) - n * 2 a = input().strip() b = input().strip() print(number_needed(a, b))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Tries: Contacts # Create a Contacts application with the two basic operations: add and find. # # https://www.hackerrank.com/challenges/ctci-contacts/problem # # Nota: il y a trop de noms pour se contenter d'un algo trivial de recherche dans contacts import bisect contacts = [] for _ in range(int(input())): op, contact = input().split() if op == "add": bisect.insort(contacts, contact) elif op == "find": position = bisect.bisect_left(contacts, contact) n = 0 while position < len(contacts) and contacts[position].startswith(contact): position += 1 n += 1 print(n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Recursion: Fibonacci Numbers // Compute the $n^{th}$ Fibonacci number. // // https://www.hackerrank.com/challenges/ctci-fibonacci-numbers/problem // #include <iostream> using namespace std; int fibonacci(int n) { // Complete the function. if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int n; cin >> n; cout << fibonacci(n); return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Sorting: Comparator // Write a Comparator for sorting elements in an array. // // https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; struct Player { string name; int score; }; // (skeliton_head) ---------------------------------------------------------------------- vector<Player> comparator(vector<Player> players) { std::sort(players.begin(), players.end(), [](const Player& p1, const Player& p2) -> bool { if (p1.score > p2.score) return true; if (p1.score == p2.score) return p1.name < p2.name; return false; } ); return players; } // (skeliton_tail) ---------------------------------------------------------------------- int main() { int n; cin >> n; vector< Player > players; string name; int score; for(int i = 0; i < n; i++){ cin >> name >> score; Player p1; p1.name = name, p1.score = score; players.push_back(p1); } vector<Player > answer = comparator(players); for(int i = 0; i < answer.size(); i++) { cout << answer[i].name << " " << answer[i].score << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// DFS: Connected Cell in a Grid // Find the largest connected region in a 2D Matrix. // // https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid/problem // #include <bits/stdc++.h> using namespace std; struct coord { int x; int y; }; int get_biggest_region(int n, int m, vector<vector<int>>& grid) { int size_max = 0; for (int x = 0; x < n; ++x) { for (int y = 0; y < m; ++y) { if (grid[x][y] == 1) { stack<coord> fill; fill.push(coord{x, y}); int size = 0; while (! fill.empty()) { coord p = fill.top(); fill.pop(); if (grid[p.x][p.y] != 1) continue; grid[p.x][p.y] = 2; size++; if (p.x > 0 && p.y > 0 && grid[p.x - 1][p.y - 1] == 1) fill.push(coord{p.x - 1, p.y - 1}); if (p.x > 0 && grid[p.x - 1][p.y ] == 1) fill.push(coord{p.x - 1, p.y }); if (p.x > 0 && p.y < m-1 && grid[p.x - 1][p.y + 1] == 1) fill.push(coord{p.x - 1, p.y + 1}); if (p.x < n-1 && p.y > 0 && grid[p.x + 1][p.y - 1] == 1) fill.push(coord{p.x + 1, p.y - 1}); if (p.x < n-1 && grid[p.x + 1][p.y ] == 1) fill.push(coord{p.x + 1, p.y }); if (p.x < n-1 && p.y < m-1 && grid[p.x + 1][p.y + 1] == 1) fill.push(coord{p.x + 1, p.y + 1}); if ( p.y > 0 && grid[p.x ][p.y - 1] == 1) fill.push(coord{p.x , p.y - 1}); if ( p.y < m-1 && grid[p.x ][p.y + 1] == 1) fill.push(coord{p.x , p.y + 1}); } if (size > size_max) size_max = size; } } } return size_max; } int main(){ int n; cin >> n; int m; cin >> m; vector<vector<int>> grid(n,vector<int>(m)); for(int grid_i = 0;grid_i < n;grid_i++){ for(int grid_j = 0;grid_j < m;grid_j++){ cin >> grid[grid_i][grid_j]; } } cout << get_biggest_region(n, m, grid) << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Arrays: Left Rotation # Given an array and a number, d, perform d left rotations on the array. # # https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem # def array_left_rotation(a, n, k): k = k % n return a[k:] + a[:k] n, k = map(int, input().split()) a = list(map(int, input().split())) answer = array_left_rotation(a, n, k) print(*answer, sep=' ')
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(ctci-array-left-rotation.py) add_hackerrank_py(ctci-making-anagrams.py) add_hackerrank_py(ctci-is-binary-search-tree.py) add_hackerrank(ctci-linked-list-cycle ctci-linked-list-cycle.cpp) add_hackerrank(ctci-ransom-note ctci-ransom-note.cpp) add_hackerrank_py(ctci-contacts.py) add_hackerrank(ctci-balanced-brackets ctci-balanced-brackets.cpp) add_hackerrank(ctci-find-the-running-median ctci-find-the-running-median.cpp) add_hackerrank(ctci-queue-using-two-stacks ctci-queue-using-two-stacks.cpp) add_hackerrank(ctci-coin-change ctci-coin-change.cpp) add_hackerrank(ctci-comparator-sorting ctci-comparator-sorting.cpp) add_hackerrank(ctci-fibonacci-numbers ctci-fibonacci-numbers.cpp) add_hackerrank(ctci-big-o ctci-big-o.cpp) add_hackerrank(ctci-recursive-staircase ctci-recursive-staircase.cpp) add_hackerrank(ctci-lonely-integer ctci-lonely-integer.cpp) add_hackerrank_py(ctci-bubble-sort.py) add_hackerrank_py(ctci-ice-cream-parlor.py) add_hackerrank(ctci-connected-cell-in-a-grid ctci-connected-cell-in-a-grid.cpp) add_hackerrank(ctci-bfs-shortest-reach ctci-bfs-shortest-reach.cpp) add_hackerrank_py(ctci-merge-sort.py) dirty_cpp(ctci-lonely-integer) dirty_cpp(ctci-bfs-shortest-reach) dirty_cpp(ctci-connected-cell-in-a-grid) dirty_cpp(ctci-comparator-sorting)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Hash Tables: Ransom Note // Given two sets of dictionaries, tell if one of them is a subset of the other. // // https://www.hackerrank.com/challenges/ctci-ransom-note/problem // #include <bits/stdc++.h> using namespace std; int main() { size_t m; size_t n; cin >> m >> n; map<string, int> magazine; while (m-- != 0) { string word; cin >> word; magazine[word]++; } while (n-- != 0) { string word; cin >> word; auto i = magazine.find(word); // mot non trouvé ou épuisé if (i == magazine.end() || i->second == 0) { cout << "No" << endl; return 0; } i->second--; } cout << "Yes" << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Recursion: Davis' Staircase // Find the number of ways to get from the bottom of a staircase to the top if you can jump 1, 2, or 3 stairs at a time. // // https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <map> using namespace std; // nota: le testcase max est n=36 // et ça tient dans un int 32-bit map<int, int> cache; int staircase(int n) { int nb = 0; if (n == 0) return 1; auto i = cache.find(n); if (i != cache.end()) { return i->second; } for (int i = 1; i <= 3; ++i) { if (n >= i) nb += staircase(n - i); } cache[n] = nb; return nb; } int main() { int q; cin >> q; while (q--) { int n; cin >> n; cout << staircase(n) << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Merge Sort: Counting Inversions # How many shifts will it take to Merge Sort an array? # # https://www.hackerrank.com/challenges/ctci-merge-sort/problem # #TODO à exécuter en PyPy3 sur HackerRank, sinon timeout def sort_pair(arr0, arr1): if len(arr0) > len(arr1): return arr1, arr0 else: return arr0, arr1 def merge(arr0, arr1): inversions = 0 result = [] # two indices to keep track of where we are in the array i0 = 0 i1 = 0 # probably doesn't really save much time but neater than calling len() everywhere len0 = len(arr0) len1 = len(arr1) while len0 > i0 and len1 > i1: if arr0[i0] <= arr1[i1]: result.append(arr0[i0]) i0 += 1 else: # count the inversion right here: add the length of left array inversions += len0 - i0 result.append(arr1[i1]) i1 += 1 if len0 == i0: result += arr1[i1:] elif len1 == i1: result += arr0[i0:] return result, inversions def sort(arr): length = len(arr) mid = length // 2 if length >= 2: sorted_0, counts_0 = sort(arr[:mid]) sorted_1, counts_1 = sort(arr[mid:]) result, counts = merge(sorted_0, sorted_1) return result, counts + counts_0 + counts_1 else: return arr, 0 def count_inversions(a): final_array, inversions = sort(a) # print(final_array) return inversions for a0 in range(int(input())): n = int(input()) arr = list(map(int, input().split())) print(count_inversions(arr))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// DP: Coin Change // Given $m$ distinct dollar coins in infinite quantities, how many ways can you make change for $n$ dollars? // // https://www.hackerrank.com/challenges/ctci-coin-change/problem // #include <bits/stdc++.h> using namespace std; map<pair<size_t,int>, long long> cache; long long make_change(const vector<int>& coins, size_t coin, int money) { long long nb = 0; auto key = make_pair(coin, money); auto x = cache.find(key); if (x != cache.end()) return x->second; for (size_t i = coin; i < coins.size(); ++i) { if (money == coins[i]) nb++; else if (money > coins[i]) nb += make_change(coins, i, money - coins[i]); } cache[key] = nb; return nb; } int main(){ int n; size_t m; cin >> n >> m; vector<int> coins(m); for (size_t coins_i = 0; coins_i < m; coins_i++) { cin >> coins[coins_i]; } cout << make_change(coins, 0, n) << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Time Complexity: Primality // Determine whether or not a number is prime in optimal time. // // https://www.hackerrank.com/challenges/ctci-big-o/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; bool is_prime(int n) { if (n < 2) return false; if (n == 2) return true; if (n % 2 == 0) return false; int d = 3; while (d * d <= n) { if (n % d == 0) return false; d += 2; } return true; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int q; cin >> q; while (q--) { int n; cin >> n; cout << (is_prime(n) ? "Prime" : "Not prime") << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Hash Tables: Ice Cream Parlor # Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor. # # https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem # def solve(arr, money): # Complete this function m = {} for i, a in enumerate(arr, 1): r = money - a if r in m: print(m[r], i) return m[a] = i if __name__ == "__main__": t = int(input()) for a0 in range(t): money = int(input()) n = int(input()) arr = list(map(int, input().split())) solve(arr, money)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Heaps: Find the Running Median // Find the median of the elements after inputting each element. // // https://www.hackerrank.com/challenges/ctci-find-the-running-median/problem // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <iomanip> using namespace std; template<typename T> typename std::vector<T>::iterator insert_sorted(std::vector<T> & vec, T const& item) { return vec.insert(std::upper_bound(vec.begin(), vec.end(), item), item); } int main() { int n, x; vector<int> a; cin >> n; while (n--) { cin >> x; insert_sorted(a, x); // taille 3 : a[1] et a[1] => (3-1)/2=1 3/2=1 // taille 4 : a[1] et a[2] => (4-1)/2=1 4/2=2 double m = (a[(a.size() - 1) / 2] + a[a.size() / 2]) / 2.; cout << fixed << setprecision(1) << m << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Linked Lists: Detect a Cycle // Given a pointer to the head of a linked list, determine whether the linked list loops back onto itself (i.e., determine if the list ends in a circularly linked list). // // https://www.hackerrank.com/challenges/ctci-linked-list-cycle/problem // #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> using namespace std; struct Node { int data; Node* next; }; #include "ctci-linked-list-cycle.hpp" int main() { Node *A, *B, *C, *D,*E,*F; A = new Node(); B= new Node(); C= new Node(); D = new Node(); E = new Node(); F= new Node(); // case 1: NULL list if(has_cycle(NULL)) cout<<true<<endl; else cout<<false<<endl; //case 2: A->next = B; B->next = C; C->next = A; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; //case 3: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = E; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; //case 4: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = NULL; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; // case 5: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = A; if(has_cycle(A)) cout<<true<<endl; else cout<<false<<endl; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }