├── .vscode ├── settings.json └── tasks.json ├── Back to back SWE ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Codechef ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Coding Blocks ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Coding Patterns ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Cracking The Coding Interview └── Easy │ ├── checkPermutation │ └── checkPermutation.js │ └── isUnique │ ├── hashMapApproach.js │ └── sortingApproach.js ├── DS Implementations ├── Graphs │ ├── a.exe │ ├── adjacency-list-vectors.cpp │ ├── adjacency-list.cpp │ ├── adjacency-matrix-class.cpp │ ├── adjacency-matrix-dummy.cpp │ ├── bfs.cpp │ └── dfs.cpp ├── Heap │ ├── a.exe │ ├── extract-min-decrease-key.cpp │ ├── heap-sort.cpp │ ├── min-heap-bottom-up.cpp │ └── min-heap-top-down.cpp ├── Linked List │ ├── a.exe │ ├── circular-linked-list-class.cpp │ ├── circular-linked-list-structure.cpp │ ├── doubly-linked-list-class.cpp │ ├── doubly-linked-list-structure.cpp │ ├── linkedListExample.cpp │ ├── singly-linked-list-class.cpp │ └── singly-linked-list-structure.cpp ├── Queue │ ├── a.exe │ ├── queue-array-class.cpp │ ├── queue-array-structure.cpp │ ├── queue-linkedlist-class.cpp │ └── queue-linkedlist-structure.cpp ├── Tree │ ├── a.exe │ ├── binary-search-tree-class.cpp │ ├── binary-search-tree-structure.cpp │ ├── binary-tree-traversals-class.cpp │ └── binary-tree-traversals-structure.cpp ├── map │ ├── a.exe │ ├── map.cpp │ └── unordered_map.cpp ├── set │ ├── a.exe │ ├── set.cpp │ └── unordered_set.cpp ├── stack │ ├── a.exe │ ├── stack-array-class.cpp │ ├── stack-array-structure.cpp │ ├── stack-linkedlist-class.cpp │ ├── stack-linkedlist-structure.cpp │ └── stack_stl.cpp └── vectors │ ├── a.exe │ └── vectors.cpp ├── FreeCodeCamp ├── Advanced Algorithm Scripting │ └── .keep ├── Basic Algorithm Scripting │ ├── .keep │ ├── Boo who │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Confirm the Ending │ │ ├── code.js │ │ ├── code2.js │ │ ├── problem.md │ │ └── solution.md │ ├── Convert Celsius to Fahrenheit │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Factorialize a number │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Find the Longest Word in a String │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Finders Keepers │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Repeat a String Repeat a String │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Return Largest Numbers In Array │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Reverse a string │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ ├── Title Case A Sentence │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md │ └── Truncate A String │ │ ├── code.js │ │ ├── problem.md │ │ └── solution.md └── Intermediate Algorithm Scripting │ └── .keep ├── Geeks For Geeks ├── Easy │ ├── .keep │ └── keypad specified sequence problem ├── Hard │ └── .keep └── Medium │ └── .keep ├── Hackerearth ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Hackerrank ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Important Interview Questions ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Interview Algorithms ├── .gitignore ├── Easy │ ├── .keep │ ├── Binary Search │ │ ├── code-iterative │ │ ├── code-iterative.cpp │ │ ├── code-recursive.cpp │ │ ├── problem.md │ │ └── tempCodeRunnerFile │ ├── Branch Sum │ │ ├── a.exe │ │ ├── code.cpp │ │ └── problem.md │ ├── Bubble Sort │ │ ├── a.exe │ │ ├── code.cpp │ │ └── problem.md │ ├── Caesar Cipher Encryptor │ │ ├── code-2.cpp │ │ ├── code.cpp │ │ └── problem.md │ ├── Closest in a BST │ │ ├── code-iterative.cpp │ │ ├── code-recursive.cpp │ │ └── problem.md │ ├── Depth First Search │ │ ├── code.cpp │ │ └── problem.md │ ├── Find Three Largest Numbers │ │ ├── a.exe │ │ ├── code.cpp │ │ └── problem.md │ ├── Insertion Sort │ │ ├── a.exe │ │ ├── code.cpp │ │ └── problem.md │ ├── Linked List Construction │ │ ├── code.cpp │ │ └── problem.md │ ├── Node Depths │ │ ├── a.exe │ │ ├── code-iterative.cpp │ │ ├── code-recursive.cpp │ │ └── problem.md │ ├── Nth Fibonacci │ │ ├── code-iterative.cpp │ │ ├── code-memoization.cpp │ │ ├── code.cpp │ │ └── problem.md │ ├── Palindrome Check │ │ ├── a.exe │ │ ├── array-split-join-approach-code.cpp │ │ ├── problem.md │ │ ├── recursive-code.cpp │ │ ├── reversed-approach-code.cpp │ │ └── two-pointer-code.cpp │ ├── Product Sum │ │ ├── code.cpp │ │ └── problem.md │ ├── Selection Sort │ │ ├── code.cpp │ │ └── problem.md │ ├── Two Number Sum │ │ ├── code.cpp │ │ ├── code2.cpp │ │ ├── code3.cpp │ │ ├── problem.md │ │ └── solution.md │ └── Validate Subsequence │ │ ├── code.cpp │ │ ├── code2.cpp │ │ ├── code3.cpp │ │ ├── problem.md │ │ └── solution.md ├── Hard │ ├── .keep │ ├── Four Number Sum │ │ ├── code.cpp │ │ └── problem.md │ ├── Largest Range │ │ ├── code.cpp │ │ └── problem.md │ └── Subarray Sort │ │ ├── code.cpp │ │ └── problem.md └── Medium │ ├── .keep │ ├── BST Construction │ ├── code-iterative.cpp │ ├── code-recursive.cpp │ └── problem.md │ ├── BST traversal │ ├── code.cpp │ └── problem.md │ ├── Balanced Brackets │ ├── code.cpp │ └── problem.md │ ├── Breadth First Search │ ├── code.cpp │ └── problem.md │ ├── Group Anagrams │ ├── code.cpp │ └── code2.cpp │ ├── Invert Binary Tree │ ├── code-iterative.cpp │ ├── code-recursive.cpp │ └── problem.md │ ├── Kadane's Algorithm │ ├── code-dp.cpp │ └── problem.md │ ├── Levenshtein Distance - Min Edits Required To Make One String To Another │ ├── code-dp-2.cpp │ ├── code-dp.cpp │ └── problem.md │ ├── Longest Palindromic Substring │ ├── code.cpp │ ├── code2.cpp │ └── problem.md │ ├── Longest Peak │ ├── code.cpp │ └── problem.md │ ├── Max Subset Sum No Adjacent - DP │ ├── a.exe │ ├── code-dp-better.cpp │ ├── code-dp.cpp │ └── problem.md │ ├── Min Heap │ ├── code.cpp │ └── problem.md │ ├── Min Height BST │ ├── code-optimized-insertion.cpp │ ├── code-return-bst.cpp │ ├── code.cpp │ └── problem.md │ ├── Min Max Stack │ ├── code.cpp │ └── problem.md │ ├── Min Number Of Couns For Change │ ├── code.cpp │ └── problem.md │ ├── Monotonic Array │ ├── code-2.cpp │ ├── code.cpp │ └── problem.md │ ├── Move Element To End │ ├── a.exe │ ├── code.cpp │ └── problem.md │ ├── Number Of Ways To Make Change │ ├── code.cpp │ └── problem.md │ ├── Permutations │ ├── code-2.cpp │ ├── code.cpp │ └── problem.md │ ├── Remove nth Node Fron Linked List │ ├── code.cpp │ └── problem.md │ ├── River Sizes │ ├── code.cpp │ └── problem.md │ ├── Search In Sorted Matrix │ ├── code.cpp │ └── problem.md │ ├── Single Cycle Check │ ├── code.cpp │ └── problem.md │ ├── Smallest Difference │ ├── code.cpp │ └── problem.md │ ├── Spiral Traversal │ ├── a.exe │ ├── code-recursive.cpp │ └── code.cpp │ ├── Suffix Trie │ └── code.cpp │ ├── Three Number Sum │ ├── code.cpp │ └── problem.md │ ├── Validate BST │ ├── code.cpp │ └── problem.md │ ├── Youngest Common Ancestor │ ├── code.cpp │ └── problem.md │ └── powerset │ ├── code-iterative.cpp │ ├── code-recursive.cpp │ └── problem.md ├── Interview Cake ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Interview Camp └── .keep ├── Leetcode Interview Questions ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Leetcode ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep ├── Prepbytes ├── Easy │ ├── .keep │ ├── Birthday Gift │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Character Value │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Floyd Cycle │ │ └── code.cpp │ ├── Leap Year or Not │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Median of Sorted Array │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Modulus Ten │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Multiply Numbers │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Number of Occurences │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Operators │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Pattern Matching Naive │ │ ├── a.exe │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Reverse A Doubly Linked List │ │ └── code.cpp │ └── Transition Point │ │ ├── a.exe │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md ├── Hard │ ├── .keep │ ├── Fit Square │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ ├── Shopping Cost │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md │ └── Ten from Two │ │ ├── code.cpp │ │ ├── problem.md │ │ └── solution.md └── Medium │ ├── .keep │ ├── Boxes and Toys │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Buddy and Socks │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Clocks and Angles │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Find Closest Pair │ ├── a.exe │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Find The Window │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Infix To Postfix Conversion │ ├── a.exe │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Journey of Bablu and Dablu │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── KMP Algorithm │ ├── a.exe │ └── code.cpp │ ├── Knight Tour Problem │ ├── a.exe │ ├── code.cpp │ ├── problem.md │ └── solution.md │ ├── Rabin Karp │ ├── a.exe │ └── code.cpp │ ├── Second Smallest │ ├── code.cpp │ ├── problem.md │ └── solution.md │ └── Two Stacks In One Array │ ├── code.cpp │ └── problem.md ├── README.md ├── Textbook Algorithms ├── Easy │ └── .keep ├── Hard │ └── .keep └── Medium │ └── .keep └── palindrome-number ├── README.md └── palindrome-number.cpp /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "ostream": "cpp", 4 | "*.tcc": "cpp", 5 | "deque": "cpp", 6 | "list": "cpp", 7 | "string": "cpp", 8 | "unordered_map": "cpp", 9 | "unordered_set": "cpp", 10 | "vector": "cpp", 11 | "bitset": "cpp", 12 | "iostream": "cpp", 13 | "ratio": "cpp", 14 | "system_error": "cpp", 15 | "array": "cpp", 16 | "functional": "cpp", 17 | "tuple": "cpp", 18 | "type_traits": "cpp", 19 | "utility": "cpp", 20 | "regex": "cpp", 21 | "atomic": "cpp", 22 | "cctype": "cpp", 23 | "cfenv": "cpp", 24 | "chrono": "cpp", 25 | "cinttypes": "cpp", 26 | "clocale": "cpp", 27 | "cmath": "cpp", 28 | "codecvt": "cpp", 29 | "complex": "cpp", 30 | "condition_variable": "cpp", 31 | "csetjmp": "cpp", 32 | "csignal": "cpp", 33 | "cstdarg": "cpp", 34 | "cstddef": "cpp", 35 | "cstdint": "cpp", 36 | "cstdio": "cpp", 37 | "cstdlib": "cpp", 38 | "cstring": "cpp", 39 | "ctime": "cpp", 40 | "cwchar": "cpp", 41 | "cwctype": "cpp", 42 | "forward_list": "cpp", 43 | "exception": "cpp", 44 | "algorithm": "cpp", 45 | "any": "cpp", 46 | "fstream": "cpp", 47 | "future": "cpp", 48 | "initializer_list": "cpp", 49 | "iomanip": "cpp", 50 | "iosfwd": "cpp", 51 | "istream": "cpp", 52 | "limits": "cpp", 53 | "memory": "cpp", 54 | "mutex": "cpp", 55 | "new": "cpp", 56 | "numeric": "cpp", 57 | "scoped_allocator": "cpp", 58 | "shared_mutex": "cpp", 59 | "sstream": "cpp", 60 | "stdexcept": "cpp", 61 | "streambuf": "cpp", 62 | "thread": "cpp", 63 | "typeindex": "cpp", 64 | "typeinfo": "cpp", 65 | "valarray": "cpp" 66 | }, 67 | 68 | "C_Cpp.errorSquiggles": "Disabled" 69 | } 70 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: clang++ build active file", 6 | "command": "/usr/bin/clang++", 7 | "args": [ 8 | "-fdiagnostics-color=always", 9 | "-g", 10 | "${file}", 11 | "-o", 12 | "${fileDirname}/${fileBasenameNoExtension}" 13 | ], 14 | "options": { 15 | "cwd": "${fileDirname}" 16 | }, 17 | "problemMatcher": [ 18 | "$gcc" 19 | ], 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "detail": "Task generated by Debugger." 25 | } 26 | ], 27 | "version": "2.0.0" 28 | } -------------------------------------------------------------------------------- /Back to back SWE/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Back to back SWE/Easy/.keep -------------------------------------------------------------------------------- /Back to back SWE/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Back to back SWE/Hard/.keep -------------------------------------------------------------------------------- /Back to back SWE/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Back to back SWE/Medium/.keep -------------------------------------------------------------------------------- /Codechef/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Codechef/Easy/.keep -------------------------------------------------------------------------------- /Codechef/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Codechef/Hard/.keep -------------------------------------------------------------------------------- /Codechef/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Codechef/Medium/.keep -------------------------------------------------------------------------------- /Coding Blocks/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Blocks/Easy/.keep -------------------------------------------------------------------------------- /Coding Blocks/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Blocks/Hard/.keep -------------------------------------------------------------------------------- /Coding Blocks/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Blocks/Medium/.keep -------------------------------------------------------------------------------- /Coding Patterns/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Patterns/Easy/.keep -------------------------------------------------------------------------------- /Coding Patterns/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Patterns/Hard/.keep -------------------------------------------------------------------------------- /Coding Patterns/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Coding Patterns/Medium/.keep -------------------------------------------------------------------------------- /Cracking The Coding Interview/Easy/checkPermutation/checkPermutation.js: -------------------------------------------------------------------------------- 1 | const checkPermutation = (first, second) => { 2 | if (first.length !== second.length) return false; 3 | first = first.split("").sort().join(""); 4 | second = second.split("").sort().join(""); 5 | console.log("first, second->", first, second); 6 | 7 | if (first !== second) return false; 8 | return true; 9 | }; 10 | 11 | let first = "Manu arora"; 12 | let second = "nauM arrao"; 13 | 14 | console.log(checkPermutation(first, second)); 15 | -------------------------------------------------------------------------------- /Cracking The Coding Interview/Easy/isUnique/hashMapApproach.js: -------------------------------------------------------------------------------- 1 | // Time - O(n) 2 | // Space - O(1) 3 | 4 | const isUnique = (str) => { 5 | let map = {}; 6 | let isUnique = true; 7 | 8 | [...str.split("")].forEach((strChar, idx) => { 9 | if (map[strChar]) { 10 | isUnique = false; 11 | return; 12 | } else { 13 | map[strChar] = true; 14 | } 15 | }); 16 | return isUnique; 17 | }; 18 | 19 | let str = "manu"; 20 | console.log(isUnique(str)); 21 | -------------------------------------------------------------------------------- /Cracking The Coding Interview/Easy/isUnique/sortingApproach.js: -------------------------------------------------------------------------------- 1 | const isUnique = (str) => { 2 | let sortedStr = str.split("").sort().join(""); 3 | let isUnique = true; 4 | let prevChar = ""; 5 | [...sortedStr].forEach((strChar, idx) => { 6 | if (strChar === prevChar) { 7 | isUnique = false; 8 | return; 9 | } else { 10 | prevChar = strChar; 11 | } 12 | }); 13 | return isUnique; 14 | }; 15 | 16 | let str = "abcdefhghijklmnopqrstuvwxyz"; 17 | console.log(isUnique(str)); 18 | -------------------------------------------------------------------------------- /DS Implementations/Graphs/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/Graphs/a.exe -------------------------------------------------------------------------------- /DS Implementations/Graphs/adjacency-list-vectors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void addEdge(vector adj[], int u, int v) 6 | { 7 | adj[u].push_back(v); 8 | adj[v].push_back(u); 9 | } 10 | 11 | void printList(vector adj[], int n) 12 | { 13 | for (int i = 0; i < n; i++) 14 | { 15 | cout << "Adjacency list of node: " << i << " is: \n"; 16 | 17 | for (auto ele : adj[i]) 18 | { 19 | cout << "-> " << ele << "\n"; 20 | } 21 | } 22 | } 23 | 24 | int main() 25 | { 26 | int n, e; 27 | cin >> n >> e; 28 | 29 | vector adj[n]; 30 | 31 | for (int i = 0; i < e; i++) 32 | { 33 | int u, v; 34 | cin >> u >> v; 35 | 36 | addEdge(adj, u, v); 37 | } 38 | 39 | printList(adj, n); 40 | } -------------------------------------------------------------------------------- /DS Implementations/Graphs/adjacency-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Graph 6 | { 7 | int nodes; 8 | list *adj; 9 | 10 | public: 11 | Graph(int n) 12 | { 13 | nodes = n; 14 | adj = new list[nodes]; 15 | } 16 | 17 | void addEdge(int u, int v) 18 | { 19 | adj[u].push_back(v); 20 | adj[v].push_back(u); 21 | } 22 | 23 | void printList() 24 | { 25 | for (int i = 0; i < nodes; i++) 26 | { 27 | cout << "Adjacency nodes of node " << i << " is"; 28 | for (auto ele : adj[i]) 29 | { 30 | cout << "-> " << ele << endl; 31 | } 32 | } 33 | } 34 | }; 35 | 36 | int main() 37 | { 38 | int n, e; 39 | cin >> n >> e; 40 | 41 | Graph graph(n); 42 | 43 | for (int i = 0; i < n; i++) 44 | { 45 | int u, v; 46 | cin >> u >> v; 47 | graph.addEdge(u, v); 48 | } 49 | graph.printList(); 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /DS Implementations/Graphs/adjacency-matrix-class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Graph 6 | { 7 | bool **adjMat; 8 | int nodes; 9 | 10 | public: 11 | Graph(int nodes) 12 | { 13 | this->nodes = nodes; 14 | 15 | // 2d array creation 16 | adjMat = new bool *[nodes]; 17 | 18 | for (int i = 0; i < nodes; i++) 19 | { 20 | adjMat[i] = new bool[nodes]; 21 | 22 | for (int j = 0; j < nodes; j++) 23 | { 24 | adjMat[i][j] = false; 25 | } 26 | } 27 | } 28 | 29 | void addEdge(int u, int v) 30 | { 31 | adjMat[u][v] = true; 32 | adjMat[v][u] = true; 33 | } 34 | 35 | void printMat() 36 | { 37 | for (int i = 0; i < nodes; i++) 38 | { 39 | cout << "i: "; 40 | for (int j = 0; j < nodes; j++) 41 | { 42 | cout << adjMat[i][j] << " "; 43 | } 44 | cout << endl; 45 | } 46 | } 47 | }; 48 | 49 | int main() 50 | { 51 | int n, e; 52 | cin >> n >> e; 53 | 54 | Graph graph(n); 55 | for (int i = 0; i < n; i++) 56 | { 57 | int u, v; 58 | cin >> u >> v; 59 | graph.addEdge(u, v); 60 | } 61 | 62 | graph.printMat(); 63 | return 0; 64 | } -------------------------------------------------------------------------------- /DS Implementations/Graphs/adjacency-matrix-dummy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool adjMatrix[6][6]; 6 | 7 | void addEdge(int u, int v) 8 | { 9 | adjMatrix[u][v] = true; 10 | adjMatrix[v][u] = true; 11 | } 12 | 13 | void printMat() 14 | { 15 | for (int i = 0; i < 6; i++) 16 | { 17 | for (int j = 0; j < 6; j++) 18 | { 19 | cout << adjMatrix[i][j] << " "; 20 | } 21 | cout << endl; 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | for (int i = 0; i < 6; i++) 28 | { 29 | int u, v; 30 | cin >> u >> v; 31 | 32 | addEdge(u, v); 33 | } 34 | printMat(); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /DS Implementations/Graphs/bfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Graph 6 | { 7 | int V; // number of nodes 8 | list *adj; // pointer to an array containing adjacency lists 9 | 10 | public: 11 | Graph(int V) 12 | { 13 | this->V = V; 14 | adj = new list[V]; 15 | } 16 | 17 | void addEdge(int u, int v); 18 | void printList(int nodes); 19 | 20 | void BFS(int v); 21 | }; 22 | 23 | void Graph::addEdge(int u, int v) 24 | { 25 | adj[v].push_back(u); 26 | adj[u].push_back(v); 27 | } 28 | 29 | void Graph::printList(int nodes) 30 | { 31 | for (int i = 0; i < nodes; i++) 32 | { 33 | cout << "Adjacency list of nodes: " << i << " is : \n"; 34 | for (auto ele : adj[i]) 35 | { 36 | cout << "-> " << ele << endl; 37 | } 38 | } 39 | } 40 | 41 | void Graph::BFS(int v) 42 | { 43 | bool *visited = new bool[V]; 44 | 45 | for (int i = 0; i < v; i++) 46 | { 47 | visited[i] = false; 48 | } 49 | 50 | list queue; // SLL acts as queue, push_back and pop_front are used 51 | visited[v] = true; 52 | queue.push_back(v); 53 | while (!queue.empty()) 54 | { 55 | v = queue.front(); 56 | cout << v << " "; 57 | 58 | queue.pop_front(); 59 | for (auto ele : adj[v]) 60 | { 61 | if (!visited[ele]) 62 | { 63 | visited[ele] = true; 64 | queue.push_back(ele); 65 | } 66 | } 67 | } 68 | } 69 | 70 | int main() 71 | { 72 | int nodes; 73 | int edges; 74 | cin >> nodes >> edges; 75 | Graph graph(nodes); 76 | for (int i = 0; i < edges; i++) 77 | { 78 | int u, v; 79 | cin >> u >> v; 80 | graph.addEdge(u, v); 81 | } 82 | graph.BFS(0); 83 | return 0; 84 | } -------------------------------------------------------------------------------- /DS Implementations/Graphs/dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void addEdge(vector adj[], int u, int v) 6 | { 7 | adj[u].push_back(v); 8 | adj[v].push_back(u); 9 | } 10 | 11 | void printList(vector adj[], int n) 12 | { 13 | for (int i = 0; i < n; i++) 14 | { 15 | cout << "Adjacency list of node: " << i << " is : \n"; 16 | for (auto ele : adj[i]) 17 | { 18 | cout << "-> " << ele << endl; 19 | } 20 | } 21 | } 22 | 23 | void DFSRecur(vector adj[], vector &visited, int u) 24 | { 25 | visited[u] = true; 26 | cout << u << " "; 27 | 28 | for (int i = 0; i < adj[u].size(); i++) 29 | { 30 | if (visited[adj[u][i]] == false) 31 | { 32 | DFSRecur(adj, visited, adj[u][i]); 33 | } 34 | } 35 | } 36 | 37 | void DFS(vector adj[], int n) 38 | { 39 | vector visited(n, false); 40 | for (int i = 0; i < n; i++) 41 | { 42 | if (visited[i] == false) 43 | { 44 | DFSRecur(adj, visited, i); 45 | } 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | int nodes; 52 | int edges; 53 | cin >> nodes >> edges; 54 | 55 | vector adj[nodes]; 56 | for (int i = 0; i < edges; i++) 57 | { 58 | int u, v; 59 | cin >> u >> v; 60 | addEdge(adj, u, v); 61 | } 62 | DFS(adj, nodes); 63 | return 0; 64 | } -------------------------------------------------------------------------------- /DS Implementations/Heap/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/Heap/a.exe -------------------------------------------------------------------------------- /DS Implementations/Heap/heap-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int parent(int i) 6 | { 7 | return ((i - 1) / 2); 8 | } 9 | 10 | int left(int i) 11 | { 12 | return (2 * i + 1); 13 | } 14 | int right(int i) 15 | { 16 | return (2 * i + 2); 17 | } 18 | 19 | void heapify_down(int heap[], int n, int i) 20 | { 21 | int l = left(i); 22 | int r = right(i); 23 | 24 | int s = i; 25 | if (l < n && heap[l] < heap[i]) 26 | s = l; 27 | if (r < n && heap[r] < heap[s]) 28 | s = r; 29 | 30 | if (s != i) 31 | { 32 | swap(heap[i], heap[s]); 33 | heapify_down(heap, n, s); 34 | } 35 | } 36 | 37 | void build_heap(int heap[], int n) 38 | { 39 | for (int i = (n / 2 - 1); i >= 0; i--) 40 | { 41 | heapify_down(heap, n, i); 42 | } 43 | } 44 | 45 | void print_heap(int heap[], int n) 46 | { 47 | for (int i = n - 1; i >= 0; i--) 48 | { 49 | cout << heap[i] << " "; 50 | } 51 | cout << endl; 52 | } 53 | 54 | void heap_sort(int heap[], int n) 55 | { 56 | build_heap(heap, n); 57 | 58 | for (int i = n - 1; i > 0; i--) 59 | { 60 | swap(heap[0], heap[i]); 61 | heapify_down(heap, i, 0); 62 | } 63 | } 64 | 65 | int size; 66 | int main() 67 | { 68 | int t; 69 | cin >> t; 70 | 71 | while (t--) 72 | { 73 | size = 0; 74 | int n; 75 | cin >> n; 76 | 77 | int heap[n]; 78 | 79 | for (int i = 0; i < n; i++) 80 | { 81 | cin >> heap[i]; 82 | size++; 83 | } 84 | 85 | heap_sort(heap, n); 86 | print_heap(heap, n); 87 | } 88 | 89 | return 0; 90 | } -------------------------------------------------------------------------------- /DS Implementations/Heap/min-heap-bottom-up.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int parent(int i) 6 | { 7 | return ((i - 1) / 2); 8 | } 9 | 10 | int left(int i) 11 | { 12 | return (2 * i + 1); 13 | } 14 | int right(int i) 15 | { 16 | return (2 * i + 2); 17 | } 18 | 19 | void heapify_down(int heap[], int n, int i) 20 | { 21 | int l = left(i); 22 | int r = right(i); 23 | 24 | int s = i; 25 | if (l < n && heap[l] < heap[i]) 26 | s = l; 27 | if (r < n && heap[r] < heap[s]) 28 | s = r; 29 | 30 | if (s != i) 31 | { 32 | swap(heap[i], heap[s]); 33 | heapify_down(heap, n, s); 34 | } 35 | } 36 | 37 | void build_heap(int heap[], int n) 38 | { 39 | for (int i = (n / 2 - 1); i >= 0; i--) 40 | { 41 | heapify_down(heap, n, i); 42 | } 43 | } 44 | 45 | void print_heap(int heap[], int n) 46 | { 47 | for (int i = 0; i < n; i++) 48 | { 49 | cout << heap[i] << " "; 50 | } 51 | cout << endl; 52 | } 53 | 54 | int size; 55 | int main() 56 | { 57 | int t; 58 | cin >> t; 59 | 60 | while (t--) 61 | { 62 | size = 0; 63 | int n; 64 | cin >> n; 65 | 66 | int heap[n]; 67 | 68 | for (int i = 0; i < n; i++) 69 | { 70 | cin >> heap[i]; 71 | size++; 72 | } 73 | 74 | build_heap(heap, n); 75 | print_heap(heap, n); 76 | } 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /DS Implementations/Heap/min-heap-top-down.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int parent(int i) 6 | { 7 | return (i - 1) / 2; 8 | } 9 | 10 | int left(int i) 11 | { 12 | return 2 * i + 1; 13 | } 14 | 15 | int right(int i) 16 | { 17 | return 2 * i + 2; 18 | } 19 | 20 | void insert(int heap[], int i, int val) 21 | { 22 | heap[i] = val; 23 | while (i != 0 && heap[parent(i)] > heap[i]) 24 | { 25 | swap(heap[parent(i)], heap[i]); 26 | i = parent(i); 27 | } 28 | } 29 | 30 | void print_heap(int heap[], int n) 31 | { 32 | for (int i = 0; i < n; i++) 33 | { 34 | cout << heap[i] << " "; 35 | } 36 | 37 | cout << endl; 38 | } 39 | 40 | int main() 41 | { 42 | int t; 43 | cin >> t; 44 | 45 | while (t--) 46 | { 47 | int n; 48 | cin >> n; 49 | 50 | int heap[n]; 51 | int ele; 52 | for (int i = 0; i < n; i++) 53 | { 54 | cin >> ele; 55 | insert(heap, i, ele); 56 | } 57 | print_heap(heap, n); 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /DS Implementations/Linked List/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/Linked List/a.exe -------------------------------------------------------------------------------- /DS Implementations/Linked List/linkedListExample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Node structure which holds data and next pointer 4 | struct node 5 | { 6 | int data; 7 | struct node *next; 8 | } 9 | 10 | main() 11 | { 12 | // initialize Linked List 13 | struct node *head = NULL; 14 | 15 | // Create list function to create linked list 16 | head = create_list(head); 17 | return; 18 | } 19 | 20 | // method to create ll 21 | struct node *create_list(struct node *head) 22 | { 23 | struct node *newNode, *tail; 24 | 25 | tail = head; // ALso keep track of tail for o(1) insertion at the end. 26 | 27 | // Dummy insertions 28 | for (int i = 0; i <= 3; i++) 29 | { 30 | newNode = (struct node *)malloc(sizeof(struct node)); //allocate memory for new node for each node. 31 | 32 | if (!newNode) 33 | { 34 | printf("Memory erryr"); 35 | return head; 36 | } 37 | 38 | // Begin inserting Data 39 | newNode->data = i; 40 | newNode->next = NULL; 41 | 42 | // if its the first insertion then point head and tail to newnode 43 | if (head == NULL) 44 | { 45 | head = newNode; 46 | tail = newNode; 47 | } 48 | // Else insert at the last 49 | else 50 | { 51 | tail->next = newNode; 52 | tail = newNode; 53 | } 54 | return head; 55 | } 56 | } -------------------------------------------------------------------------------- /DS Implementations/Queue/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/Queue/a.exe -------------------------------------------------------------------------------- /DS Implementations/Queue/queue-linkedlist-class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | 11 | Node(int data) 12 | { 13 | this->data = data; 14 | this->next = nullptr; 15 | } 16 | }; 17 | 18 | class Queue 19 | { 20 | public: 21 | Node *front; 22 | Node *rear; 23 | 24 | Queue() 25 | { 26 | front = rear = nullptr; 27 | } 28 | 29 | void enqueue(int data) 30 | { 31 | Node *temp = new Node(data); 32 | if (rear == NULL) 33 | { 34 | front = rear = temp; 35 | return; 36 | } 37 | 38 | rear->next = temp; 39 | rear = temp; 40 | } 41 | 42 | int dequeue() 43 | { 44 | if (front == NULL) 45 | { 46 | return INT_MAX; 47 | } 48 | Node *temp = front; 49 | front = front->next; 50 | 51 | if (front == NULL) 52 | { 53 | front = rear = NULL; 54 | } 55 | 56 | int data = temp->data; 57 | 58 | free(temp); 59 | 60 | return data; 61 | } 62 | }; 63 | 64 | int main() 65 | { 66 | Queue queue; 67 | int n; 68 | cin >> n; 69 | 70 | for (int i = 0; i < n; i++) 71 | { 72 | int ele; 73 | cin >> ele; 74 | queue.enqueue(ele); 75 | } 76 | return 0; 77 | } -------------------------------------------------------------------------------- /DS Implementations/Tree/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/Tree/a.exe -------------------------------------------------------------------------------- /DS Implementations/map/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/map/a.exe -------------------------------------------------------------------------------- /DS Implementations/map/map.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void display(map m) 8 | { 9 | map::iterator itr; 10 | for (itr = m.begin(); itr != m.end(); itr++) 11 | { 12 | cout << itr->first << " " << itr->second << endl; 13 | } 14 | } 15 | 16 | int main() 17 | { 18 | map m; 19 | 20 | m.insert(make_pair(2, 10)); 21 | m[5] = 10; 22 | m[0] = 2; 23 | m.insert(make_pair(4, 13)); 24 | 25 | display(m); 26 | } -------------------------------------------------------------------------------- /DS Implementations/map/unordered_map.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void display(unordered_map m) 8 | { 9 | unordered_map::iterator itr; 10 | for (itr = m.begin(); itr != m.end(); itr++) 11 | { 12 | cout << itr->first << " " << itr->second << endl; 13 | } 14 | } 15 | 16 | int main() 17 | { 18 | unordered_map m; 19 | 20 | m.insert(make_pair(2, 10)); 21 | m[5] = 10; 22 | m[0] = 2; 23 | m.insert(make_pair(4, 13)); 24 | 25 | display(m); 26 | } -------------------------------------------------------------------------------- /DS Implementations/set/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/set/a.exe -------------------------------------------------------------------------------- /DS Implementations/set/set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void display(set s) 6 | { 7 | set::iterator itr; 8 | 9 | for (itr = s.begin(); itr != s.end(); itr++) 10 | { 11 | cout << *itr << " "; 12 | } 13 | cout << endl; 14 | } 15 | int main() 16 | { 17 | 18 | set s; 19 | 20 | s.insert(40); 21 | s.insert(20); 22 | s.insert(10); 23 | s.insert(50); 24 | s.insert(50); 25 | s.insert(1); 26 | s.insert(72); 27 | s.insert(24); 28 | s.insert(12); 29 | s.erase(10); 30 | 31 | if (s.find(50) != s.end()) 32 | { 33 | cout << "50 is there"; 34 | cout << endl; 35 | } 36 | set::iterator itr = s.find(50); 37 | cout << *itr << endl; 38 | display(s); 39 | } -------------------------------------------------------------------------------- /DS Implementations/set/unordered_set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void display(unordered_set s) 6 | { 7 | unordered_set::iterator itr; 8 | 9 | for (itr = s.begin(); itr != s.end(); itr++) 10 | { 11 | cout << *itr << " "; 12 | } 13 | cout << endl; 14 | } 15 | int main() 16 | { 17 | 18 | unordered_set s; 19 | 20 | s.insert(40); 21 | s.insert(20); 22 | s.insert(10); 23 | s.insert(50); 24 | s.insert(50); 25 | s.insert(1); 26 | s.insert(72); 27 | s.insert(24); 28 | s.insert(12); 29 | s.erase(10); 30 | 31 | if (s.find(50) != s.end()) 32 | { 33 | cout << "50 is there"; 34 | cout << endl; 35 | } 36 | unordered_set::iterator itr = s.find(50); 37 | cout << *itr << endl; 38 | display(s); 39 | } -------------------------------------------------------------------------------- /DS Implementations/stack/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/stack/a.exe -------------------------------------------------------------------------------- /DS Implementations/stack/stack-array-class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Stack 6 | { 7 | int *arr; 8 | int top; 9 | int capacity; 10 | 11 | public: 12 | Stack(int capacity) 13 | { 14 | this->capacity = capacity; 15 | arr = new int(capacity); 16 | top = -1; 17 | } 18 | 19 | int size() 20 | { 21 | return top + 1; 22 | } 23 | 24 | bool isEmpty() 25 | { 26 | return top == -1; 27 | } 28 | bool isFull() 29 | { 30 | return top + 1 == capacity; 31 | } 32 | void push(int data) 33 | { 34 | if (isFull()) 35 | { 36 | cout << "Overflow\n"; 37 | return; 38 | } 39 | top++; 40 | arr[top] = data; 41 | } 42 | 43 | int peek() 44 | { 45 | if (isEmpty()) 46 | { 47 | cout << "Stack empty"; 48 | return; 49 | } 50 | return arr[top]; 51 | } 52 | 53 | int pop() 54 | { 55 | if (isEmpty()) 56 | { 57 | cout << "Underflow\n"; 58 | return -1; 59 | } 60 | return arr[top--]; 61 | } 62 | }; 63 | 64 | int main() 65 | { 66 | int capacity, n; 67 | cin >> capacity >> n; 68 | 69 | Stack st(capacity); 70 | for (int i = 0; i < n; i++) 71 | { 72 | int ele; 73 | cin >> ele; 74 | st.push(ele); 75 | } 76 | 77 | cout << st.peek(); 78 | } -------------------------------------------------------------------------------- /DS Implementations/stack/stack-linkedlist-class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | next = NULL; 14 | } 15 | }; 16 | 17 | class Stack 18 | { 19 | Node *head; 20 | 21 | public: 22 | Stack() 23 | { 24 | head = NULL; 25 | } 26 | 27 | void push(int data) 28 | { 29 | Node *newNode = new Node(data); 30 | newNode->next = head; 31 | head = newNode; 32 | } 33 | 34 | int isEmpty() { return head == NULL } 35 | 36 | int peak() 37 | { 38 | if (isEmpty()) 39 | { 40 | cout << "Empty bruh!"; 41 | return -1; 42 | } 43 | 44 | return head->data; 45 | } 46 | 47 | int pop() 48 | { 49 | Node *temp; 50 | 51 | if (head == NULL) 52 | { 53 | cout << "Stack underflow"; 54 | return -1; 55 | } 56 | 57 | int ele = head->data; 58 | temp = head; 59 | head = head->next; 60 | free(temp); 61 | return ele; 62 | } 63 | }; 64 | 65 | int main() 66 | { 67 | // driver code goes here 68 | } -------------------------------------------------------------------------------- /DS Implementations/stack/stack-linkedlist-structure.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | typedef struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | 10 | } Node; 11 | 12 | Node *head = NULL; 13 | int size = 0; 14 | 15 | void push(int data) 16 | { 17 | Node *newNode = (Node *)malloc(sizeof(Node)); 18 | if (!newNode) 19 | { 20 | cout << "Heap size overflow!\n"; 21 | return; 22 | } 23 | newNode->data = data; 24 | newNode->next = head; 25 | head = newNode; 26 | size++; 27 | } 28 | 29 | // Check if stack is isEmpty 30 | int isEmpty() 31 | { 32 | return head == NULL; 33 | } 34 | 35 | int peek() 36 | { 37 | if (isEmpty()) 38 | return -1; 39 | return head->data; 40 | } 41 | 42 | int pop() 43 | { 44 | Node *temp; 45 | 46 | if (head == NULL) 47 | return -1; 48 | 49 | int ele = head->data; 50 | temp = head; 51 | head = head->next; 52 | free(temp); 53 | size--; 54 | return ele; 55 | } 56 | 57 | int sizeFunction() { return size; } 58 | 59 | int main() 60 | { 61 | // Driver code here 62 | } -------------------------------------------------------------------------------- /DS Implementations/stack/stack_stl.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | stack s; 9 | s.push(100); 10 | s.push(200); 11 | s.push(300); 12 | s.push(400); 13 | s.push(500); 14 | 15 | cout << s.top() << endl; 16 | 17 | s.pop(); 18 | 19 | cout << s.top() << endl; 20 | 21 | if (s.empty()) 22 | cout << "Stack is empty"; 23 | else 24 | cout << "Stack is not empty"; 25 | 26 | cout << "Stack size: " << s.size() << endl; 27 | } -------------------------------------------------------------------------------- /DS Implementations/vectors/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/DS Implementations/vectors/a.exe -------------------------------------------------------------------------------- /DS Implementations/vectors/vectors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | bool myCompare(int x, int y) 9 | { 10 | return (x < y); 11 | } 12 | 13 | int main() 14 | { 15 | vector v; 16 | 17 | int x; 18 | for (int i = 0; i < 5; i++) 19 | { 20 | cin >> x; 21 | v.push_back(x); 22 | } 23 | 24 | sort(v.begin(), v.end(), myCompare); 25 | 26 | vector::iterator itr; 27 | // for (itr = v.begin(); itr != v.end(); itr++) 28 | // { 29 | // cout << *itr << " "; 30 | // } 31 | // cout << endl; 32 | 33 | itr = v.begin() + 2; 34 | 35 | // Insert at a specific position 36 | v.insert(itr, 3, 5); // insert 5, 3 times; 37 | 38 | for (itr = v.begin(); itr != v.end(); itr++) 39 | { 40 | cout << *itr << " "; 41 | } 42 | cout << endl; 43 | 44 | // erasing from a position 45 | 46 | v.erase(v.begin() + 3, v.begin() + 5); // erase from 3 to 5 47 | for (itr = v.begin(); itr != v.end(); itr++) 48 | { 49 | cout << *itr << " "; 50 | } 51 | cout << endl; 52 | 53 | v.pop_back(); // deletes last element 54 | 55 | for (itr = v.begin(); itr != v.end(); itr++) 56 | { 57 | cout << *itr << " "; 58 | } 59 | } -------------------------------------------------------------------------------- /FreeCodeCamp/Advanced Algorithm Scripting/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/FreeCodeCamp/Advanced Algorithm Scripting/.keep -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/FreeCodeCamp/Basic Algorithm Scripting/.keep -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Boo who/code.js: -------------------------------------------------------------------------------- 1 | function booWho(bool) { 2 | return typeof bool === "boolean"; 3 | } 4 | 5 | booWho(null); 6 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Boo who/problem.md: -------------------------------------------------------------------------------- 1 | Check if a value is classified as a boolean primitive. Return true or false. 2 | 3 | Boolean primitives are true and false. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Boo who/solution.md: -------------------------------------------------------------------------------- 1 | Simple, use typeof operator -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Confirm the Ending/code.js: -------------------------------------------------------------------------------- 1 | function confirmEnding(str, target) { 2 | // "Never give up and good luck will find you." 3 | // -- Falcor 4 | 5 | return str.slice(str.length - target.length) === target; 6 | } 7 | 8 | confirmEnding("He has to give me a new name", "name"); -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Confirm the Ending/code2.js: -------------------------------------------------------------------------------- 1 | function confirmEnding(str, target) { 2 | // "Never give up and good luck will find you." 3 | // -- Falcor 4 | 5 | let re = new RegExp(target + "$", "i"); 6 | 7 | return re.test(str); 8 | } 9 | 10 | console.log(confirmEnding("Bastian", "n")); -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Confirm the Ending/problem.md: -------------------------------------------------------------------------------- 1 | Check if a string (first argument, str) ends with the given target string (second argument, target). 2 | 3 | This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Confirm the Ending/solution.md: -------------------------------------------------------------------------------- 1 | Approach: 1 2 | First we use the slice method copy the string. 3 | In order to get the last characters in str equivalent to the target's length we use the slice method. 4 | The first parameter inside the slice method is the starting index and the second parameter would be the ending index. 5 | For example str.slice(10, 17) would return give me. 6 | In this case we only include one parameter which it will copy everything from the starting index. 7 | We substract the length of str and the length of target, that way, we shall get the last remaining characters equivalent to the target's length. 8 | Finally we compare the return result of slice to target and check if they have the same characters. 9 | 10 | 11 | Approach: 2 REGEX 12 | We need to make a pattern from the target variable that exists at the end of the string str. 13 | Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object new RegExp(pattern[, flags]), so we start with: new RegExp(target). 14 | Then we have to check at the end of the string, so we concatenate to the target variable the $ character to match the end: new RegExp(target+'$'). 15 | We use the flag i to ignore the case of the pattern and we have our completed RegExp: new RegExp(target+'$','i'), or we can ommit the flag entirely. 16 | Finally, we are using our regular expression with the test method to the given string, to check if the string ends with the pattern and return true or false accordingly. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Convert Celsius to Fahrenheit/code.js: -------------------------------------------------------------------------------- 1 | function convertToF(celsius) { 2 | // Only change code below this line 3 | var fahrenheit = celsius * (9 / 5) + 32; 4 | 5 | // Only change code above this line 6 | if (typeof fahrenheit !== "undefined") { 7 | return fahrenheit; 8 | } else { 9 | return "fahrenheit not defined"; 10 | } 11 | } 12 | 13 | // Change the inputs below to test your code 14 | convertToF(30); -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Convert Celsius to Fahrenheit/problem.md: -------------------------------------------------------------------------------- 1 | The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5, plus 32. 2 | 3 | You are given a variable celsius representing a temperature in Celsius. Use the variable fahrenheit already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Convert Celsius to Fahrenheit/solution.md: -------------------------------------------------------------------------------- 1 | Use the formula celsius * ( 9 / 5 ) + 32; to convert to hahrenheit -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Factorialize a number/code.js: -------------------------------------------------------------------------------- 1 | function factorialize(num) { 2 | if(num === 0 || num === 1) return 1; 3 | for(let i = num - 1; i >=2; i--) { 4 | num = num*i; 5 | } 6 | return num; 7 | } 8 | 9 | factorialize(5); 10 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Factorialize a number/problem.md: -------------------------------------------------------------------------------- 1 | Return the factorial of the provided integer. 2 | 3 | If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. 4 | 5 | Factorials are often represented with the shorthand notation n! 6 | 7 | For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 8 | 9 | Only integers greater than or equal to zero will be supplied to the function. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Factorialize a number/solution.md: -------------------------------------------------------------------------------- 1 | Used iterative method here. 2 | Iteratate from (number - 1) to 2 3 | for every iteration perfom number = number * i; -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Find the Longest Word in a String/code.js: -------------------------------------------------------------------------------- 1 | function findLongestWordLength(str) { 2 | let length = -Infinity; 3 | let strArray = str.split(" "); 4 | 5 | for(let i = 0; i < strArray.length; i++) { 6 | // console.log(strArray[word]); 7 | if(strArray[i].length > length) length = strArray[i].length; 8 | } 9 | // console.log(strArray); 10 | return length; 11 | 12 | } 13 | 14 | findLongestWordLength("The quick brown fox jumped over the lazy dog"); 15 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Find the Longest Word in a String/problem.md: -------------------------------------------------------------------------------- 1 | Return the length of the longest word in the provided sentence. 2 | 3 | Your response should be a number. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Find the Longest Word in a String/solution.md: -------------------------------------------------------------------------------- 1 | 1. Convert the given string into an array. 2 | 2. Check if the length of the word is greater than the current global length variable 3 | 3. If YES then reassign the global length variable to current length; else --> increment i 4 | 5 | Time: O(n) for string iteration -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Finders Keepers/code.js: -------------------------------------------------------------------------------- 1 | function findElement(arr, func) { 2 | 3 | for(let i = 0; i < arr.length; i++) { 4 | if(func(arr[i])) return arr[i] 5 | } 6 | 7 | 8 | return undefined; 9 | } 10 | 11 | findElement([1, 2, 3, 4], num => num % 2 === 0); 12 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Finders Keepers/problem.md: -------------------------------------------------------------------------------- 1 | Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Finders Keepers/solution.md: -------------------------------------------------------------------------------- 1 | Since a function is passed which either returns true or false (if the number is even it returns true), 2 | We iterate over the array and find the number which is even. 3 | 4 | if(func(arr[i])) // This returns true or false, we return true if TRUE 5 | else we return undefined. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Repeat a String Repeat a String/code.js: -------------------------------------------------------------------------------- 1 | function repeatStringNumTimes(str, num) { 2 | if(num <= 0) return ""; 3 | let initial = str; 4 | for(let i = 0; i < num - 1; i++) { 5 | str = str + initial; 6 | } 7 | 8 | return str; 9 | } 10 | 11 | repeatStringNumTimes("*", 8); 12 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Repeat a String Repeat a String/problem.md: -------------------------------------------------------------------------------- 1 | Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Repeat a String Repeat a String/solution.md: -------------------------------------------------------------------------------- 1 | This is a naive approach 2 | Let initial = provided string 3 | 4 | iterate `num` number of times and append the initial string at the end of the string 5 | `str = str + initial` 6 | 7 | return the string -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Return Largest Numbers In Array/code.js: -------------------------------------------------------------------------------- 1 | function largestOfFour(arr) { 2 | let result = []; 3 | 4 | for(let i = 0; i < 4; i++) { 5 | let length = -Infinity; 6 | for(let j = 0; j < arr[i].length; j++) { 7 | if(arr[i][j] > length) length = arr[i][j]; 8 | } 9 | result.push(length); 10 | } 11 | console.log(result); 12 | return result; 13 | } 14 | 15 | largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]); 16 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Return Largest Numbers In Array/problem.md: -------------------------------------------------------------------------------- 1 | Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. 2 | 3 | Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Return Largest Numbers In Array/solution.md: -------------------------------------------------------------------------------- 1 | Initialize a global length variable to -Infinity 2 | Iterate through the inner subarrays and find the largest number using comparision. 3 | Reset the length variable for each subarray. 4 | 5 | Time: O(n) because the number of subarrays are limited to 4 therefore it is constant time for the outer loop, For the inner loop its O(n) -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Reverse a string/code.js: -------------------------------------------------------------------------------- 1 | function reverseString(str) { 2 | return str.split("").reverse().join(""); 3 | } 4 | 5 | reverseString("hello"); 6 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Reverse a string/problem.md: -------------------------------------------------------------------------------- 1 | Reverse the provided string. 2 | 3 | You may need to turn the string into an array before you can reverse it. 4 | 5 | Your result must be a string. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Reverse a string/solution.md: -------------------------------------------------------------------------------- 1 | use split("") to split the string into array 2 | use reverse() to reverse the array order 3 | use join("") to join back to form a string -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Title Case A Sentence/code.js: -------------------------------------------------------------------------------- 1 | function titleCase(str) { 2 | str = str.toLowerCase() 3 | .split(' ') 4 | .map((s) => s.charAt(0).toUpperCase() + s.substring(1)) 5 | .join(' '); 6 | 7 | return str; 8 | } 9 | 10 | titleCase("I'm a little tea pot"); 11 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Title Case A Sentence/problem.md: -------------------------------------------------------------------------------- 1 | Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. 2 | 3 | For the purpose of this exercise, you should also capitalize connecting words like "the" and "of". -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Title Case A Sentence/solution.md: -------------------------------------------------------------------------------- 1 | Simple run a map loop after splitting the string into an array of strings (using split()) 2 | Find the first character with charAt(0) and toUpperCase() it, after doing so, merge the substring after with substring(1) 3 | 4 | Finally join the array back to a string with spaces with join(" ") 5 | 6 | return string -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Truncate A String/code.js: -------------------------------------------------------------------------------- 1 | function truncateString(str, num) { 2 | if(num < str.length) { 3 | let substring = str.substr(0, num); 4 | substring = substring + "..."; 5 | console.log(substring); 6 | return substring; 7 | } 8 | else { 9 | 10 | return str; 11 | } 12 | } 13 | 14 | truncateString("A-tisket a-tasket A green and yellow basket", 8); 15 | -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Truncate A String/problem.md: -------------------------------------------------------------------------------- 1 | Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending. -------------------------------------------------------------------------------- /FreeCodeCamp/Basic Algorithm Scripting/Truncate A String/solution.md: -------------------------------------------------------------------------------- 1 | Check if the number is less than length of the string 2 | if yes, use the substr(index, upto_index) method to extract substring 3 | Append "..." at the end of the substring and return result. 4 | 5 | -------------------------------------------------------------------------------- /FreeCodeCamp/Intermediate Algorithm Scripting/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/FreeCodeCamp/Intermediate Algorithm Scripting/.keep -------------------------------------------------------------------------------- /Geeks For Geeks/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Geeks For Geeks/Easy/.keep -------------------------------------------------------------------------------- /Geeks For Geeks/Easy/keypad specified sequence problem: -------------------------------------------------------------------------------- 1 | //program to convert string to keyboard specified sequence : love babbar sheet problems 2 | 3 | #include 4 | using namespace std; 5 | 6 | string KeypadSequenceConverter(string str[], string input) 7 | { 8 | int n=input.size(); 9 | string output=""; 10 | for (int i = 0; i < n;i++) 11 | { 12 | // CHARACTER IS SPACE THEN ADD 0 TO OUTPUT STRING 13 | if(input[i]==' ') 14 | { 15 | output = output + "0"; 16 | } 17 | // otherwise add specified string on the basis of array 18 | else 19 | { 20 | output = output + str[input[i] - 'A']; 21 | } 22 | 23 | } 24 | return output; 25 | } 26 | 27 | 28 | int main() 29 | { 30 | ios_base::sync_with_stdio(false); 31 | cin.tie(NULL); 32 | 33 | 34 | // storing the sequence in array 35 | string str[] = {"2","22","222", 36 | "3","33","333", 37 | "4","44","444", 38 | "5","55","555", 39 | "6","66","666", 40 | "7","77","777","7777", 41 | "8","88","888", 42 | "9","99","999","9999" 43 | }; 44 | 45 | string input = "RISHABH BHATT"; 46 | cout << KeypadSequenceConverter(str, input); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Geeks For Geeks/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Geeks For Geeks/Hard/.keep -------------------------------------------------------------------------------- /Geeks For Geeks/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Geeks For Geeks/Medium/.keep -------------------------------------------------------------------------------- /Hackerearth/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerearth/Easy/.keep -------------------------------------------------------------------------------- /Hackerearth/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerearth/Hard/.keep -------------------------------------------------------------------------------- /Hackerearth/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerearth/Medium/.keep -------------------------------------------------------------------------------- /Hackerrank/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerrank/Easy/.keep -------------------------------------------------------------------------------- /Hackerrank/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerrank/Hard/.keep -------------------------------------------------------------------------------- /Hackerrank/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Hackerrank/Medium/.keep -------------------------------------------------------------------------------- /Important Interview Questions/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Important Interview Questions/Easy/.keep -------------------------------------------------------------------------------- /Important Interview Questions/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Important Interview Questions/Hard/.keep -------------------------------------------------------------------------------- /Important Interview Questions/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Important Interview Questions/Medium/.keep -------------------------------------------------------------------------------- /Interview Algorithms/.gitignore: -------------------------------------------------------------------------------- 1 | questions/ 2 | c++ solutions/ -------------------------------------------------------------------------------- /Interview Algorithms/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/.keep -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Binary Search/code-iterative: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Binary Search/code-iterative -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Binary Search/code-iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int binarySearch(vector array, int target); 6 | int binarySearchHelper(vector array, int target, int left, int right); 7 | // O(log(n)) time | O(1) space 8 | int binarySearch(vector array, int target) 9 | { 10 | return binarySearchHelper(array, target, 0, array.size() - 1); 11 | } 12 | int binarySearchHelper(vector array, int target, int left, int right) 13 | { 14 | while (left <= right) 15 | { 16 | int middle = (left + right) / 2; 17 | int potentialMatch = array[middle]; 18 | if (target == potentialMatch) 19 | { 20 | return middle; 21 | } 22 | else if (target < potentialMatch) 23 | { 24 | right = middle - 1; 25 | } 26 | else 27 | { 28 | left = middle + 1; 29 | } 30 | } 31 | return -1; 32 | } 33 | 34 | int main() 35 | { 36 | vector array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 37 | int target = 5; 38 | cout << binarySearch(array, target) << endl; 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Binary Search/code-recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int binarySearch(vector array, int target); 4 | int binarySearchHelper(vector array, int target, int left, int right); 5 | // O(log(n)) time | O(log(n)) space 6 | int binarySearch(vector array, int target) 7 | { 8 | return binarySearchHelper(array, target, 0, array.size() - 1); 9 | } 10 | int binarySearchHelper(vector array, int target, int left, int right) 11 | { 12 | if (left > right) 13 | { 14 | return -1; 15 | } 16 | int middle = (left + right) / 2; 17 | int potentialMatch = array[middle]; 18 | if (target == potentialMatch) 19 | { 20 | return middle; 21 | } 22 | else if (target < potentialMatch) 23 | { 24 | return binarySearchHelper(array, target, left, middle - 1); 25 | } 26 | else 27 | { 28 | return binarySearchHelper(array, target, middle + 1, right); 29 | } 30 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Binary Search/problem.md: -------------------------------------------------------------------------------- 1 | ## Binary Search 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a sorted array of integers as well as a target integer. The function should use the Binary Search algorithm to nd if the target 6 | number is contained in the array and should return its index if it is, otherwise -1. 7 | 8 | Sample input: [0, 1, 21, 33, 45, 45, 61, 71, 72, 73], 33 9 | 10 | Sample output: 3 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Binary Search/tempCodeRunnerFile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Binary Search/tempCodeRunnerFile -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Branch Sum/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Branch Sum/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Branch Sum/problem.md: -------------------------------------------------------------------------------- 1 | Find the sum of each branch in a BST. Number of branches are the number of leaf nodes, return a vector/array. 2 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Bubble Sort/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Bubble Sort/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Bubble Sort/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector bubbleSort(vector array) 8 | { 9 | for (int i = 0; i < array.size(); i++) 10 | { 11 | int swapVal = 0; 12 | for (int j = i + 1; j < array.size(); j++) 13 | { 14 | if (array[j] > array[j + 1]) 15 | { 16 | swap(array[j], array[i]); 17 | swapVal = 1; 18 | } 19 | } 20 | if (swapVal == 0) 21 | { 22 | // lil optimization 23 | for (int i = 0; i < array.size(); i++) 24 | { 25 | cout << array[i] << " "; 26 | } 27 | cout << endl; 28 | return array; 29 | } 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | vector array{9, 8, 7, 6, 5, 4, 3, 2, 1}; 36 | 37 | bubbleSort(array); 38 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Bubble Sort/problem.md: -------------------------------------------------------------------------------- 1 | ## Bubble Sort 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of integers and returns a sorted version of that array. Use the Bubble Sort algorithm to sort the array. 6 | 7 | Sample input: [8, 5, 2, 9, 5, 6, 3] 8 | Sample output: [2, 3, 5, 5, 6, 8, 9] 9 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Caesar Cipher Encryptor/code-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | char getNewLetter(char letter, int key, string alphabet); 7 | // O(n) time | O(n) space 8 | string caesarCypherEncryptor(string str, int key) 9 | { 10 | vector newLetters; 11 | int newKey = key % 26; 12 | string alphabet = "abcdefghijklmnopqrstuvwxyz"; 13 | for (int i = 0; i < str.length(); i++) 14 | { 15 | newLetters.push_back(getNewLetter(str[i], newKey, alphabet)); 16 | } 17 | return string(newLetters.begin(), newLetters.end()); 18 | } 19 | char getNewLetter(char letter, int key, string alphabet) 20 | { 21 | int newLetterCode = alphabet.find(letter) + key; 22 | return newLetterCode <= 25 ? alphabet[newLetterCode] 23 | : alphabet[-1 + newLetterCode % 25]; 24 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Caesar Cipher Encryptor/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | char getNewLetter(char letter, int key); 6 | // O(n) time | O(n) space 7 | string caesarCypherEncryptor(string str, int key) 8 | { 9 | vector newLetters; 10 | int newKey = key % 26; 11 | for (int i = 0; i < str.length(); i++) 12 | { 13 | newLetters.push_back(getNewLetter(str[i], newKey)); 14 | } 15 | return string(newLetters.begin(), newLetters.end()); 16 | } 17 | char getNewLetter(char letter, int key) 18 | { 19 | int newLetterCode = letter + key; 20 | return newLetterCode <= 122 ? newLetterCode : 96 + newLetterCode % 1; 21 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Caesar Cipher Encryptor/problem.md: -------------------------------------------------------------------------------- 1 | ## Caesar Cipher Encryptor 2 | 3 | #### Problem Statement 4 | 5 | Given a non-empty string of lowercase letters and a non-negative integer value representing a key, write a function that returns a new string obtained by shifting 6 | every letter in the input string by k positions in the alphabet, where k is the key. Note that letters should "wrap" around the alphabet; in other words, the letter "z" 7 | shifted by 1 returns the letter "a". 8 | 9 | Sample input:"xyz", 2 10 | Sample output:"zab" 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Closest in a BST/problem.md: -------------------------------------------------------------------------------- 1 | ## Find Closest Value In BST 2 | 3 | #### Problem Statement 4 | 5 | You are given a BST data structure consisting of BST nodes. Each BST node has an integer value stored in a property called "value" and two children nodes stored 6 | in properties called "left" and "right," respectively. A node is said to be a BST node if and only if it satises the BST property: its value is strictly greater than the 7 | values of every node to its left; its value is less than or equal to the values of every node to its right; and both of its children nodes are either BST nodes 8 | themselves or None (null) values. You are also given a target integer value; write a function that nds the closest value to that target value contained in the BST. 9 | Assume that there will only be one closest value. 10 | Sample input: 11 | 10 , 12 12 | / \ 13 | 5 15 14 | / \ / \ 15 | 2 5 13 22 16 | / \ 17 | 1 14 18 | Sample output: 13 19 | 20 | #### Explanation 21 | 22 | We can use a Stack here 23 | 24 | #### Solution 25 | 26 | Check this [Python](../python/Find_Closest_Value_in_BST.py) code. 27 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Depth First Search/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | class Node 5 | { 6 | public: 7 | string name; 8 | vector children; 9 | Node(string name) { this->name = name; } 10 | // O(v + e) time | O(v) space 11 | vector depthFirstSearch(vector *array) 12 | { 13 | array->push_back(this->name); 14 | for (int i = 0; i < this->children.size(); i++) 15 | { 16 | children[i]->depthFirstSearch(array); 17 | } 18 | return *array; 19 | } 20 | Node *addChild(string name) 21 | { 22 | Node *child = new Node(name); 23 | children.push_back(child); 24 | return this; 25 | } 26 | }; -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Depth First Search/problem.md: -------------------------------------------------------------------------------- 1 | ## Depth First Search 2 | 3 | #### Problem Statement 4 | 5 | You are given a Node class that has a name and an array of optional children Nodes. When put together, Nodes form a simple tree-like structure. Implement the 6 | depthFirstSearch method on the Node class, which takes in an empty array, traverses the tree using the Depth-rst Search approach (specically navigating the 7 | tree from left to right), stores all the of the Nodes' names in the input array, and returns it. 8 | 9 | Sample input: 10 | A 11 | / | \ 12 | B C D 13 | / \ / \ 14 | E F G H 15 | / \ \ 16 | I J K 17 | Sample output: ["A","B","E","F","I","J","C","D","G","K","H"] 18 | 19 | #### Explanation 20 | 21 | We can use a Stack here 22 | 23 | #### Solution 24 | 25 | Check this [Python](../python/Depth_First_Search.py) code. 26 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Find Three Largest Numbers/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Find Three Largest Numbers/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Find Three Largest Numbers/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: (n) | Space: O(1) 2 | #include 3 | 4 | using namespace std; 5 | void updateLargest(vector *threeLargest, int num); 6 | 7 | void shiftAndUpdate(vector *threeLargest, int num, int idx); 8 | 9 | vector findThreeLargest(vector array) 10 | { 11 | vector threeLargest{INT_MIN, INT_MIN, INT_MIN}; 12 | 13 | for (int num : array) 14 | { 15 | updateLargest(&threeLargest, num); 16 | } 17 | 18 | cout << endl; 19 | cout << "Three largest are: "; 20 | for (int i = 0; i < threeLargest.size(); i++) 21 | { 22 | cout << threeLargest[i] << " "; 23 | } 24 | } 25 | 26 | void updateLargest(vector *threeLargest, int num) 27 | { 28 | if (num > threeLargest->at(2)) 29 | { 30 | shiftAndUpdate(threeLargest, num, 2); 31 | } 32 | else if (num > threeLargest->at(1)) 33 | { 34 | shiftAndUpdate(threeLargest, num, 1); 35 | } 36 | else if (num > threeLargest->at(0)) 37 | { 38 | shiftAndUpdate(threeLargest, num, 0); 39 | } 40 | } 41 | 42 | // [0, 1, 2] 43 | // [x, y, z] 44 | // if i == idx array[i] = num 45 | // else arr[i] = arr[i+1]; 46 | // [y, y, z]; 47 | // [y, z, z]; 48 | // [y, z, num]; 49 | void shiftAndUpdate(vector *threeLargest, int num, int idx) 50 | { 51 | for (int i = 0; i <= idx; i++) 52 | { 53 | if (i == idx) 54 | { 55 | threeLargest->at(i) = num; 56 | } 57 | else 58 | { 59 | threeLargest->at(i) = threeLargest->at(i + 1); 60 | } 61 | } 62 | } 63 | 64 | int main() 65 | { 66 | vector array{1, 2, 3, 4, 5, 6, 7, 8, 9}; 67 | int n; 68 | cin >> n; 69 | 70 | findThreeLargest(array); 71 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Find Three Largest Numbers/problem.md: -------------------------------------------------------------------------------- 1 | ## Find Three Largest Numbers 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of integers and returns a sorted array of the three largest integers in the input array. Note that the function should return 6 | duplicate integers if necessary; for example, it should return [10, 10, 12] for an input array of [10, 5, 9, 10, 12]. 7 | Sample input: [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7] 8 | Sample output: [18, 141, 541] 9 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Insertion Sort/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Insertion Sort/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Insertion Sort/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector insertionSort(vector array) 7 | { 8 | for (int i = 0; i < array.size(); i++) 9 | { 10 | for (int j = i; j >= 1; j--) 11 | { 12 | if (array[j] < array[j - 1]) 13 | { 14 | swap(array[j], array[j - 1]); 15 | } 16 | } 17 | } 18 | 19 | for (int i = 0; i < array.size(); i++) 20 | { 21 | cout << array[i] << " "; 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | vector array{9, 8, 7, 65, 34, 543, 3, 5, 6, 4}; 28 | insertionSort(array); 29 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Insertion Sort/problem.md: -------------------------------------------------------------------------------- 1 | ##Insertion Sort 2 | 3 | ####Problem Statement 4 | 5 | Write a function that takes in an array of integers and returns a sorted version of that array.Use the Insertion Sort algorithm to sort the array.Sample input : [ 8, 5, 2, 9, 5, 6, 3 ] Sample output : [ 2, 3, 5, 5, 6, 8, 9 ] 6 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Linked List Construction/problem.md: -------------------------------------------------------------------------------- 1 | ## Linked List Construction 2 | 3 | #### Problem Statement 4 | 5 | Write a class for a Doubly Linked List. The class should have a "head" and "tail" properties, both of which should point to either the None (null) value or to a 6 | Linked List node. Every node will have a "value" property as well as "next" and "prev" properties, both of which can point to either the None (null) value or 7 | another node. The class should support setting the head and tail of the linked list, inserting nodes before and after other nodes as well as at certain positions, 8 | removing given nodes and removing nodes with specic values, and searching for nodes with values. Only the searching method should return a value: 9 | specically, a boolean. 10 | 11 | Sample input: 12 | 1 -> 2 -> 3 -> 4 -> 5 13 | Sample output (after setting 4 to head): 14 | 4 -> 1 -> 2 -> 3 -> 5 15 | Sample output (after setting 6 to tail): 16 | 4 -> 1 -> 2 -> 3 -> 5 -> 6 17 | Sample output (after inserting 3 before 6): 18 | 4 -> 1 -> 2 -> 5 -> 3 -> 6 19 | Sample output (after inserting a new 3 after 6): 20 | 4 -> 1 -> 2 -> 5 -> 3 -> 6 -> 3 21 | Sample output (after inserting a new 3 at position 1): 22 | 3 -> 4 -> 1 -> 2 -> 5 -> 3 -> 6 -> 3 23 | Sample output (after removing nodes with value 3): 24 | 4 -> 1 -> 2 -> 5 -> 6 25 | Sample output (after removing 2): 26 | 4 -> 1 -> 5 -> 6 27 | Sample output (after searching for 5): True 28 | 29 | #### Explanation 30 | 31 | We can use a Stack here 32 | 33 | #### Solution 34 | 35 | Check this [Python](../python/Linked_List_Construction.py) code. 36 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Node Depths/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Node Depths/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Node Depths/problem.md: -------------------------------------------------------------------------------- 1 | Find the depth of each node in a BST and add all of them up and return the answer. 2 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Nth Fibonacci/code-iterative.cpp: -------------------------------------------------------------------------------- 1 | #include s 2 | 3 | using namespace std; 4 | // O(n) time | O(1) space 5 | int getNthFib(int n) 6 | { 7 | int lastTwo[] = {0, 1}; 8 | int counter = 3; 9 | while (counter <= n) 10 | { 11 | int nextFib = lastTwo[0] + lastTwo[1]; 12 | lastTwo[0] = lastTwo[1]; 13 | lastTwo[1] = nextFib; 14 | counter++; 15 | } 16 | return n > 1 ? lastTwo[1] : lastTwo[0]; 17 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Nth Fibonacci/code-memoization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int helperFib(int n, unordered_map memoize) 6 | { 7 | if (memoize.find(n) != memoize.end()) 8 | { 9 | return memoize[n]; 10 | } 11 | else 12 | { 13 | memoize[n] = helperFib(n - 1, memoize) + helperFib(n - 2, memoize); 14 | 15 | return memoize[n]; 16 | } 17 | } 18 | 19 | int getFib(int n) 20 | { 21 | // Hash table -- initialized with n==1 and n==2 22 | unordered_map memoize({{1, 0}, {2, 1}}); 23 | 24 | return helperFib(n, memoize); 25 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Nth Fibonacci/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | // O(2^n) time | O(n) space 5 | int getNthFib(int n) 6 | { 7 | if (n == 2) 8 | { 9 | return 1; 10 | } 11 | else if (n == 1) 12 | { 13 | return 0; 14 | } 15 | else 16 | { 17 | return getNthFib(n - 1) + getNthFib(n - 2); 18 | } 19 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Nth Fibonacci/problem.md: -------------------------------------------------------------------------------- 1 | ## Nth Fibonacci 2 | 3 | #### Problem Statement 4 | 5 | The Fibonacci sequence is dened as follows: the rst number of the sequence is 0, the second number is 1, and the nth number is the sum of the (n - 1)th and (n - 6 | 2)th numbers. Write a function that takes in an integer n and returns the nth Fibonacci number. 7 | 8 | Sample input: 6 9 | 10 | Sample output: 5 (0, 1, 1, 2, 3, 5) 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Easy/Palindrome Check/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/array-split-join-approach-code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(n) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool palindromeCheck(string s) 8 | { 9 | vector reversedChars; 10 | 11 | for (int i = s.length() - 1; i >= 0; i--) 12 | { 13 | reversedChars.push_back(s[i]); 14 | } 15 | 16 | return s == string(reversedChars.begin(), reversedChars.end); // JS ke join jaisa hai yeh 17 | } 18 | 19 | int main() 20 | { 21 | string s; 22 | cin >> s; 23 | 24 | cout << palindromeCheck(s); 25 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/problem.md: -------------------------------------------------------------------------------- 1 | ## Palindrome Check 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a non-empty string and that returns a boolean representing whether or not the string is a palindrome. A palindrome is dened as a 6 | string that is written the same forward and backward. 7 | 8 | Sample input:"abcdcba" 9 | 10 | Sample output: True (it is a palindrome) 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/recursive-code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(n) 2 | 3 | #include 4 | 5 | using namespace std; 6 | bool helperPalindromeCheck(string s, int i) 7 | { 8 | int j = s.length() - 1 - i; // acts as right pointer 9 | return i >= j ? true : s[i] == s[j] && helperPalindromeCheck(s, i + 1); 10 | } 11 | bool palindromeCheck(string s) 12 | { 13 | return helperPalindromeCheck(s, 0); 14 | } 15 | 16 | int main() 17 | { 18 | string s; 19 | cin >> s; 20 | 21 | cout << palindromeCheck(s); 22 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/reversed-approach-code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool palindromeCheck(string s) 8 | { 9 | 10 | string reversed = ""; 11 | 12 | for (int i = s.length() - 1; i >= 0; i--) 13 | { 14 | reversed += s[i]; // concatination takes O(n) 15 | } 16 | 17 | return s == reversed; 18 | } 19 | 20 | int main() 21 | { 22 | string s; 23 | cin >> s; 24 | 25 | cout << palindromeCheck(s); 26 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Palindrome Check/two-pointer-code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool palindromeCheck(string s) 8 | { 9 | int left = 0; 10 | int right = s.length() - 1; 11 | 12 | while (left < right) 13 | { 14 | if (s[left] == s[right]) 15 | { 16 | left++; 17 | right--; 18 | } 19 | else 20 | { 21 | cout << "False"; 22 | return false; 23 | } 24 | } 25 | cout << "True"; 26 | return true; 27 | } 28 | 29 | int main() 30 | { 31 | string s; 32 | cin >> s; 33 | 34 | cout << palindromeCheck(s); 35 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Product Sum/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n), n are total number of elements 2 | // Space: O(max_depth) 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int productSum(vector array, int multiplier = 1) 10 | { 11 | int sum = 0; 12 | 13 | for (auto el : array) 14 | { 15 | if (el.type() == typeid(vector)) 16 | { 17 | sum += productSum(any_cast>(el), multiplier + 1); 18 | } 19 | else 20 | { 21 | sum += any_cast(el); 22 | } 23 | } 24 | return sum * multiplier; 25 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Product Sum/problem.md: -------------------------------------------------------------------------------- 1 | ## Product Sum 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a "special" array and returns its product sum. A "special" array is 6 | a non-empty array that contains either integers or other "special" arrays. The product sum of a 7 | "special" array is the sum of its elements, where "special" arrays inside it should be summed 8 | themselves and then multiplied by their level of depth. For example, the product sum of [x, y] is 9 | x + y; the product sum of [x, [y, z]] is x + 2y + 2z. 10 | 11 | `Sample input: [5, 2, [7, -1], 3, [6, [-13, 8], 4]] Sample output: 12 (5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4)` 12 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Selection Sort/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) 2 | 3 | #include 4 | using namespace std; 5 | 6 | vector selectionSort(vector array) 7 | { 8 | if (array.empty()) 9 | { 10 | return {}; 11 | } 12 | int startIdx = 0; 13 | while (startIdx < array.size() - 1) 14 | { 15 | int smallestIdx = 0; 16 | 17 | for (int i = startIdx + 1; i < array.size(); i++) 18 | { 19 | if (array[smallestIdx] > array[i]) 20 | { 21 | smallestIdx = i; 22 | } 23 | } 24 | swap(array[startIdx], array[smallestIdx]); 25 | startIdx++; 26 | } 27 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Selection Sort/problem.md: -------------------------------------------------------------------------------- 1 | ## Selection Sort 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of integers and returns a sorted version of that array. Use the Selection Sort algorithm to sort the array. 6 | 7 | Sample input: [8, 5, 2, 9, 5, 6, 3] 8 | 9 | Sample output: [2, 3, 5, 5, 6, 8, 9] 10 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Two Number Sum/code.cpp: -------------------------------------------------------------------------------- 1 | // Approach 1: Two For loops 2 | 3 | #include 4 | using namespace std; 5 | int solve(int arr[], int target, int size); 6 | int main() { 7 | int size; 8 | std::cin>>size; 9 | int arr[size]; 10 | 11 | 12 | for(int i = 0; i < size; i++) { 13 | std::cin>>arr[i]; 14 | } 15 | 16 | int target; 17 | std::cin>>target; 18 | 19 | solve(arr, target, size); 20 | } 21 | 22 | int solve(int arr[], int target, int size) { 23 | for(int i = 0; i < size; i++) { 24 | int firstNum = arr[i]; 25 | for(int j = i+1; j < size; j++) { 26 | int secondNum = arr[j]; 27 | if(firstNum + secondNum == target) { 28 | std::cout<<"Target found: "< 2 | #include 3 | using namespace std; 4 | // O(n) time | O(n) space 5 | vector twoNumberSum(vector array, int targetSum) { 6 | unordered_set nums; 7 | for (int num : array) { 8 | int potentialMatch = targetSum - num; 9 | if (nums.find(potentialMatch) != nums.end()) { 10 | return vector{potentialMatch, num}; 11 | } else { 12 | nums.insert(num); 13 | } 14 | } 15 | return {}; 16 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Two Number Sum/code3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | // O(nlog(n)) | O(1) space 5 | vector twoNumberSum(vector array, int targetSum) { 6 | sort(array.begin(), array.end()); 7 | int left = 0; 8 | int right = array.size() - 1; 9 | while (left < right) { 10 | int currentSum = array[left] + array[right]; 11 | if (currentSum == targetSum) { 12 | return {array[left], array[right]}; 13 | } else if (currentSum < targetSum) { 14 | left++; 15 | } else if (currentSum > targetSum) { 16 | right--; 17 | } 18 | } 19 | return {}; 20 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Two Number Sum/problem.md: -------------------------------------------------------------------------------- 1 | ## Two Number Sum 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the 6 | target sum, the function should return them in an array, in sorted order. If no two numbers sum up to the target sum, the function should return an empty array. 7 | Assume that there will be at most one pair of numbers summing up to the target sum. 8 | 9 | `Sample input: [3, 5, -4, 8, 11, 1, -1, 6], 10 Sample output: [-1, 11]` 10 | 11 | #### Explanation 12 | 13 | We can use a Stack here 14 | 15 | #### Solution 16 | 17 | Check this [Python](../python/Two_Number_Sum.py) code. 18 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Two Number Sum/solution.md: -------------------------------------------------------------------------------- 1 | Approach 1: Naive approach 2 | 3 | Use two for loops and traverse the array to find the pair which sum upto target 4 | Time: O(n^2) 5 | space: O(n) 6 | 7 | Approach 2: Hash Tables 8 | 9 | While traversing the array, check if targetNumber - currentNumber is present in the hash table; 10 | If not, take the current element and push it into the hash table. 11 | There will come a time when the x - y = targetNumber equation is satisfied 12 | 13 | Time: O(n) 14 | Space: O(n) 15 | 16 | Approach 3: Two Pointer Approach 17 | 18 | First sort the array, Thats O(n) time. 19 | Then take two pointers, left and right 20 | point left to the extreme left, right to the extreme right. 21 | 22 | Now, check if left + right === targetNumber; if yes then return the number 23 | If not, then check if left+right > targetNumber; if yes, do right-- because we want to decrease the sum and check again 24 | else do left++; 25 | 26 | Time: O(nlogn) 27 | Space: O(1) 28 | -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Validate Subsequence/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int validateSubsequence(int arr[], int subsequence[],int arrSize,int seqSize); 4 | int main() { 5 | int arrSize = 8, seqSize = 4; 6 | int arr[] = [5,1,22,25,6,-1,8,10]; 7 | int subsequence[] = [1,6,-1,10] 8 | 9 | validateSubsequence(arr, subsequence, arrSize, seqSize); 10 | } 11 | 12 | int validateSubsequence(int arr[], int subsequence[], int arrSize, int seqSize) { 13 | int arrIdx = 0; 14 | int seqIdx = 0; 15 | 16 | while(arrIdx < arrSize && seqIdx < seqSize) { 17 | if (arr[arrIdx] == subsequence[seqIdx]) { 18 | seqIdx++; 19 | } 20 | arrIdx++; 21 | } 22 | // Valid subsequence if seqIdx == seqSize 23 | 24 | return seqIdx == seqSize; 25 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Validate Subsequence/code2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Same solution but with for loop 3 | int validateSubsequence(int arr[], int subsequence[], int arrSize, int seqSize); 4 | int main() 5 | { 6 | int arrSize = 8, seqSize = 4; 7 | int arr[] = {5, 1, 22, 25, 6, -1, 8, 10}; 8 | int subsequence[] = {1, 6, -1, 10}; 9 | 10 | validateSubsequence(arr, subsequence, arrSize, seqSize); 11 | } 12 | 13 | int validateSubsequence(int arr[], int subsequence[], int arrSize, int seqSize) 14 | { 15 | int arrIdx = 0; 16 | int seqIdx = 0; 17 | 18 | for (int i = 0; i < arrSize; i++) 19 | { 20 | if (seqIdx == seqSize) 21 | break; 22 | if (subsequence[seqIdx] == arr[i]) 23 | { 24 | seqIdx++; 25 | } 26 | } 27 | // Valid subsequence if seqIdx == seqSize 28 | 29 | return seqIdx == seqSize; 30 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Validate Subsequence/code3.cpp: -------------------------------------------------------------------------------- 1 | // Vector approach 2 | 3 | #include 4 | 5 | using namespace std; 6 | // O(n) time | O(1) space - where n is the length of the array 7 | bool isValidSubsequence(vector array, vector sequence) 8 | { 9 | int seqIdx = 0; 10 | for (auto value : array) 11 | { 12 | if (seqIdx == sequence.size()) 13 | break; 14 | if (sequence[seqIdx] == value) 15 | seqIdx++; 16 | } 17 | return seqIdx == sequence.size(); 18 | } -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Validate Subsequence/problem.md: -------------------------------------------------------------------------------- 1 | Given an array and a subsequence, Find whether the subsequence belongs to the array. -------------------------------------------------------------------------------- /Interview Algorithms/Easy/Validate Subsequence/solution.md: -------------------------------------------------------------------------------- 1 | Approach 1: Two pointers 2 | 3 | Take one pointer and point it to the subsequence array, 4 | Take second pointer and point it to the main array 5 | 6 | Traverse the main array to find for the first element, If found, Increment the pointer in subsequence array 7 | and proceed this way. 8 | 9 | Time: O(n) 10 | Space: O(n) -------------------------------------------------------------------------------- /Interview Algorithms/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Hard/.keep -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Four Number Sum/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector> fourNumberSum(vector array, int target) 6 | { 7 | unordered_map>> allPairsSum; 8 | vector> quadruples{}; 9 | 10 | for (int i = 1; i < array.size() - 1; i++) 11 | { 12 | for (int j = i + 1; j < array.size(); j++) 13 | { 14 | int currentSum = array[i] + array[j]; 15 | int diff = target - currentSum; 16 | 17 | if (allPairsSum.find(diff) != allPairsSum.end()) 18 | { 19 | // found a difference and a pair 20 | for (vector pair : allPairsSum[diff]) 21 | { 22 | pair.push_back(array[i]); 23 | pair.push_back(array[j]); 24 | quadruples.push_back(pair); 25 | } 26 | } 27 | } 28 | 29 | // Now fill the HT -- to avoid duplicate entries 30 | for (int k = 0; k < i; k++) 31 | { 32 | int currentSum = array[k] + array[i]; 33 | //if not in HT 34 | if (allPairsSum.find(currentSum) == allPairsSum.end()) 35 | { 36 | // initialize that sum with the array of pairs 37 | allPairsSum[currentSum] = vector>{{array[k], array[i]}}; 38 | } 39 | else 40 | { 41 | allPairsSum[currentSum].push_back(vector{array[i], array[k]}); 42 | } 43 | } 44 | } 45 | 46 | return quadruples; 47 | } -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Four Number Sum/problem.md: -------------------------------------------------------------------------------- 1 | ## Four Number Sum 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should nd all quadruplets in the array 6 | that sum up to the target sum and return a two-dimensional array of all these quadruplets in no particular order. If no four numbers sum up to the target sum, the 7 | function should return an empty array. 8 | 9 | 10 | `Sample input: [7, 6, 4, -1, 1, 2], 16 11 | Sample output: [[7, 6, 4, -1], [7, 6, 1, 2]]` 12 | 13 | -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Largest Range/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // O(n) time | O(n) space 6 | 7 | vector largestRange(vector array) 8 | { 9 | vector bestRange = {}; 10 | 11 | int longestLength = 0; 12 | unordered_map nums = {}; 13 | 14 | for (int num : array) 15 | { 16 | nums[num] = true; 17 | } 18 | 19 | for (int num : array) 20 | { 21 | // If the number is already marked false, then we skip it to avoid repetative work 22 | if (!nums[num]) 23 | { 24 | continue; 25 | } 26 | 27 | nums[num] = false; 28 | int currentLength = 1; 29 | int left = num - 1; 30 | int right = num + 1; 31 | 32 | // Find the left most range 33 | while (nums.find(left) != nums.end()) 34 | { 35 | nums[left] = false; 36 | currentLength++; 37 | left--; 38 | } 39 | 40 | // Find the right most range 41 | while (nums.find(right) != nums.end()) 42 | { 43 | nums[right] = false; 44 | currentLength++; 45 | right++; 46 | } 47 | 48 | // Check if current is longer than longest 49 | if (currentLength > longestLength) 50 | { 51 | longestLength = currentLength; 52 | bestRange = {left + 1, 53 | right - 1}; 54 | } 55 | } 56 | 57 | return bestRange; 58 | } -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Largest Range/problem.md: -------------------------------------------------------------------------------- 1 | ## Largest Range 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of integers and returns an array of length 2 representing the largest range of numbers contained in that array. The rst 6 | number in the output array should be the rst number in the range while the second number should be the last number in the range. A range of numbers is dened 7 | as a set of numbers that come right after each other in the set of real integers. For instance, the output array [2, 6] represents the range {2, 3, 4, 5, 6}, which is a 8 | range of length 5. Note that numbers do not need to be ordered or adjacent in the array in order to form a range. Assume that there will only be one largest range. 9 | 10 | 11 | `Sample input: [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6] 12 | Sample output: [0, 7]` 13 | -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Subarray Sort/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector subarraySort(vector array) 6 | { 7 | int minOutOfOrder = INT_MAX; 8 | int maxOutOfOrder = INT_MIN; 9 | 10 | for (int i = 0; i < array.size(); i++) 11 | { 12 | int num = array[i]; 13 | if (isOutOfOrder(i, num, array)) 14 | { 15 | minOutOfOrder = min(minOutOfOrder, num); 16 | maxOutOfOrder = max(maxOutOfOrder, num); 17 | } 18 | } 19 | 20 | if (minOutOfOrder == INT_MAX) 21 | return vector{-1, -1}; 22 | 23 | int subALeftIdx = 0; 24 | while (minOutOfOrder >= array[subALeftIdx]) 25 | subALeftIdx++; 26 | int subARightIdx = 0; 27 | while (maxOutOfOrder <= array[subARightIdx]) 28 | subARightIdx--; 29 | 30 | return vector{subALeftIdx, subARightIdx}; 31 | } 32 | 33 | bool isOutOfOrder(int i, int num, vector arr) 34 | { 35 | // O(n) time | O(1) space 36 | if (i == 0) 37 | return num > arr[i + 1]; 38 | if (i == arr.size() - 1) 39 | return num < arr[i - 1]; 40 | 41 | return num > arr[i + 1] || num < arr[i - 1]; 42 | } -------------------------------------------------------------------------------- /Interview Algorithms/Hard/Subarray Sort/problem.md: -------------------------------------------------------------------------------- 1 | ## Subarray Sort 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of integers of length at least 2. The function should return an array of the starting and ending indices of the smallest 6 | subarray in the input array that needs to be sorted in place in order for the entire input array to be sorted. If the input array is already sorted, the function should 7 | return [-1, -1]. 8 | 9 | 10 | `Sample input: [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19] 11 | Sample output: [3, 9]` 12 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Medium/.keep -------------------------------------------------------------------------------- /Interview Algorithms/Medium/BST Construction/problem.md: -------------------------------------------------------------------------------- 1 | ## BST Construction 2 | 3 | #### Problem Statement 4 | 5 | Write a Binary Search Tree (BST) class. The class should have a "value" property set to be an integer, as well as "left" and "right" properties, both of which should 6 | point to either the None (null) value or to another BST. A node is said to be a BST node if and only if it satises the BST property: its value is strictly greater than 7 | the values of every node to its left; its value is less than or equal to the values of every node to its right; and both of its children nodes are either BST nodes 8 | themselves or None (null) values. The BST class should support insertion, searching, and removal of values. The removal method should only remove the rst 9 | instance of the target value. 10 | 11 | Sample input: 12 | 10 13 | / \ 14 | 5 15 15 | / \ / \ 16 | 2 5 13 22 17 | / \ 18 | 1 14 19 | Sample output (after inserting 12): 20 | 10 21 | / \ 22 | 5 15 23 | / \ / \ 24 | 2 5 13 22 25 | / / \ 26 | 1 12 14 27 | Sample output (after removing 10): 28 | 12 29 | / \ 30 | 5 15 31 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/BST traversal/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class BST 6 | { 7 | public: 8 | int value; 9 | BST *left; 10 | BST *right; 11 | 12 | BST(int value) 13 | { 14 | this->value = value; 15 | left = nullptr; 16 | right = nullptr; 17 | } 18 | }; 19 | 20 | // O(n) time | O(n) space 21 | vector inorder(BST *tree, vector array) 22 | { 23 | if (tree->left != NULL) 24 | { 25 | array = inorder(tree->left, array); 26 | } 27 | array.push_back(tree->value); 28 | if (tree->right != NULL) 29 | { 30 | array = inorder(tree->right, array); 31 | } 32 | return array; 33 | } 34 | 35 | // O(n) time | O(n) space 36 | vector preOrderTraverse(BST *tree, vector array) 37 | { 38 | array.push_back(tree->value); 39 | if (tree->left != NULL) 40 | { 41 | array = preOrderTraverse(tree->left, array); 42 | } 43 | if (tree->right != NULL) 44 | { 45 | array = preOrderTraverse(tree->right, array); 46 | } 47 | return array; 48 | } 49 | // O(n) time | O(n) space 50 | vector postOrderTraverse(BST *tree, vector array) 51 | { 52 | if (tree->left != NULL) 53 | { 54 | array = postOrderTraverse(tree->left, array); 55 | } 56 | if (tree->right != NULL) 57 | { 58 | array = postOrderTraverse(tree->right, array); 59 | } 60 | array.push_back(tree->value); 61 | return array; 62 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/BST traversal/problem.md: -------------------------------------------------------------------------------- 1 | ## BST Construction 2 | 3 | #### Problem Statement 4 | 5 | Write a Binary Search Tree (BST) class. The class should have a "value" property set to be an integer, as well as "left" and "right" properties, both of which should 6 | point to either the None (null) value or to another BST. A node is said to be a BST node if and only if it satises the BST property: its value is strictly greater than 7 | the values of every node to its left; its value is less than or equal to the values of every node to its right; and both of its children nodes are either BST nodes 8 | themselves or None (null) values. The BST class should support insertion, searching, and removal of values. The removal method should only remove the rst 9 | instance of the target value. 10 | 11 | Sample input: 12 | 10 13 | / \ 14 | 5 15 15 | / \ / \ 16 | 2 5 13 22 17 | / \ 18 | 1 14 19 | Sample output (after inserting 12): 20 | 10 21 | / \ 22 | 5 15 23 | / \ / \ 24 | 2 5 13 22 25 | / / \ 26 | 1 12 14 27 | Sample output (after removing 10): 28 | 12 29 | / \ 30 | 5 15 31 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Balanced Brackets/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | // O(n) time | O(n) space 5 | bool balancedBrackets(string str) 6 | { 7 | string openingBrackets = "([{"; 8 | string closingBrackets = ")]}"; 9 | unordered_map matchingBrackets{ 10 | {')', '('}, {']', '['}, {'}', '{'}}; 11 | vector stack; 12 | for (char character : str) 13 | { 14 | if (openingBrackets.find(character) != string::npos) 15 | { 16 | stack.push_back(character); 17 | } 18 | else if (closingBrackets.find(character) != string::npos) 19 | { 20 | if (stack.size() == 0) 21 | { 22 | return false; 23 | } 24 | if (stack[stack.size() - 1] == matchingBrackets[character]) 25 | { 26 | stack.pop_back(); 27 | } 28 | else 29 | { 30 | return false; 31 | } 32 | } 33 | } 34 | return stack.size() == 0; 35 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Balanced Brackets/problem.md: -------------------------------------------------------------------------------- 1 | ## Balanced Bracket 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a string made up of brackets `("(","[","{",")","]", and "}")` and other optional characters. The function should return a boolean 6 | representing whether or not the string is balanced in regards to brackets. A string is said to be balanced if it has as many opening brackets of a given type as it has 7 | closing brackets of that type and if no bracket is unmatched. Note that a closing bracket cannot match a corresponding opening bracket that comes after it. 8 | Similarly, brackets cannot overlap each other as in `"[(])"`. 9 | 10 | `Sample input:"([])(){}(())()()" Sample output: True (it is balanced)` 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Breadth First Search/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | string name; 8 | vector children; 9 | 10 | Node(string name) 11 | { 12 | this->name = name; 13 | } 14 | // Time: O(V + E) | Space: O(V) 15 | vector bfs(vector *array) 16 | { 17 | deque queue{this}; 18 | while (!queue.empty()) 19 | { 20 | Node current = *queue.front(); 21 | queue.pop_front(); 22 | array->push_back(current.name); 23 | for (int i = 0; i < current.children.size(); i++) 24 | { 25 | queue.push_back(current.children[i]); 26 | } 27 | } 28 | return *array; 29 | } 30 | 31 | Node *addNode(string name) 32 | { 33 | Node *child = new Node(name); 34 | children.push_back(child); 35 | return this; 36 | } 37 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Breadth First Search/problem.md: -------------------------------------------------------------------------------- 1 | ## Breadth first Search 2 | 3 | #### Problem Statement 4 | 5 | You are given a Node class that has a name and an array of optional children Nodes. When put together, 6 | Nodes form a simple tree-like structure. Implement the breadthFirstSearch method on the Node class, 7 | which takes in an empty array, traverses the tree using the Breadth-rst Search approach (specically 8 | navigating the tree from left to right), stores all of the Nodes' names in the input array, and returns it. 9 | Sample input: 10 | A 11 | / | \ 12 | B C D 13 | / \ / \ 14 | E F G H 15 | / \ \ 16 | I J K 17 | Sample output: ["A","B","C","D","E","F","G","H","I","J","K"] 18 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Group Anagrams/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | // O(w * n * log(n) + n * w * log(w)) time | O(wn) space - where w is the number 6 | // of words and n is the length of the longest word 7 | vector> groupAnagrams(vector words) 8 | { 9 | if (words.size() == 0) 10 | return {}; 11 | vector sortedWords = {}; 12 | for (auto word : words) 13 | { 14 | sort(word.begin(), word.end()); 15 | sortedWords.push_back(word); 16 | } 17 | vector indices(words.size()); 18 | iota(indices.begin(), indices.end(), 0); 19 | sort(indices.begin(), indices.end(), [sortedWords](int a, int b) -> bool { 20 | return sortedWords[a] < sortedWords[b]; 21 | }); 22 | vector> result = {}; 23 | vector currentAnagramGroup = {}; 24 | string currentAnagram = sortedWords[indices[0]]; 25 | for (auto index : indices) 26 | { 27 | string word = words[index]; 28 | string sortedWord = sortedWords[index]; 29 | if (sortedWord == currentAnagram) 30 | { 31 | currentAnagramGroup.push_back(word); 32 | continue; 33 | } 34 | result.push_back(currentAnagramGroup); 35 | currentAnagramGroup = vector{word}; 36 | currentAnagram = sortedWord; 37 | } 38 | result.push_back(currentAnagramGroup); 39 | return result; 40 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Group Anagrams/code2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | // O(w * n * log(n)) time | O(wn) space - where w is the number of words and n 6 | // is the length of the longest word 7 | vector> groupAnagrams(vector words) 8 | { 9 | unordered_map> anagrams; 10 | for (auto word : words) 11 | { 12 | string sortedWord = word; 13 | sort(sortedWord.begin(), sortedWord.end()); 14 | if (anagrams.find(sortedWord) != anagrams.end()) 15 | { 16 | anagrams[sortedWord].push_back(word); 17 | } 18 | else 19 | { 20 | anagrams[sortedWord] = vector{word}; 21 | } 22 | } 23 | vector> output = {}; 24 | for (auto it : anagrams) 25 | { 26 | output.push_back(it.second); 27 | } 28 | return output; 29 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Invert Binary Tree/code-iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class BT 6 | { 7 | public: 8 | int value; 9 | BT *left; 10 | BT *right; 11 | 12 | BT(int value); 13 | void insert(vector values, int i = 0); 14 | void invertedInsert(vector values, int i = 0); 15 | }; 16 | 17 | void swapLeftRight(BT *tree); 18 | 19 | void invertBinaryTree(BT *tree) 20 | { 21 | deque queue; 22 | queue.push_back(tree); 23 | while (queue.size() > 0) 24 | { 25 | BT *current = queue.front(); 26 | queue.pop_front(); 27 | if (current == NULL) 28 | continue; 29 | 30 | swapLeftRight(current); 31 | queue.push_back(current->left); 32 | queue.push_back(current->right); 33 | } 34 | } 35 | 36 | void swapLeftRight(BT *tree) 37 | { 38 | BT *left = tree->left; 39 | tree->left = tree->right; 40 | tree->right = left; 41 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Invert Binary Tree/code-recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class BT 6 | { 7 | public: 8 | int value; 9 | BT *left; 10 | BT *right; 11 | 12 | BT(int value); 13 | void insert(vector values, int i = 0); 14 | void invertedInsert(vector values, int i = 0); 15 | }; 16 | 17 | void swapLeftRight(BT *tree); 18 | 19 | void invertBinaryTree(BT *tree) 20 | { 21 | if (tree == NULL) 22 | return; 23 | 24 | swapLeftRight(tree); 25 | invertBinaryTree(tree->left); 26 | invertBinaryTree(tree->right); 27 | } 28 | 29 | void swapLeftRight(BT *tree) 30 | { 31 | BT *left = tree->left; 32 | tree->left = tree->right; 33 | tree->right = left; 34 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Invert Binary Tree/problem.md: -------------------------------------------------------------------------------- 1 | ## Invert Binary Tree 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a Binary Tree and inverts it. In other words, the 6 | function should swap every left node in the tree for its corresponding 7 | (mirrored) right node. Each Binary Tree node has a value stored in a property 8 | called "value" and two children nodes stored in properties called "left" and 9 | "right," respectively. Children nodes can either be Binary Tree nodes themselves 10 | or the None (null) value. 11 | Sample input: 12 | 1 13 | / \ 14 | 2 3 15 | / \ / \ 16 | 4 5 6 7 17 | / \ 18 | 8 9 19 | Sample output: 20 | 1 21 | / \ 22 | 3 2 23 | / \ / \ 24 | 7 6 5 4 25 | / \ 26 | 9 8 27 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Kadane's Algorithm/code-dp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | // O(n) time | O(1) space 5 | int kadanesAlgorithm(vector array) 6 | { 7 | int maxEndingHere = array[0]; 8 | int maxSoFar = array[0]; 9 | for (int i = 1; i < array.size(); i++) 10 | { 11 | int num = array[i]; 12 | maxEndingHere = max(num, maxEndingHere + num); 13 | maxSoFar = max(maxSoFar, maxEndingHere); 14 | } 15 | return maxSoFar; 16 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Kadane's Algorithm/problem.md: -------------------------------------------------------------------------------- 1 | ## Kadane's Algorithm 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a non-empty array of integers and returns the maximum sum that can be obtained by summing up all the numbers in a non-empty 6 | subarray of the input array. A subarray must only contain adjacent numbers. 7 | Sample input: [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4] 8 | Sample output: 19 ([1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1]) 9 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Levenshtein Distance - Min Edits Required To Make One String To Another/code-dp-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // O(nm) time | O(min(n, m)) space 4 | int levenshteinDistance(string str1, string str2) 5 | { 6 | string small = str1.length() < str2.length() ? str1 : str2; 7 | string big = str1.length() >= str2.length() ? str1 : str2; 8 | int *evenEdits = new int[small.length() + 1]; 9 | int *oddEdits = new int[small.length() + 1]; 10 | for (int j = 0; j < small.length() + 1; j++) 11 | { 12 | evenEdits[j] = j; 13 | } 14 | int *currentEdits; 15 | int *previousEdits; 16 | for (int i = 1; i < big.length() + 1; i++) 17 | { 18 | if (i % 2 == 1) 19 | { 20 | currentEdits = oddEdits; 21 | previousEdits = evenEdits; 22 | } 23 | else 24 | { 25 | currentEdits = evenEdits; 26 | previousEdits = oddEdits; 27 | } 28 | currentEdits[0] = i; 29 | for (int j = 1; j < small.length() + 1; j++) 30 | { 31 | if (big[i - 1] == small[j - 1]) 32 | { 33 | currentEdits[j] = previousEdits[j - 1]; 34 | } 35 | else 36 | { 37 | currentEdits[j] = 1 + min(previousEdits[j - 1], 38 | min(previousEdits[j], currentEdits[j - 1])); 39 | } 40 | } 41 | } 42 | return big.length() % 2 == 0 ? evenEdits[small.length()] 43 | : oddEdits[small.length()]; 44 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Levenshtein Distance - Min Edits Required To Make One String To Another/code-dp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // O(nm) time | O(nm) space 4 | int levenshteinDistance(string str1, string str2) 5 | { 6 | vector> edits(str2.length() + 1, 7 | vector(str1.length() + 1, 0)); 8 | for (int i = 0; i < str2.length() + 1; i++) 9 | { 10 | for (int j = 0; j < str1.length() + 1; j++) 11 | { 12 | edits[i][j] = j; 13 | } 14 | edits[i][0] = i; 15 | } 16 | for (int i = 1; i < str2.length() + 1; i++) 17 | { 18 | for (int j = 1; j < str1.length() + 1; j++) 19 | { 20 | if (str2[i - 1] == str1[j - 1]) 21 | { 22 | edits[i][j] = edits[i - 1][j - 1]; 23 | } 24 | else 25 | { 26 | edits[i][j] = 27 | 1 + min(edits[i - 1][j - 1], min(edits[i - 1][j], edits[i][j - 1])); 28 | } 29 | } 30 | } 31 | return edits[str2.length()][str1.length()]; 32 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Levenshtein Distance - Min Edits Required To Make One String To Another/problem.md: -------------------------------------------------------------------------------- 1 | ## Levenshtein Distance 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in two strings and returns the minimum number of edit operations that need to be performed on the rst string to obtain the second 6 | string. There are three edit operations: insertion of a character, deletion of a character, and substitution of a character for another. 7 | 8 | Sample input:"abc","yabd" 9 | Sample output: 2 (insert"y"; substitute "c"for "d") 10 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Longest Palindromic Substring/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | string longestPalindromicSubstring(string str) 8 | { 9 | vector currentLongest{0, 1}; 10 | 11 | for (int i = 0; i < str.length(); i++) 12 | { 13 | vector odd = getPalFrom(str, i - 1, i + 1); 14 | vector even = getPalFrom(str, i - 1, i); 15 | 16 | vector longest = odd[1] - odd[0] > even[1] - even[0] ? odd : even; 17 | vector currentLongest = currentLongest[1] - currentLongest[0] > longest[1] - longest[0] ? currentLongest : longest; 18 | } 19 | return str.substr(currentLongest[0], currentLongest[1] - currentLongest[0]); 20 | } 21 | 22 | vector getPalFrom(string str, int leftIdx, int rightIdx) 23 | { 24 | while (leftIdx >= 0 && rightIdx <= str.length()) 25 | { 26 | if (str[leftIdx] != str[rightIdx]) 27 | break; 28 | 29 | leftIdx--; 30 | rightIdx++; 31 | } 32 | 33 | return vector{leftIdx + 1, rightIdx}; 34 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Longest Palindromic Substring/code2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool isPalindrome(string str); 4 | // Brute force 5 | // O(n^3) time | O(1) space 6 | string longestPalindromicSubstring(string str) 7 | { 8 | string longest = ""; 9 | for (int i = 0; i < str.length(); i++) 10 | { 11 | for (int j = i; j < str.length(); j++) 12 | { 13 | string substring = str.substr(i, j + 1 - i); 14 | if (substring.length() > longest.length() && isPalindrome(substring)) 15 | { 16 | longest = substring; 17 | } 18 | } 19 | } 20 | return longest; 21 | } 22 | bool isPalindrome(string str) 23 | { 24 | int leftIdx = 0; 25 | int rightIdx = str.length() - 1; 26 | while (leftIdx < rightIdx) 27 | { 28 | if (str[leftIdx] != str[rightIdx]) 29 | { 30 | return false; 31 | } 32 | leftIdx++; 33 | rightIdx--; 34 | } 35 | return true; 36 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Longest Palindromic Substring/problem.md: -------------------------------------------------------------------------------- 1 | ## Longest Palindromic Substring 2 | 3 | #### Problem Statement 4 | 5 | 6 | Write a function that, given a string, returns its longest palindromic substring. A palindrome is dened as a string that is written the same forward and backward. 7 | Assume that there will only be one longest palindromic substring. 8 | Sample input:"abaxyzzyxf" 9 | Sample output:"xyzzyx" 10 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Longest Peak/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(1) 2 | #include 3 | 4 | using namespace std; 5 | 6 | int longestPeak(vector arr) 7 | { 8 | int longestPeakLength = 0; 9 | int i = 1; 10 | int size = arr.size(); 11 | while (i < size - 1) 12 | { 13 | int isPeak = arr[i] > arr[i - 1] && arr[i] > arr[i + 1]; 14 | if (!isPeak) 15 | { 16 | i++; 17 | continue; 18 | } 19 | int leftIdx = i - 2; 20 | while (leftIdx >= 0 && arr[leftIdx] < arr[leftIdx + 1]) 21 | { 22 | leftIdx--; 23 | } 24 | int rightIdx = i + 2; 25 | while (rightIdx <= size - 1 && arr[rightIdx] < arr[rightIdx - 1]) 26 | { 27 | rightIdx++; 28 | } 29 | int currentPeakLength = rightIdx - leftIdx - 1; 30 | longestPeakLength = max(longestPeakLength, currentPeakLength); 31 | i = rightIdx; 32 | } 33 | 34 | return longestPeakLength; 35 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Longest Peak/problem.md: -------------------------------------------------------------------------------- 1 | Find the longest peak in the given array 2 | 3 | ip = [1, 2, 3, 4, 5, 0, 10, 6, 5, -1, -3, 2, 3] 4 | op = 6 5 | 6 | Peak is basically a mountain in which we consider atleast three elements. The left and the right elements to the peak are smaller than the peak element. 7 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Max Subset Sum No Adjacent - DP/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Medium/Max Subset Sum No Adjacent - DP/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Max Subset Sum No Adjacent - DP/code-dp-better.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Time: O(n) | Space: O(1) 6 | int maxSubsetSumNoAdjacent(vector array) 7 | { 8 | if (!array.size()) 9 | return INT_MIN; 10 | if (array.size() == 1) 11 | return array[0]; 12 | 13 | int second = array[0]; 14 | int first = max(array[0], array[1]); 15 | 16 | for (int i = 2; i < array.size(); i++) 17 | { 18 | int current = max(first, second + array[i]); 19 | second = first; 20 | first = current; 21 | } 22 | 23 | return first; 24 | } 25 | 26 | int main() 27 | { 28 | vector array{7, 10, 12, 7, 9, 14}; 29 | cout << maxSubsetSumNoAdjacent(array); 30 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Max Subset Sum No Adjacent - DP/code-dp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Time: O(n) | Space: O(n) 6 | int maxSubsetSumNoAdjacent(vector array) 7 | { 8 | if (!array.size()) 9 | return INT_MIN; 10 | if (array.size() == 1) 11 | return array[0]; 12 | 13 | vector maxSums = array; 14 | maxSums[0] = array[0]; 15 | maxSums[1] = max(array[0], array[1]); 16 | 17 | for (int i = 2; i < array.size(); i++) 18 | { 19 | maxSums[i] = max(maxSums[i - 1], maxSums[i - 2] + array[i]); 20 | } 21 | 22 | return maxSums[maxSums.size() - 1]; 23 | } 24 | 25 | int main() 26 | { 27 | vector array{7, 10, 12, 7, 9, 14}; 28 | cout << maxSubsetSumNoAdjacent(array); 29 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Max Subset Sum No Adjacent - DP/problem.md: -------------------------------------------------------------------------------- 1 | ## Maximum Subset Sum With No Adjacent Elements 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of positive integers and returns an integer representing the maximum sum of non-adjacent elements in the array. If a sum 6 | cannot be generated, the function should return 0. 7 | 8 | `Sample input: [75, 105, 120, 75, 90, 135] Sample output: 330 (75, 120, 135)` 9 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Heap/problem.md: -------------------------------------------------------------------------------- 1 | ## Min Heap Construction 2 | 3 | #### Problem Statement 4 | 5 | Implement a Min Heap class. The class should support insertion, removal (of the minimum / root value), peeking (of the minimum / root value), as well as sifting a 6 | value up and down the heap and building the heap from an input array. The heap should be represented in the form of an array. 7 | 8 | Sample input: [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41] 9 | -> buildHeap(array) 10 | -> insert(76) 11 | -> remove() 12 | -> remove() 13 | -> insert(87) 14 | 15 | Sample output: 16 | -> [-5, 2, 6, 7, 8, 8, 24, 391, 24, 56, 12, 24, 48, 41] 17 | -> [-5, 2, 6, 7, 8, 8, 24, 391, 24, 56, 12, 24, 48, 41, 76] 18 | -> [2, 7, 6, 24, 8, 8, 24, 391, 76, 56, 12, 24, 48, 41] 19 | -> [6, 7, 8, 24, 8, 24, 24, 391, 76, 56, 12, 41, 48] 20 | -> [6, 7, 8, 24, 8, 24, 24, 391, 76, 56, 12, 41, 48, 87] 21 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Height BST/code-return-bst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class BST 4 | { 5 | public: 6 | int value; 7 | BST *left; 8 | BST *right; 9 | BST(int value) 10 | { 11 | this->value = value; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | // We don't use this method for this solution. 16 | void insert(int value) 17 | { 18 | if (value < this->value) 19 | { 20 | if (left == NULL) 21 | { 22 | left = new BST(value); 23 | } 24 | else 25 | { 26 | left->insert(value); 27 | } 28 | } 29 | else 30 | { 31 | if (right == NULL) 32 | { 33 | right = new BST(value); 34 | } 35 | else 36 | { 37 | right->insert(value); 38 | } 39 | } 40 | } 41 | }; 42 | BST *constructMinHeightBst(vector array, int startIdx, int endIdx); 43 | // O(n) time | O(n) space - where n is the length of the array 44 | BST *minHeightBst(vector array) 45 | { 46 | return constructMinHeightBst(array, 0, array.size() - 1); 47 | } 48 | BST *constructMinHeightBst(vector array, int startIdx, int endIdx) 49 | { 50 | if (endIdx < startIdx) 51 | return NULL; 52 | int midIdx = (startIdx + endIdx) / 2; 53 | BST *bst = new BST(array[midIdx]); 54 | bst->left = constructMinHeightBst(array, startIdx, midIdx - 1); 55 | bst->right = constructMinHeightBst(array, midIdx + 1, endIdx); 56 | return bst; 57 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Height BST/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class BST 4 | { 5 | public: 6 | int value; 7 | BST *left; 8 | BST *right; 9 | BST(int value) 10 | { 11 | this->value = value; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | void insert(int value) 16 | { 17 | if (value < this->value) 18 | { 19 | if (left == NULL) 20 | { 21 | left = new BST(value); 22 | } 23 | else 24 | { 25 | left->insert(value); 26 | } 27 | } 28 | else 29 | { 30 | if (right == NULL) 31 | { 32 | right = new BST(value); 33 | } 34 | else 35 | { 36 | right->insert(value); 37 | } 38 | } 39 | } 40 | }; 41 | BST *constructMinHeightBst(vector array, BST *bst, int startIdx, 42 | int endIdx); 43 | // O(nlog(n)) time | O(n) space - where n is the length of the array 44 | BST *minHeightBst(vector array) 45 | { 46 | return constructMinHeightBst(array, NULL, 0, array.size() - 1); 47 | } 48 | BST *constructMinHeightBst(vector array, BST *bst, int startIdx, 49 | int endIdx) 50 | { 51 | if (endIdx < startIdx) 52 | return NULL; 53 | int midIdx = (startIdx + endIdx) / 2; 54 | int valueToAdd = array[midIdx]; 55 | if (bst == NULL) 56 | { 57 | bst = new BST(valueToAdd); 58 | } 59 | else 60 | { 61 | bst->insert(valueToAdd); 62 | } 63 | constructMinHeightBst(array, bst, startIdx, midIdx - 1); 64 | constructMinHeightBst(array, bst, midIdx + 1, endIdx); 65 | return bst; 66 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Height BST/problem.md: -------------------------------------------------------------------------------- 1 | Given a sorted array of integers, construct a minimum height BST out of it. 2 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Max Stack/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class MinMaxStack 5 | { 6 | public: 7 | vector> minMaxStack = {}; 8 | vector stack = {}; 9 | // O(1) time | O(1) space 10 | int peek() { return stack[stack.size() - 1]; } 11 | // O(1) time | O(1) space 12 | int pop() 13 | { 14 | minMaxStack.pop_back(); 15 | int result = stack[stack.size() - 1]; 16 | stack.pop_back(); 17 | return result; 18 | } 19 | // O(1) time | O(1) space 20 | void push(int number) 21 | { 22 | unordered_map newMinMax = {{"min", number}, {"max", number}}; 23 | if (minMaxStack.size()) 24 | { 25 | unordered_map lastMinMax = 26 | minMaxStack[minMaxStack.size() - 1]; 27 | newMinMax["min"] = min(lastMinMax["min"], number); 28 | newMinMax["max"] = max(lastMinMax["max"], number); 29 | } 30 | minMaxStack.push_back(newMinMax); 31 | stack.push_back(number); 32 | } 33 | // O(1) time | O(1) space 34 | int getMin() { return minMaxStack[minMaxStack.size() - 1]["min"]; } 35 | // O(1) time | O(1) space 36 | int getMax() { return minMaxStack[minMaxStack.size() - 1]["max"]; } 37 | }; -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Max Stack/problem.md: -------------------------------------------------------------------------------- 1 | ## Min Max Stack Construction 2 | 3 | #### Problem Statement 4 | 5 | Write a Min Max Stack class. The class should support pushing and popping values on and off the stack, peeking at values at the top of the stack, and getting both 6 | the minimum and the maximum values in the stack. All class methods, when considered independently, should run in constant time and with constant space. 7 | 8 | Sample input: 9 | -> push(5) 10 | -> getMin() 11 | -> getMax() 12 | -> peek() 13 | -> push(7) 14 | -> getMin() 15 | -> getMax() 16 | -> peek() 17 | -> push(2) 18 | -> getMin() 19 | -> getMax() 20 | -> peek() 21 | -> pop() 22 | -> pop() 23 | -> getMin() 24 | -> getMax() 25 | -> peek() 26 | 27 | Sample output: 28 | -> (push 5) 29 | -> 5 (min) 30 | -> 5 (max) 31 | -> 5 (peek) 32 | -> (push 7) 33 | -> 5 (min) 34 | -> 7 (max) 35 | -> 7 (peek) 36 | -> (push 2) 37 | -> 2 (min) 38 | -> 7 (max) 39 | -> 2 (peek) 40 | -> 2 (pop) 41 | -> 7 (pop) 42 | -> 5 (min) 43 | -> 5 (max) 44 | -> 5 (peek) 45 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Number Of Couns For Change/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int minCoinChange(vector denoms, int n) 6 | { 7 | vector numOfCoins(n + 1, INT_MAX); 8 | numOfCoins[0] = 0; 9 | int toCompare = 0; 10 | for (int denom : denoms) 11 | { 12 | for (int amount = 0; amount < numOfCoins.size(); amount++) 13 | { 14 | if (denom <= amount) 15 | { 16 | if (numOfCoins[amount - denom] == INT_MAX) 17 | { 18 | toCompare = numOfCoins[amount - denom]; 19 | } 20 | else 21 | { 22 | toCompare = numOfCoins[amount - denom] + 1; 23 | } 24 | 25 | numOfCoins[amount] = min(numOfCoins[amount], toCompare); 26 | } 27 | } 28 | } 29 | return numOfCoins[n] != INT_MAX ? numOfCoins[n] : -1; 30 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Min Number Of Couns For Change/problem.md: -------------------------------------------------------------------------------- 1 | ## Min Number Of Coins For Change 2 | 3 | #### Problem Statement 4 | 5 | Given an array of positive integers representing coin denominations and a single non-negative integer representing a target amount of money, implement a 6 | function that returns the smallest number of coins needed to make change for that target amount using the given coin denominations. Note that an unlimited 7 | amount of coins is at your disposal. If it is impossible to make change for the target amount, return -1. 8 | 9 | Sample input: 7, [1, 5, 10] 10 | 11 | Sample output: 3 (2x1 + 1x5) 12 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Monotonic Array/code-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool breaksDirection(int direction, int prev, int curr) 6 | { 7 | int difference = curr - prev; 8 | if (direction > 0) 9 | { 10 | return difference < 0; 11 | } 12 | return difference > 0; 13 | } 14 | 15 | bool isMonotonic(vector array) 16 | { 17 | if (array.size() <= 2) 18 | return true; 19 | 20 | int direction = array[1] - array[0]; 21 | 22 | for (int i = 2; i < array.size(); i++) 23 | { 24 | if (direction == 0) 25 | { 26 | direction = array[i] - array[i - 1]; 27 | continue; 28 | } 29 | 30 | if (breaksDirection(direction, array[i - 1], array[i])) 31 | return false; 32 | } 33 | return true; 34 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Monotonic Array/code.cpp: -------------------------------------------------------------------------------- 1 | // Time : O(n) | Space O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool isMonotonic(vector array) 8 | { 9 | bool isNonDecreasing = true; 10 | bool isNonIncreasing = true; 11 | 12 | for (int i = 1; i < array.size(); i++) 13 | { 14 | if (array[i] < array[i - 1]) 15 | { 16 | isNonDecreasing = false; 17 | } 18 | { 19 | if (array[i] > array[i - 1]) 20 | { 21 | isNonIncreasing = false; 22 | } 23 | } 24 | 25 | return isNonDecreasing || isNonIncreasing; 26 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Monotonic Array/problem.md: -------------------------------------------------------------------------------- 1 | Determine if the array is strictly increasing or strictly decreasing. 2 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Move Element To End/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Medium/Move Element To End/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Move Element To End/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(1)s 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector moveElementToEnd(vector &arr, int target) 8 | { 9 | int start = 0; 10 | int end = arr.size() - 1; 11 | 12 | while (start < end) 13 | { 14 | while (start < end && arr[end] == target) // imp stat start < end 15 | { 16 | end--; 17 | } 18 | if (arr[start] == target) 19 | { 20 | swap(arr[start], arr[end]); 21 | } 22 | start++; 23 | } 24 | 25 | return arr; 26 | } 27 | 28 | int main() 29 | { 30 | vector arr{2, 1, 2, 2, 2, 3, 4, 2}; 31 | 32 | moveElementToEnd(arr, 2); 33 | 34 | for (int i = 0; i < arr.size(); i++) 35 | { 36 | cout << arr[i] << " "; 37 | } 38 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Move Element To End/problem.md: -------------------------------------------------------------------------------- 1 | Move all the target numbers to the end of the array 2 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Number Of Ways To Make Change/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Time: O(nd) | Space: O(n) 6 | int numberOfWaysToMakeChange(vector denominations, int targetAmount) 7 | { 8 | vector ways(targetAmount + 1); // dp array 9 | ways[0] = 1; 10 | 11 | for (int denom : denominations) 12 | { 13 | for (int amount = 1; amount < targetAmount + 1; amount++) 14 | { 15 | if (denom <= amount) 16 | { 17 | ways[amount] += ways[amount - denom]; 18 | } 19 | } 20 | } 21 | return ways[targetAmount]; 22 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Number Of Ways To Make Change/problem.md: -------------------------------------------------------------------------------- 1 | You're given a target currency amd an array of coins. Meet the target sum by using the given coins, you can use any number of coins as many times. 2 | 3 | I/p: \$10, [1, 5, 10, 25] 4 | O/p: 4 5 | 6 | Explanation: 7 | 1*10 8 | 5*2 9 | 1*5 + 5*1 10 | 10\*1 11 | 12 | Total 4 ways 13 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Permutations/code-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void permutationsHelper(int i, vector *array, 4 | vector> *permutations); 5 | void swap(vector *array, int i, int j); 6 | // O(n*n!) time | O(n*n!) space 7 | vector> getPermutations(vector array) 8 | { 9 | vector> permutations; 10 | permutationsHelper(0, &array, &permutations); 11 | return permutations; 12 | } 13 | void permutationsHelper(int i, vector *array, 14 | vector> *permutations) 15 | { 16 | if (i == array->size() - 1) 17 | { 18 | permutations->push_back(*array); 19 | } 20 | else 21 | { 22 | for (int j = i; j < array->size(); j++) 23 | { 24 | swap(array, i, j); 25 | permutationsHelper(i + 1, array, permutations); 26 | swap(array, i, j); 27 | } 28 | } 29 | } 30 | void swap(vector *array, int i, int j) 31 | { 32 | int tmp = array->at(i); 33 | array->at(i) = array->at(j); 34 | array->at(j) = tmp; 35 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Permutations/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void permutationsHelper(vector array, vector currentPermutations, vector> *permutations); 5 | 6 | // Upper Bound: O(n^2 * n!) Time | Space: O(n*n!) 7 | // Roughly: O(n*n!) Time | Space: O(n*n!) 8 | 9 | vector> getPermutations(vector array) 10 | { 11 | vector> permutations; 12 | 13 | permutationsHelper(array, {}, &permutations); 14 | return permutations; 15 | } 16 | 17 | void permutationsHelper(vector array, vector currentPermutations, vector> *permutations) 18 | { 19 | if (array.size() == 0 && currentPermutations.size() > 0) 20 | { 21 | permutations->push_back(currentPermutations); 22 | } 23 | else 24 | { 25 | for (int i = 0; i < array.size(); i++) 26 | { 27 | vector newArray; 28 | newArray.insert(newArray.end(), array.begin(), array.begin() + i); 29 | newArray.insert(newArray.end(), array.begin() + i + 1, array.end()); 30 | vector newPermutation = currentPermutations; 31 | newPermutation.push_back(array[i]); 32 | permutationsHelper(newArray, newPermutation, permutations); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Permutations/problem.md: -------------------------------------------------------------------------------- 1 | ## Permutations 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of unique integers and returns an array of all permutations of those integers. If the input array is empty, your function 6 | should return an empty array. 7 | 8 | Sample input: [1, 2, 3] 9 | 10 | Sample output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Remove nth Node Fron Linked List/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class LinkedList 6 | { 7 | public: 8 | int value; 9 | LinkedList *next; 10 | 11 | LinkedList(int value); 12 | }; 13 | 14 | // Time: O(n) | Space: O(1) 15 | 16 | void removeKthNode(LinkedList *head, int k) 17 | { 18 | int counter = 1; 19 | LinkedList *first = head; 20 | LinkedList *second = head; 21 | 22 | while (counter <= k) 23 | { 24 | second = second->next; 25 | counter++; 26 | } 27 | 28 | if (second == NULL) 29 | { 30 | head->value = head->next->value; 31 | head->next = head->next->next; 32 | } 33 | while (second->next != NULL) 34 | { 35 | second = second->next; 36 | first = first->next; 37 | } 38 | first->next = first->next->next; 39 | } 40 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Remove nth Node Fron Linked List/problem.md: -------------------------------------------------------------------------------- 1 | ## Remove Kth Node From End 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in the head of a Singly Linked List and an integer k (assume that the list has at least k nodes). The function should remove the kth node 6 | from the end of the list. Note that every node in the Singly Linked List has a "value" property storing its value as well as a "next" property pointing to the next node 7 | in the list or None (null) if it is the tail of the list. 8 | 9 | Sample input: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9, 4 10 | 11 | Sample output: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 7 -> 8 -> 9 12 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/River Sizes/problem.md: -------------------------------------------------------------------------------- 1 | ## River Sizes 2 | 3 | #### Problem Statement 4 | 5 | You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents 6 | part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent). The number of adjacent 1s 7 | forming a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input matrix. Note that these sizes do not need 8 | to be in any particular order. 9 | 10 | Sample input: 11 | [ 12 | [1, 0, 0, 1, 0], 13 | [1, 0, 1, 0, 0], 14 | [0, 0, 1, 0, 1], 15 | [1, 0, 1, 0, 1], 16 | [1, 0, 1, 1, 0], 17 | ] 18 | 19 | Sample output: [1, 2, 2, 2, 5] 20 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Search In Sorted Matrix/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // O(n) time | O(1) space 4 | vector searchInSortedMatrix(vector> matrix, int target) 5 | { 6 | int row = 0; 7 | int col = matrix[0].size() - 1; 8 | while (row < matrix.size() && col >= 0) 9 | { 10 | if (matrix[row][col] > target) 11 | { 12 | col--; 13 | } 14 | else if (matrix[row][col] < target) 15 | { 16 | row++; 17 | } 18 | else 19 | { 20 | return {row, col}; 21 | } 22 | } 23 | return {-1, -1}; 24 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Search In Sorted Matrix/problem.md: -------------------------------------------------------------------------------- 1 | ## Search In Sorted Matrix 2 | 3 | #### Problem Statement 4 | 5 | You are given a two-dimensional array (matrix) of distinct integers where each row is sorted and each column is also sorted. The matrix does not necessarily have 6 | the same height and width. You are also given a target number, and you must write a function that returns an array of the row and column indices of the target 7 | number if it is contained in the matrix and [-1, -1] if it is not contained in the matrix. 8 | 9 | Sample input: 10 | [ 11 | [1, 4, 7, 12, 15, 1000], 12 | [2, 5, 19, 31, 32, 1001], 13 | [3, 8, 24, 33, 35, 1002], 14 | [40, 41, 42, 44, 45, 1003], 15 | [99, 100, 103, 106, 128, 1004], 16 | ], 44 17 | 18 | Sample output: [3, 3] 19 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Single Cycle Check/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | int getNextIdx(int currentIdx, vector array); 5 | bool hasSingleCycle(vector array) 6 | { 7 | int numEleVisited = 0; 8 | int currentIdx = 0; 9 | 10 | while (numEleVisited < array.size()) 11 | { 12 | if (numEleVisited > 0 && currentIdx == 0) 13 | return false; 14 | 15 | numEleVisited++; 16 | currentIdx = getNextIdx(currentIdx, array); 17 | } 18 | } 19 | 20 | int getNextIdx(int currentIdx, vector array) 21 | { 22 | int jump = array[currentIdx]; 23 | int nextIdx = (currentIdx + jump) % (array.size()); 24 | 25 | return nextIdx >= 0 ? nextIdx : nextIdx + array.size(); 26 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Single Cycle Check/problem.md: -------------------------------------------------------------------------------- 1 | ## Single Cycle Check 2 | 3 | #### Problem Statement 4 | 5 | You are given an array of integers. Each integer represents a jump of its value in the array. For instance, the integer 2 represents a jump of 2 indices forward in the array; the integer -3 represents a jump of 3 indices backward in the array. If a jump spills past the array's bounds, it wraps over to the other side. For instance, a 6 | jump of -1 at index 0 brings us to the last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0. Write a function that returns a 7 | boolean representing whether the jumps in the array form a single cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every 8 | element is visited exactly once before landing back on the starting index. 9 | 10 | `Sample input: [2, 3, 1, -4, -4, 2] Sample output: True` 11 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Smallest Difference/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: (O(nlogn) + O(mlogm)) | Space: O(1) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector smallestDifference(vector arrayOne, vector arrayTwo) 8 | { 9 | sort(arrayOne.begin(), arrayOne.end()); 10 | sort(arrayTwo.begin(), arrayTwo.end()); 11 | 12 | int idxOne = 0; 13 | int idxTwo = 0; 14 | int smallest = INT_MAX; 15 | int current = INT_MAX; 16 | 17 | vector smallestPair; 18 | while (idxOne < arrayOne.size() && idxTwo < arrayTwo.size()) 19 | { 20 | int firstNum = arrayOne[idxOne]; 21 | int secondNum = arrayTwo[idxTwo]; 22 | 23 | if (firstNum < secondNum) 24 | { 25 | current = secondNum - firstNum; 26 | idxOne++; 27 | } 28 | else if (secondNum < firstNum) 29 | { 30 | current = firstNum - secondNum; 31 | idxTwo++; 32 | } 33 | else 34 | { 35 | return vector{firstNum, secondNum}; // both equal so diff = 0; 36 | } 37 | if (smallest > current) 38 | { 39 | smallest = current; 40 | smallestPair = {firstNum, 41 | secondNum}; 42 | } 43 | } 44 | return smallestPair; 45 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Smallest Difference/problem.md: -------------------------------------------------------------------------------- 1 | ## Smallest Difference 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in two non-empty arrays of integers. The function should nd the pair of numbers (one from the rst array, one from the second array) 6 | whose absolute difference is closest to zero. The function should return an array containing these two numbers, with the number from the rst array in the rst 7 | position. Assume that there will only be one pair of numbers with the smallest difference. 8 | Sample input: [-1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17] 9 | Sample output: [28, 26] 10 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Spiral Traversal/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Algorithms/Medium/Spiral Traversal/a.exe -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Spiral Traversal/code-recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // O(n) time | O(n) space - where n is the total number of elements in the array 4 | void spiralFill(vector> array, int startRow, int endRow, 5 | int startCol, int endCol, vector &result) 6 | { 7 | if (startRow > endRow || startCol > endCol) 8 | { 9 | return; 10 | } 11 | for (int col = startCol; col <= endCol; col++) 12 | { 13 | result.push_back(array[startRow][col]); 14 | } 15 | for (int row = startRow + 1; row <= endRow; row++) 16 | { 17 | result.push_back(array[row][endCol]); 18 | } 19 | for (int col = endCol - 1; col >= startCol; col--) 20 | { 21 | if (startRow == endRow) 22 | break; 23 | result.push_back(array[endRow][col]); 24 | } 25 | for (int row = endRow - 1; row >= startRow + 1; row--) 26 | { 27 | if (startCol == endCol) 28 | break; 29 | result.push_back(array[row][startCol]); 30 | } 31 | spiralFill(array, startRow + 1, endRow - 1, startCol + 1, endCol - 1, result); 32 | } 33 | vector spiralTraverse(vector> array) 34 | { 35 | if (array.size() == 0) 36 | return {}; 37 | vector result = {}; 38 | spiralFill(array, 0, array.size() - 1, 0, array[0].size() - 1, result); 39 | return result; 40 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Spiral Traversal/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n) | Space: O(n) , n = total number of elements in the array 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector spiralTraversal(vector> array) 8 | { 9 | int size = array.size(); 10 | 11 | int sr = 0; // start row 12 | int sc = 0; // start column 13 | int er = size - 1; // end row 14 | int ec = size - 1; // end column 15 | vector final; 16 | while (sr < er && sc < ec) 17 | { 18 | for (int i = sc; i <= ec; i++) 19 | { 20 | final.push_back(array[sr][i]); 21 | } 22 | 23 | for (int i = sr + 1; i <= er; i++) 24 | { 25 | final.push_back(array[i][ec]); 26 | } 27 | 28 | for (int i = ec - 1; i >= sc; i--) 29 | { 30 | if (sr == er) 31 | break; 32 | final.push_back(array[er][i]); 33 | } 34 | 35 | for (int i = er - 1; i > sr; i--) 36 | { 37 | if (sc == ec) 38 | break; 39 | final.push_back(array[i][sc]); 40 | } 41 | 42 | sc++; 43 | sr++; 44 | er--; 45 | ec--; 46 | } 47 | 48 | for (int i = 0; i < final.size(); i++) 49 | { 50 | cout << final[i] << " "; 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | vector> traversal{ 57 | {1, 2, 3, 4}, 58 | {12, 13, 14, 5}, 59 | {11, 16, 15, 6}, 60 | {10, 9, 8, 7}}; 61 | 62 | spiralTraversal(traversal); 63 | 64 | // for (int i = 0; i < traversal.size(); i++) 65 | // { 66 | // for (int j = 0; j < traversal.size(); j++) 67 | // { 68 | // cout << traversal[i][j] << " "; 69 | // } 70 | // cout << endl; 71 | // } 72 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Suffix Trie/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class TrieNode 4 | { 5 | public: 6 | unordered_map children; 7 | }; 8 | class SuffixTrie 9 | { 10 | public: 11 | TrieNode *root; 12 | char endSymbol; 13 | SuffixTrie(string str) 14 | { 15 | this->root = new TrieNode(); 16 | this->endSymbol = '*'; 17 | this->populateSuffixTrieFrom(str); 18 | } 19 | // O(n^2) time | O(n^2) space 20 | void populateSuffixTrieFrom(string str) 21 | { 22 | for (int i = 0; i < str.length(); i++) 23 | { 24 | this->insertSubstringStartingAt(i, str); 25 | } 26 | } 27 | void insertSubstringStartingAt(int i, string str) 28 | { 29 | TrieNode *node = this->root; 30 | for (int j = i; j < str.length(); j++) 31 | { 32 | char letter = str[j]; 33 | if (node->children.find(letter) == node->children.end()) 34 | { 35 | TrieNode *newNode = new TrieNode(); 36 | node->children.insert({letter, newNode}); 37 | } 38 | node = node->children[letter]; 39 | } 40 | node->children.insert({this->endSymbol, NULL}); 41 | } 42 | // O(m) time | O(1) space 43 | bool contains(string str) 44 | { 45 | TrieNode *node = this->root; 46 | for (char letter : str) 47 | { 48 | if (node->children.find(letter) == node->children.end()) 49 | { 50 | return false; 51 | } 52 | node = node->children[letter]; 53 | } 54 | return node->children.find(this->endSymbol) != node->children.end(); 55 | } 56 | }; -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Three Number Sum/code.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n^2) | Space: O(1) -- sorting time : O(nlogn) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector> threeNumberSum(vector array, int target) 8 | { 9 | sort(array.begin(), array.end()); 10 | 11 | vector> triplets; 12 | 13 | for (int i = 0; i < array.size() - 2; i++) 14 | { 15 | int left = i + 1; 16 | int right = array.size() - 1; 17 | 18 | while (left < right) 19 | { 20 | int currentSum = array[i] + array[left] + array[right]; 21 | 22 | if (currentSum == target) 23 | { 24 | triplets.push_back({array[i], array[left], array[right]}); 25 | left++; 26 | right--; 27 | } 28 | else if (currentSum < target) 29 | { 30 | left++; 31 | } 32 | else if (currentSum > target) 33 | { 34 | right--; 35 | } 36 | } 37 | } 38 | return triplets; 39 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Three Number Sum/problem.md: -------------------------------------------------------------------------------- 1 | ## Three Number Sum 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should nd all triplets in the array that 6 | sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the 7 | triplets themselves should be ordered in ascending order with respect to the numbers they hold. If no three numbers sum up to the target sum, the function 8 | should return an empty array. 9 | 10 | Sample input: [12, 3, 1, 2, -6, 5, -8, 6], 0 11 | 12 | Sample output: [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]] 13 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Validate BST/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class BST 4 | { 5 | public: 6 | int value; 7 | BST *left; 8 | BST *right; 9 | BST(int val); 10 | BST &insert(int val); 11 | }; 12 | bool validateBst(BST *tree); 13 | bool validateBstHelper(BST *tree, int minValue, int maxValue); 14 | // O(n) time | O(d) spaceS 15 | 16 | bool validateBst(BST *tree) 17 | { 18 | return validateBstHelper(tree, INT_MIN, INT_MAX); 19 | } 20 | 21 | bool validateBst(BST *root, int minValue, int maxValue) 22 | { 23 | if (root == NULL) 24 | return true; 25 | 26 | if (root->value < minValue || root->value >= maxValue) 27 | return false; 28 | 29 | bool isLeftValid = validateBstHelper(root->left, minValue, root->value); 30 | bool isRightValid = validateBstHelper(root->right, root->value, maxValue); 31 | 32 | return isLeftValid && isRightValid; 33 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Validate BST/problem.md: -------------------------------------------------------------------------------- 1 | ## Validate BST 2 | 3 | #### Problem Statement 4 | 5 | You are given a Binary Tree data structure consisting of Binary Tree nodes. Each Binary Tree node has an integer value stored in a property called "value" and two 6 | children nodes stored in properties called "left" and "right," respectively. Children nodes can either be Binary Tree nodes themselves or the None (null) value. Write a function that returns a boolean representing whether or not the Binary Tree is a valid BST. A node is said to be a BST node if and only if it satises the BST 7 | property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and both of its 8 | children nodes are either BST nodes themselves or None (null) values. 9 | 10 | Sample input: 11 | 10 12 | / \ 13 | 5 15 14 | / \ / \ 15 | 2 5 13 22 16 | / \ 17 | 1 14 18 | 19 | Sample output: True 20 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/Youngest Common Ancestor/problem.md: -------------------------------------------------------------------------------- 1 | ## Youngest Common Ancestor 2 | 3 | #### Problem Statement 4 | 5 | You're given three inputs, all of which are instances of a class that have an "ancestor" property pointing to their youngest ancestor. The rst input is the top 6 | ancestor in an ancestral tree (i.e., the only instance that has no ancestor), and the other two inputs are descendants in the ancestral tree. Write a function that 7 | returns the youngest common ancestor to the two descendants. 8 | 9 | Sample input: Node A, Node E, Node I (from the ancestral tree below) 10 | A 11 | / \ 12 | B C 13 | / \ / \ 14 | D E F G 15 | / \ 16 | H I 17 | -------------------------------------------------------------------------------- /Interview Algorithms/Medium/powerset/code-iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // O(n*2^n) time | O(n*2^n) space 4 | vector> powerset(vector array) 5 | { 6 | vector> subsets = {{}}; 7 | for (int ele : array) 8 | { 9 | int length = subsets.size(); 10 | for (int i = 0; i < length; i++) 11 | { 12 | vector currentSubset = subsets[i]; 13 | currentSubset.push_back(ele); 14 | subsets.push_back(currentSubset); 15 | } 16 | } 17 | return subsets; 18 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/powerset/code-recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector> powersetHelper(vector array, int idx); 4 | // O(n*2^n) time | O(n*2^n) space 5 | vector> powerset(vector array) 6 | { 7 | return powersetHelper(array, array.size() - 1); 8 | } 9 | vector> powersetHelper(vector array, int idx) 10 | { 11 | if (idx < 0) 12 | { 13 | return vector>{{}}; 14 | } 15 | int ele = array[idx]; 16 | vector> subsets = powersetHelper(array, idx - 1); 17 | int length = subsets.size(); 18 | for (int i = 0; i < length; i++) 19 | { 20 | vector currentSubset = subsets[i]; 21 | vector newSubset = currentSubset; 22 | newSubset.push_back(ele); 23 | subsets.push_back(newSubset); 24 | } 25 | return subsets; 26 | } -------------------------------------------------------------------------------- /Interview Algorithms/Medium/powerset/problem.md: -------------------------------------------------------------------------------- 1 | ## Powerset 2 | 3 | #### Problem Statement 4 | 5 | Write a function that takes in an array of unique integers and returns its powerset. The powerset P(X) of a set X is the set of all subsets of X. For example, the 6 | powerset of [1,2] is [[], [1], [2], [1,2]]. Note that the sets in the powerset do not need to be in any particular order. 7 | 8 | Sample input: [1, 2, 3] 9 | 10 | Sample output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] 11 | -------------------------------------------------------------------------------- /Interview Cake/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Cake/Easy/.keep -------------------------------------------------------------------------------- /Interview Cake/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Cake/Hard/.keep -------------------------------------------------------------------------------- /Interview Cake/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Cake/Medium/.keep -------------------------------------------------------------------------------- /Interview Camp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Interview Camp/.keep -------------------------------------------------------------------------------- /Leetcode Interview Questions/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode Interview Questions/Easy/.keep -------------------------------------------------------------------------------- /Leetcode Interview Questions/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode Interview Questions/Hard/.keep -------------------------------------------------------------------------------- /Leetcode Interview Questions/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode Interview Questions/Medium/.keep -------------------------------------------------------------------------------- /Leetcode/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode/Easy/.keep -------------------------------------------------------------------------------- /Leetcode/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode/Hard/.keep -------------------------------------------------------------------------------- /Leetcode/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Leetcode/Medium/.keep -------------------------------------------------------------------------------- /Prepbytes/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Easy/.keep -------------------------------------------------------------------------------- /Prepbytes/Easy/Birthday Gift/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | long long int a,b,c; 7 | cin>>a>>b>>c; 8 | if(b==a) 9 | std::cout<<"YES"<b&&c>0||a b && c > 0 OR a < b && c < 0 then we return NO because this way, we'll never be able to reach our target value 'b' 6 | 7 | Now if c == 0 and a == b then return true, but everything else will fail where c == 0 because difference is equal to zero and will never qualify for achieving b. 8 | 9 | finally, we calculate difference of b and a which gives 'u'. 10 | 11 | This 'u' must be divisible by difference 'c' in order to attain b. If the condition is satisfied, return true, else return false. 12 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Character Value/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | char c; 8 | cin>>c; 9 | 10 | if(c == 'P' || c == 'p') cout << "Paaji"; 11 | else if(c == 'Z' || c == 'z') cout << "Zenith"; 12 | else if(c == 'E' || c == 'e') cout << "Expert Coder"; 13 | else if(c == 'D' || c == 'd') cout << "Data Structure"; 14 | else cout << "none"; 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Character Value/problem.md: -------------------------------------------------------------------------------- 1 | Character Value 2 | You are provided with this table containing a character and its value. Given one of this character as input you need to print it's corresponding value. 3 | | P or p - Paaji | 4 | | Z or z - Zenith | 5 | | E or e - Expert Coder | 6 | | D or d - Data Structure | 7 | 8 | Input format 9 | A single character 10 | 11 | Output format 12 | For each test case print the corresponding value of the given character. 13 | 14 | Time Limit 15 | 1 16 | ​secon 17 | 18 | Example 19 | Input 20 | e 21 | 22 | Output 23 | Expert Coder -------------------------------------------------------------------------------- /Prepbytes/Easy/Character Value/solution.md: -------------------------------------------------------------------------------- 1 | The solution is simple: 2 | 3 | For every character that is input, Match the lower case and the uppercase with the corresponding word and print it. -------------------------------------------------------------------------------- /Prepbytes/Easy/Floyd Cycle/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *next; 9 | struct node *prev; 10 | }; 11 | 12 | bool floydCycle(struct node *head) 13 | { 14 | node *slow = head, *fast = head; 15 | 16 | while (slow != nullptr && fast != nullptr && fast->next != nullptr) 17 | { 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | if (slow == fast) 21 | return true; 22 | } 23 | return false; 24 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Leap Year or Not/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool leap(int); 4 | int main() 5 | { 6 | //write your code here 7 | 8 | int t; 9 | cin>>t; 10 | for(int i = t; i >0; i--) { 11 | int year; 12 | cin>>year; 13 | 14 | leap(year) ? cout << "Yes\n" : cout << "No\n"; 15 | } 16 | return 0; 17 | } 18 | 19 | bool leap(int year) { 20 | 21 | if(year % 400 == 0) return true; 22 | if(year % 100 == 0) return false; 23 | if(year % 4 == 0) return true; 24 | return false; 25 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Leap Year or Not/problem.md: -------------------------------------------------------------------------------- 1 | Given birthday year 2 | N 3 | of your friend, can you tell her if that is leap year or not? 4 | 5 | Input format 6 | The first line constains an integer 7 | T 8 | denoting the number of test cases. 9 | Each test case contains one integer 10 | N 11 | . 12 | 13 | Output format 14 | For each test case on a new line, print Yes if the given year is a leap year else print No. 15 | 16 | Constraints 17 | 1 18 | <= 19 | T 20 | <= 21 | 10 22 | 23 | 1 24 | <= 25 | N 26 | <= 27 | 2500 28 | 29 | Time Limit 30 | 1 31 | second 32 | 33 | Example 34 | Input 35 | 2 36 | 37 | 1900 38 | 39 | 2012 40 | 41 | Output 42 | No 43 | Yes 44 | 45 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Leap Year or Not/solution.md: -------------------------------------------------------------------------------- 1 | A classic beginners problem. 2 | If the year % 400 is equal to zero -> return true 3 | If the year % 100 is equal to zero -> return false 4 | If year % 4 is equal to 0 -> return true; 5 | 6 | return false 7 | 8 | Follow this order only. -------------------------------------------------------------------------------- /Prepbytes/Easy/Median of Sorted Array/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | /* Function to print an array */ 4 | void printArray(int arr[], int size) 5 | { 6 | int i; 7 | for (i = 0; i < size; i++) 8 | cout << arr[i] << " "; 9 | cout << endl; 10 | } 11 | 12 | void bubbleSort(int arr[], int length) 13 | { 14 | for (int i = 0; i < length - 1; i++) 15 | { 16 | for (int j = 0; j < length - i - 1; j++) 17 | { 18 | if (arr[j] > arr[j + 1]) 19 | { 20 | // swapping 21 | int temp = arr[j]; 22 | arr[j] = arr[j + 1]; 23 | arr[j + 1] = temp; 24 | } 25 | } 26 | } 27 | } 28 | 29 | int main() 30 | { 31 | //write your code here 32 | int length; 33 | std::cin >> length; 34 | 35 | int arr[length]; 36 | for (int i = 0; i < length; i++) 37 | { 38 | std::cin >> arr[i]; 39 | } 40 | 41 | bubbleSort(arr, length); 42 | int median = arr[(length - 1) / 2]; 43 | std::cout << median; 44 | // printArray(arr, length); 45 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Median of Sorted Array/problem.md: -------------------------------------------------------------------------------- 1 | Median of Sorted Array 2 | Sorting is another very important concept in competitive programming. Many of the problems can be solved easily if the elements are arranged in sorted order. We are going to solve one such problem. 3 | We all have studied the median in our schools, it is a simple concept. Let's say we have 4 | N 5 | numbers arranged in sorted order. Median is nothing but the mid element in case of an odd number of elements and in case of even number of elements it is the average of the two mid elements. 6 | 7 | To keep your task simple, we have kept 8 | N 9 | as odd for you. So, your task is to find the median among 10 | N 11 | elements. 12 | 13 | Input Format 14 | The input consists of two lines. 15 | First line contains 16 | N 17 | i.e total number of elements. 18 | Second lines contains 19 | N 20 | space separated unsorted integers 21 | A 22 | [ 23 | i 24 | ] 25 | . 26 | 27 | Output Format 28 | Print the median value. 29 | 30 | Constraints 31 | 1 32 | <= 33 | N 34 | <= 35 | 10 36 | 6 + 37 | 1 38 | 39 | − 40 | 10 41 | 4 42 | <= 43 | A 44 | [ 45 | i 46 | ] 47 | <= 48 | 10 49 | 4 50 | 51 | Example 52 | Input 53 | 7 54 | 0 1 2 4 6 5 3 55 | 56 | Output 57 | 3 58 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Median of Sorted Array/solution.md: -------------------------------------------------------------------------------- 1 | Sort the array, take the med element and return 2 | 3 | Sorting can be done with any sorting algorithm (I've taken bubble sort, Merge sort would perform much better) 4 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Modulus Ten/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int a; 8 | std::cin>>a; 9 | 10 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int a, b; 8 | std::cin >> a >> b; 9 | 10 | std::cout << a * b; 11 | return 0; 12 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Multiply Numbers/problem.md: -------------------------------------------------------------------------------- 1 | Multiply Numbers 2 | Let's practice multiplication a bit. 3 | Write a program to take two integers 4 | x 5 | and 6 | y 7 | as input from the user, multiply those integers and print the product. 8 | 9 | Input format 10 | Two space-separated integers are provided 11 | x 12 | and 13 | y 14 | . 15 | 16 | Output format 17 | Print a single integer representing the product of 18 | x 19 | and 20 | y 21 | as output. 22 | 23 | Constraints 24 | − 25 | 10 26 | <= 27 | a 28 | , 29 | b 30 | <= 31 | 40 32 | 33 | Time Limit 34 | 1 35 | ​secon 36 | 37 | Example 38 | Input 39 | 5 40 | 41 | 5 42 | 43 | Output 44 | 25 45 | 46 | Sample Test Case Explanation 47 | 5 48 | ∗ 49 | 5 50 | = 51 | 25 52 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Multiply Numbers/solution.md: -------------------------------------------------------------------------------- 1 | Simply multiply two numbers using a \* b and return the result. 2 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Number of Occurences/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int t; 8 | std::cin >> t; 9 | 10 | while(t--) { 11 | int size; 12 | std::cin >> size; 13 | 14 | char array[size]; 15 | 16 | for(int i = 0; i < size; i++) { 17 | std::cin>>array[i]; 18 | } 19 | 20 | int count = 0; 21 | for(int i = 0; i < size; i++) { 22 | if(array[i] == 'x') count++; 23 | } 24 | 25 | std::cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int x, y; 8 | cin>>x>>y; 9 | 10 | if(x > y) cout << x <<" is greater than " << y; 11 | else if (x < y) cout << x << " is smaller than " << y; 12 | else cout << x << " is equal to " << y; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Operators/problem.md: -------------------------------------------------------------------------------- 1 | Paaji wants you to get familiar with various Relational operators. He provides you with two numerical values 2 | X 3 | and 4 | Y 5 | and your task is to find the relation between them that is, 6 | 7 | X 8 | ​is smaller than 9 | Y 10 | X 11 | ​is greater than 12 | Y 13 | X 14 | ​is equal to 15 | Y 16 | Input format 17 | Two space-separated integers are provided denoted by 18 | X 19 | and 20 | Y 21 | . 22 | 23 | Output format 24 | Print the relation between 25 | X 26 | and 27 | Y 28 | . 29 | 30 | X is smaller than Y 31 | X is greater than Y 32 | X is equal to Y 33 | Constraints 34 | 1 35 | <= 36 | X 37 | , 38 | Y 39 | <= 40 | 100 41 | 42 | Time Limit 43 | 1 44 | ​secon 45 | 46 | Example 47 | Input 48 | 4 49 | 50 | 6 51 | 52 | Output 53 | 4 54 | ​is smaller than 55 | 6 56 | 57 | Sample test case explanation 58 | Since 59 | 4 60 | < 61 | 6 62 | , print 4 is smaller than 6 -------------------------------------------------------------------------------- /Prepbytes/Easy/Operators/solution.md: -------------------------------------------------------------------------------- 1 | Use comparision operators and print the respective answers. Simple! -------------------------------------------------------------------------------- /Prepbytes/Easy/Pattern Matching Naive/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Easy/Pattern Matching Naive/a.exe -------------------------------------------------------------------------------- /Prepbytes/Easy/Pattern Matching Naive/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | bool charMatch(string t, string p, int s, int m) 5 | { 6 | for (int j = 0; j < m; j++) 7 | { 8 | if (p[j] != t[s + j]) 9 | { 10 | return false; 11 | } 12 | } 13 | 14 | return true; 15 | } 16 | 17 | void naive_string_matching(string t, string p) 18 | { 19 | int n = t.length(); 20 | int m = p.length(); 21 | for (int s = 0; s <= n - m; s++) 22 | { 23 | if (charMatch(t, p, s, m)) 24 | { 25 | cout << "Pattern matches after " << s << " shifts"; 26 | } 27 | } 28 | } 29 | 30 | int main() 31 | { 32 | string t; 33 | cin >> t; 34 | 35 | string p; 36 | cin >> p; 37 | 38 | naive_string_matching(t, p); 39 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Pattern Matching Naive/problem.md: -------------------------------------------------------------------------------- 1 | Match a given pattern with a string 2 | 3 | string: manupaajiislit 4 | pattern: paaji 5 | 6 | Output: 4 // Matches after four shifts 7 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Pattern Matching Naive/solution.md: -------------------------------------------------------------------------------- 1 | Brute force approach: 2 | Match the given pattern word by word to the given string. 3 | 4 | Problem: Entirely ignores the information gained about text for one value of S, When it considers other values fo S. 5 | 6 | Time: O((n-m+1) \* m) 7 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Reverse A Doubly Linked List/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *next; 9 | struct node *prev; 10 | }; 11 | 12 | void reverse(struct node **head) 13 | { 14 | struct node *temp = NULL; 15 | 16 | struct node *current = *head; 17 | 18 | while (current != NULL) 19 | { 20 | temp = current->prev; 21 | current->prev = current->next; 22 | current->next = temp; 23 | current = current->prev; 24 | } 25 | 26 | if (temp != NULL) 27 | { 28 | *head = temp->prev; 29 | } 30 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Transition Point/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Easy/Transition Point/a.exe -------------------------------------------------------------------------------- /Prepbytes/Easy/Transition Point/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int findOne(int a[], int start, int end) 6 | { 7 | if (start > end) 8 | return -1; 9 | 10 | int mid = start + (end - start) / 2; 11 | 12 | if (a[mid] == 1 && (mid == 0 || a[mid - 1] == 0)) 13 | return mid; 14 | else if (a[mid] == 0) 15 | return findOne(a, mid + 1, end); 16 | else 17 | return findOne(a, start, mid - 1); 18 | } 19 | 20 | int main() 21 | { 22 | //write your code here 23 | 24 | int t; 25 | std::cin >> t; 26 | 27 | while (t--) 28 | { 29 | int n; 30 | std::cin >> n; 31 | 32 | int a[n]; 33 | 34 | for (int i = 0; i < n; i++) 35 | { 36 | std::cin >> a[i]; 37 | } 38 | 39 | int index = findOne(a, 0, n - 1); 40 | 41 | std::cout << index << std::endl; 42 | } 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Prepbytes/Easy/Transition Point/problem.md: -------------------------------------------------------------------------------- 1 | Transition Point 2 | Tina is a computer scientist and a part of her work requires her to find first occurence of 3 | 1 4 | in the array consisting of 5 | 0 6 | and 7 | 1 8 | . One good news is that array is sorted. Tina is sure that a sorted array will give solution to this problem in more efficient way. Can you write code to find first occurence of 9 | 1 10 | in the array consisting of 11 | 0 12 | and 13 | 1 14 | . 15 | 16 | Input 17 | First line contains an integer 18 | T 19 | , number of test cases. Then follows 20 | T 21 | test cases. Each test case consists of two lines. 22 | First line contains 23 | N 24 | , length of the array( 25 | 0 26 | -based indexing). Second lines contains 27 | N 28 | space separated integers 29 | 0 30 | and 31 | 1 32 | . 33 | 34 | Output 35 | Print 36 | T 37 | lines, each containing index of first occurence of 38 | 1 39 | if it exists else print 40 | − 41 | 1 42 | . 43 | 44 | Constraints 45 | 1 46 | <= 47 | T 48 | <= 49 | 10 50 | 51 | 1 52 | <= 53 | N 54 | <= 55 | 5 56 | ∗ 57 | 10 58 | 6 59 | 60 | A 61 | [ 62 | i 63 | ] 64 | = 65 | 0 66 | | 67 | 1 68 | 69 | Time Limit 70 | 1 second 71 | 72 | Example 73 | Input 74 | 2 75 | 5 76 | 0 0 1 1 1 77 | 4 78 | 0 0 0 0 79 | 80 | Output 81 | 2 82 | -1 83 | -------------------------------------------------------------------------------- /Prepbytes/Easy/Transition Point/solution.md: -------------------------------------------------------------------------------- 1 | This is done using Binary Search 2 | 3 | The basic algorithm is this: 4 | 5 | 1. Check if the mid is 1; if yes then check if the immediate left is 0; if yes, then we have the first occurence of 1. return the index. 6 | 2. if the mid is 1 and the immediate left is not zero, we iterate on the left half and find i.e. recurse on the left half and repeat the process. 7 | 3. If the mid == 0, that means the one's are in the right half of the array, we recurse in the right half. 8 | 4. If start > end meaning there are no one's then simply return -1. 9 | -------------------------------------------------------------------------------- /Prepbytes/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Hard/.keep -------------------------------------------------------------------------------- /Prepbytes/Hard/Fit Square/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int countSquare(bool arr, int, int); 6 | int main() 7 | { 8 | int t; 9 | cin>>t; 10 | while(t) { 11 | t--; 12 | int m, n; 13 | cin>>m>>n; 14 | 15 | int value = (m * n) / 2; 16 | 17 | cout << value << endl; 18 | } 19 | return 0; 20 | } -------------------------------------------------------------------------------- /Prepbytes/Hard/Fit Square/problem.md: -------------------------------------------------------------------------------- 1 | Fit Square 2 | Paaji provided you with a rectangular board of 3 | M 4 | x 5 | N 6 | dimension. Also, he provided an unlimited number of small blocks of 7 | 2 8 | x 9 | 1 10 | size. You are allowed to rotate the block. You are asked to place as many blocks as possible on the board to meet the following conditions: 11 | 1. Each block completely covers two squares. 12 | 2. No two blocks overlap. 13 | 3. Each block lies entirely inside the board. It is allowed to touch the edges of the board. 14 | Find the maximum number of blocks, which can be placed under these restrictions. 15 | 16 | Input format 17 | The first line contains an integer 18 | T 19 | denoting the number of test cases. 20 | In each of the next 21 | T 22 | lines, you are given two integers 23 | M 24 | and 25 | N 26 | 27 | Output format 28 | Print the maximal number of blocks, which can be placed. 29 | 30 | Constraints 31 | 1 32 | <= 33 | T 34 | <= 35 | 15 36 | 37 | 1 38 | ≤ 39 | M 40 | ≤ 41 | N 42 | ≤ 43 | 16 44 | 45 | Time Limit 46 | 1 47 | ​secon 48 | 49 | Example 50 | Input 51 | 1 52 | 53 | 2 54 | 55 | 5 56 | 57 | Output 58 | 5 -------------------------------------------------------------------------------- /Prepbytes/Hard/Fit Square/solution.md: -------------------------------------------------------------------------------- 1 | Since we are given 2:1 blocks and are allowed to rotate them vertically or horizontally 2 | Simplest solution would be to perform (m * n) / 2 where m and n are dimensions of the big box. -------------------------------------------------------------------------------- /Prepbytes/Hard/Shopping Cost/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int items; 8 | cin>>items; 9 | 10 | for(int i = 0; i < items; i++) { 11 | float quant, cost; 12 | 13 | cin>>quant>>cost; 14 | quant = quant; 15 | cost = cost; 16 | if(quant > 100) { 17 | printf("%0.1f", quant*cost - (quant*cost)*(20.0/100.0)); 18 | } else { 19 | printf("%0.1f",quant*cost); 20 | } 21 | 22 | cout << endl; 23 | // cout << "float value" << 20.0/100.0< 2 | using namespace std; 3 | 4 | int countN(int); 5 | int main() 6 | { 7 | //write your code here 8 | int t; 9 | cin>>t; 10 | 11 | for(int i = t; i > 0; i--) { 12 | int num; 13 | cin>>num; 14 | 15 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int boxes; 8 | cin>>boxes; 9 | int count = 0; 10 | for(int i = 0; i < boxes; i++) { 11 | int present, capacity; 12 | cin>>present>>capacity; 13 | 14 | if(capacity - present >=2 ) count++; 15 | } 16 | 17 | cout << count; 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Boxes and Toys/problem.md: -------------------------------------------------------------------------------- 1 | Boxes and Toys 2 | Tina and Rahul have 3 | 1 4 | toy each. They are entering into an amusement park but it is not allowed to take the toys inside, so they have to keep it in the boxes provided by the park management. They want to keep the toys together in one box. There are 5 | N 6 | boxes in total, at this moment there are 7 | t 8 | i 9 | toys present in 10 | i 11 | t 12 | h 13 | box and the maximum capacity of the box is denoted by 14 | c 15 | i 16 | . Rahul and Tina want to know in how many boxes can they keep their toys such that both the toys are in the same box. 17 | 18 | Input format 19 | The first line of the input contains integer 20 | N 21 | , denoting the count of boxes. 22 | Each of the next 23 | N 24 | lines contains two integers 25 | t 26 | i 27 | and 28 | c 29 | i 30 | denoting the number of toys present in the 31 | i 32 | t 33 | h 34 | box and the maximum capacity of that box. 35 | 36 | Output format 37 | Print the maximum number of boxes that fulfill the conditions. 38 | 39 | Constraints 40 | 1 41 | <= 42 | N 43 | <= 44 | 100 45 | 46 | 0 47 | <= 48 | t 49 | i 50 | , 51 | c 52 | i 53 | <= 54 | 100 55 | 56 | Time Limit 57 | 1 58 | ​secon 59 | 60 | Example 61 | Input 62 | 4 63 | 1 2 64 | 2 4 65 | 5 6 66 | 6 10 67 | 68 | Output 69 | 2 70 | 71 | Sample test case explanation 72 | It is only possible to keep both the toys in box2 and box4. -------------------------------------------------------------------------------- /Prepbytes/Medium/Boxes and Toys/solution.md: -------------------------------------------------------------------------------- 1 | We simply check if capacity - present is greater than 2, If yes then increment the count -------------------------------------------------------------------------------- /Prepbytes/Medium/Buddy and Socks/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int t; 8 | cin>>t; 9 | 10 | for(int i = t; i > 0; i--) { 11 | int pair; 12 | cin>>pair; 13 | 14 | cout << pair + 1 << endl; 15 | } 16 | 17 | // cout<< pair + 1 << endl; 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Buddy and Socks/problem.md: -------------------------------------------------------------------------------- 1 | Buddy and Socks 2 | Buddy is getting late for college. She is looking for a matching pair of socks from a box full of socks. In the worst-case scenario, how many socks should Buddy remove from her drawer until she finds a matching pair. 3 | 4 | Input format 5 | The first line contains the number of test cases 6 | T 7 | . 8 | Next 9 | T 10 | lines contain an integer 11 | N 12 | which indicates the total pairs of socks present in the drawer. 13 | 14 | Output format 15 | Print the number of draws Buddy will have to make in the worst case. 16 | 17 | Constraints 18 | 1 19 | <= 20 | T 21 | <= 22 | 1000 23 | 24 | 1 25 | <= 26 | N 27 | < 28 | 10 29 | 6 30 | 31 | Time Limit 32 | 1 33 | ​secon 34 | 35 | Example 36 | Input 37 | 2 38 | 39 | 1 40 | 41 | 2 42 | 43 | Output 44 | 2 45 | 46 | 3 47 | 48 | Sample Test case Explanation 49 | In the first test case, there is just 50 | 1 51 | pair of socks i.e 52 | 2 53 | socks in her drawer, so she has to remove both to get a pair, therefore the output is 54 | 2 55 | . -------------------------------------------------------------------------------- /Prepbytes/Medium/Buddy and Socks/solution.md: -------------------------------------------------------------------------------- 1 | This is very straightforward and doesn't require any explanation. -------------------------------------------------------------------------------- /Prepbytes/Medium/Clocks and Angles/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int computeAngle(int, int); 5 | int main() 6 | { 7 | //write your code here 8 | int t; 9 | cin>>t; 10 | 11 | for(int i = t; i > 0; i--) { 12 | float h, m; 13 | cin>>h; 14 | cin>>m; 15 | 16 | cout << computeAngle(h, m) << endl; 17 | } 18 | return 0; 19 | } 20 | 21 | 22 | int computeAngle(int h, int m) { 23 | float hourAngle, minAngle; 24 | 25 | // Calculate hour angle 26 | hourAngle = ((float)h + (float)m/60)*360/12; 27 | minAngle = 360*(float(m)/60); 28 | int total = hourAngle - minAngle; 29 | // return hourAngle - minAngle; 30 | if(total > 360/2) total = 360 - total; 31 | 32 | if(total > 0) return total; 33 | else return (-1)*total; 34 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Clocks and Angles/problem.md: -------------------------------------------------------------------------------- 1 | Clock and Angles 2 | PrepBuddy has an analog clock which consists of two hands one for hour and another for minute. She wants to calculate the shorter angle formed between hour and minute hand at any given time. 3 | 4 | Input format 5 | The first line contains the number of test cases 6 | T 7 | . 8 | Each test case contains two integers 9 | h 10 | and 11 | m 12 | representing the time in hour and minute format. 13 | 14 | Output format 15 | For each test case on a new line, print the required shorter angle. 16 | 17 | Constraints 18 | 1 19 | <= 20 | T 21 | <= 22 | 5 23 | 24 | All valid times 25 | 26 | Time Limit 27 | 1 28 | ​secon 29 | 30 | Example 31 | Input 32 | 2 33 | 34 | 5 35 | 36 | 30 37 | 38 | 6 39 | 40 | 00 41 | 42 | Output 43 | 15 44 | 45 | 180 -------------------------------------------------------------------------------- /Prepbytes/Medium/Clocks and Angles/solution.md: -------------------------------------------------------------------------------- 1 | 1. Create a separate function computeAngle which takes hour and minute as parameters. 2 | 2. Compute hourAngle with the formula (h + m/60)*360/12 3 | 3. Compute minAngle with the formula 360*(m / 60) 4 | 4. Compute total by subtracting minAngle from hourAngle 5 | 5. Return result if total > 0 -------------------------------------------------------------------------------- /Prepbytes/Medium/Find Closest Pair/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Medium/Find Closest Pair/a.exe -------------------------------------------------------------------------------- /Prepbytes/Medium/Find Closest Pair/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int findClosest(int arr[], int size, int target) 6 | { 7 | int low = 0, high = size - 1; 8 | 9 | if (target < arr[low]) 10 | return arr[low]; 11 | else if (target > arr[high]) 12 | return arr[high]; 13 | 14 | while (low <= high) 15 | { 16 | int mid = (low + high) / 2; 17 | 18 | if (arr[mid] == target) 19 | return arr[mid]; 20 | 21 | if (arr[mid] > target) 22 | { 23 | // check if target lies between the mid two numbers 24 | if (mid > 0 && arr[mid - 1] < target) 25 | { 26 | return min(target - arr[mid], arr[mid] - target); 27 | } 28 | high = mid - 1; 29 | } 30 | else 31 | { 32 | // if arr[mid] < target 33 | if (arr[mid + 1] > target) 34 | { 35 | return min(target - arr[mid + 1], arr[mid] - target); 36 | } 37 | low = mid + 1; 38 | } 39 | } 40 | } 41 | 42 | int main() 43 | { 44 | int t; 45 | cin >> t; 46 | 47 | while (t--) 48 | { 49 | int size; 50 | cin >> size; 51 | 52 | int arr[size]; 53 | int target; 54 | cin >> target; 55 | for (int i = 0; i < size; i++) 56 | { 57 | cin >> arr[i]; 58 | } 59 | 60 | cout << findClosest(arr, size, target); 61 | } 62 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Find Closest Pair/problem.md: -------------------------------------------------------------------------------- 1 | Find the number in the sorted array which is closest to the target given number 2 | 3 | IP: [1, 2, 3, 4, 5, 6, 7, 8, 9] 4 | Target: 11 5 | O/P: 9 6 | 7 | Since 9 is closest to 11, we return 11. 8 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Find Closest Pair/solution.md: -------------------------------------------------------------------------------- 1 | 1. O(n) approach 2 | 3 | Traverse the array and calculate minDiff at each element. The one which gives the minimum difference is the answer. 4 | 5 | 2. O(logn) Binary search 6 | 7 | Check the edge cases first. 8 | Traverse right if the target is greater than the mid, traverse left if the target is lesser than the mid. 9 | 10 | There's a catch here. We also check between arr[mid] and arr[mid-1] AND arr[mid] and arr[mid+1] to see if the element is present there. 11 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Find The Window/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int t; 8 | std::cin >> t; 9 | 10 | while (t--) 11 | { 12 | int size; 13 | std::cin >> size; 14 | ; 15 | 16 | int arr[size]; 17 | 18 | // Populate array 19 | for (int i = 0; i < size; i++) 20 | { 21 | std::cin >> arr[i]; 22 | } 23 | 24 | int start, end; 25 | for (start = 0; start < size - 1; start++) 26 | { 27 | if (arr[start] > arr[start + 1]) 28 | break; //starting index found 29 | } 30 | 31 | for (end = size - 1; end >= 0; end--) 32 | { 33 | if (arr[end] < arr[end - 1]) 34 | break; //ending index found 35 | } 36 | 37 | int max = INT_MIN, min = INT_MAX; 38 | 39 | // find maximum and minimum in the window -- which will later be compared in lh array and rh array 40 | for (int i = start; i <= end; i++) 41 | { 42 | if (max < arr[i]) 43 | max = arr[i]; 44 | if (min > arr[i]) 45 | min = arr[i]; 46 | } 47 | 48 | // Check min and max and edit the start and end position 49 | for (int i = 0; i < start; i++) 50 | { 51 | if (arr[i] > min) 52 | start = i; 53 | } 54 | 55 | for (int i = end; i < size; i++) 56 | { 57 | if (arr[i] < max) 58 | end = i; 59 | } 60 | 61 | std::cout << start << " " << end << std::endl; 62 | } 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Find The Window/problem.md: -------------------------------------------------------------------------------- 1 | Find the Window 2 | You are given an array that is not completely sorted but sorting a window in this array can make the whole array sorted. That window could be a complete array as well. So, out of several such parts, you have to find the one with minimum length. 3 | 4 | Input Format 5 | The first line contains an integer 6 | T 7 | , number of test cases. Then follows 8 | T 9 | test cases. Each test case consists of two lines. 10 | The first line contains 11 | N 12 | , size of the array. 13 | The second line contains 14 | N 15 | space-separated positive integers 16 | A 17 | [ 18 | i 19 | ] 20 | denoting elements of the array( 21 | 0 22 | -based indexing). 23 | 24 | Output Format 25 | The output contains 26 | T 27 | lines, each line contains two space-separated integers denoting start and end index of the minimum length window. 28 | 29 | Constraints 30 | 1 31 | <= 32 | T 33 | <= 34 | 10 35 | 36 | 1 37 | <= 38 | N 39 | <= 40 | 10 41 | 6 42 | 43 | 1 44 | <= 45 | A 46 | [ 47 | i 48 | ] 49 | <= 50 | 10 51 | 6 52 | 53 | Time Limit 54 | 1 second 55 | 56 | Example 57 | Input 58 | 2 59 | 8 60 | 1 3 2 7 5 6 4 8 61 | 10 62 | 1 2 5 3 4 6 8 7 10 9 63 | 64 | Output 65 | 1 6 66 | 2 9 67 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Find The Window/solution.md: -------------------------------------------------------------------------------- 1 | Approach: O(n) time 2 | 3 | 1. Take all the inputs 4 | 2. Traverse the array to find the 'start' index. if arr[i] > arr[i+1] then current index becomes our start index. 5 | 3. Similarly calculate end window index. if arr[i] < arr[i-1] then current becomes end index. 6 | 4. Now between start and end index, find min and max values. we do so because we need to find if there are any elements greater than the min element in the left side of the window; and if there are any elements greater than the max in right side of the window. 7 | 5. Now compare min with lhs of the window, if any element < min is found, this current index becomes the start index, same is for end index. 8 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Infix To Postfix Conversion/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Medium/Infix To Postfix Conversion/a.exe -------------------------------------------------------------------------------- /Prepbytes/Medium/Infix To Postfix Conversion/problem.md: -------------------------------------------------------------------------------- 1 | Convert an Infix expression to a postfix expression. 2 | 3 | A + B _ C ---> ABC+_ 4 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Infix To Postfix Conversion/solution.md: -------------------------------------------------------------------------------- 1 | Follow the algorithm which uses Stack 2 | 3 | 1. Create a stack. 4 | 2. For each element in the input 5 | if(t is an operand) 6 | Output t; 7 | else if (t is a right parenthesis) 8 | Pop and print tokens until a left parenthesis is popped. 9 | else // if t is an operator or a left parenthesis 10 | pop and output tokens until one of lower priority than t is encountered or stack is empty 11 | 3. Pop and output tokens until stack is empty 12 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Journey of Bablu and Dablu/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | 5 | void solve() 6 | { 7 | int n; 8 | cin >> n; 9 | 10 | int rem = n % 8; 11 | 12 | if (rem == 0) 13 | { 14 | cout << --n << "SL"; 15 | } 16 | else if (rem == 1 || rem == 2 || rem == 3) 17 | { 18 | cout << n + 3; 19 | 20 | if (rem == 1) 21 | { 22 | cout << "LB"; 23 | } 24 | 25 | if (rem == 2) 26 | { 27 | cout << "MB"; 28 | } 29 | if (rem == 3) 30 | { 31 | cout << "UB"; 32 | } 33 | } 34 | else if (rem == 4 || rem == 5 || rem == 6) 35 | { 36 | cout << n - 3; 37 | 38 | if (rem == 4) 39 | { 40 | cout << "LB"; 41 | } 42 | 43 | if (rem == 5) 44 | { 45 | cout << "MB"; 46 | } 47 | if (rem == 6) 48 | { 49 | cout << "UB"; 50 | } 51 | } 52 | else 53 | { 54 | cout << ++n << "SU"; 55 | } 56 | } 57 | 58 | int main() 59 | { 60 | ios_base::sync_with_stdio(false); 61 | cin.tie(NULL); 62 | 63 | #ifndef ONLINE_JUDGE 64 | freopen("input.txt", "r", stdin); 65 | freopen("output.txt", "w", stdout); 66 | #endif 67 | int t = 1; 68 | cin >> t; 69 | while (t--) 70 | { 71 | solve(); 72 | cout << "\n"; 73 | } 74 | return 0; 75 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Journey of Bablu and Dablu/solution.md: -------------------------------------------------------------------------------- 1 | Let remainder be modulo of 8 2 | rem = n % 8 3 | 4 | Check for every individual case of 1 to 8 and match with respective classes. -------------------------------------------------------------------------------- /Prepbytes/Medium/KMP Algorithm/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Medium/KMP Algorithm/a.exe -------------------------------------------------------------------------------- /Prepbytes/Medium/KMP Algorithm/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // static vector pi; 6 | 7 | void COMPUTE_PREFIX(string P, int pi[]) 8 | { 9 | int m = P.length(); 10 | pi[0] = 0; 11 | int k = 0; 12 | for (int q = 1; q < m; q++) 13 | { 14 | while (k > 0 && P[k] != P[1]) 15 | { 16 | k = pi[k]; 17 | } 18 | if (P[k] == P[q]) 19 | { 20 | k = k + 1; 21 | } 22 | pi[q] = k; 23 | } 24 | } 25 | 26 | void KMP_Algo(string T, string P) 27 | { 28 | int n = T.length(); 29 | int m = P.length(); 30 | 31 | int pi[m]; 32 | 33 | COMPUTE_PREFIX(P, pi); 34 | 35 | int q = 0; 36 | for (int i = 0; i < n; i++) 37 | { 38 | while (q > 0 && P[q] != T[i]) 39 | q = pi[q]; 40 | if (P[q] == T[i]) 41 | q = q + 1; 42 | if (q == m) 43 | { 44 | cout << "PAttern matches after " << (i - m + 1) << " index"; 45 | q = pi[q - 1]; 46 | } 47 | } 48 | } 49 | int main() 50 | { 51 | string T; 52 | string P; 53 | 54 | cin >> T >> P; 55 | 56 | KMP_Algo(T, P); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Knight Tour Problem/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Medium/Knight Tour Problem/a.exe -------------------------------------------------------------------------------- /Prepbytes/Medium/Knight Tour Problem/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int isValidMove(int x, int y, int tour[8][8]) 6 | { 7 | return (x >= 0 && x < 8 && y >= 0 && y < 8 && tour[x][y] == -1); 8 | } 9 | 10 | int knightTour(int currX, int currY, int moveCount, int tour[8][8], int x[8], int y[8]) 11 | { 12 | if (moveCount == 8 * 8) 13 | { 14 | return 1; 15 | } 16 | int nextX, nextY; 17 | for (int i = 0; i < 8; i++) 18 | { 19 | nextX = currX + x[i]; 20 | nextY = currY + y[i]; 21 | 22 | if (isValidMove(nextX, nextY, tour)) 23 | { 24 | tour[nextX][nextY] = moveCount; 25 | if (knightTour(nextX, nextY, moveCount + 1, tour, x, y) == 1) 26 | return 1; 27 | else 28 | tour[nextX][nextY] = -1; 29 | } 30 | } 31 | return 0; 32 | } 33 | 34 | int main() 35 | { 36 | int tour[8][8]; 37 | 38 | // Initialising all the cells as non visited 39 | for (int i = 0; i < 8; i++) 40 | { 41 | for (int j = 0; j < 8; j++) 42 | { 43 | tour[i][j] = -1; 44 | } 45 | } 46 | 47 | tour[0][0] = 0; 48 | 49 | int x[8] = {2, 50 | 1, 51 | -1, 52 | -2, 53 | -2, 54 | -1, 55 | 1, 56 | 2}; 57 | int y[8] = {1, 58 | 2, 59 | 2, 60 | 1, 61 | -1, 62 | -2, 63 | -2, 64 | -1}; 65 | if (knightTour(0, 0, 1, tour, x, y) == 0) 66 | { 67 | cout << "Solution doesnt exist"; 68 | } 69 | else 70 | { 71 | for (int i = 0; i < 8; i++) 72 | { 73 | for (int j = 0; j < 8; j++) 74 | { 75 | cout << tour[i][j] << " "; 76 | } 77 | cout << endl; 78 | } 79 | } 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Knight Tour Problem/problem.md: -------------------------------------------------------------------------------- 1 | Given a chess board of 8x8 size, We are to visit every cell once with a Knight (2 1/2 move). 2 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Knight Tour Problem/solution.md: -------------------------------------------------------------------------------- 1 | 1. Generate all possible paths and find the one which satisfies the condition -- take very long. 2 | 2. Backtracking. 3 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Rabin Karp/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Prepbytes/Medium/Rabin Karp/a.exe -------------------------------------------------------------------------------- /Prepbytes/Medium/Rabin Karp/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool charMatch(string t, string p, int s, int m) 4 | { 5 | for (int j = 0; j < m; j++) 6 | { 7 | if (p[j] != t[s + j]) 8 | { 9 | return false; 10 | } 11 | } 12 | 13 | return true; 14 | } 15 | void rabin_karp(string T, string P, int d, int q) 16 | { 17 | int n = T.length(); 18 | int m = P.length(); 19 | 20 | int h = pow((int)d, (int)(m - 1)) + 1; 21 | cout << h; 22 | int p = 0; 23 | int t[n - m + 1]; 24 | t[0] = 0; 25 | for (int i = 0; i < m; i++) 26 | { 27 | p = (d * p + (P[i] - 'a')) % q; 28 | t[0] = (d * t[0] + (T[i] - 'a')) % q; 29 | } 30 | 31 | for (int s = 0; s <= n - m; s++) 32 | { 33 | if (p == t[s]) 34 | { 35 | if (charMatch(T, P, s, m)) 36 | { 37 | cout << "Pattern match after " << s << "shifts\n"; 38 | } 39 | } 40 | if (s < n - m) 41 | { 42 | t[s + 1] = (d * (t[s] - (T[s] - 'a') * h) + (T[s + m] - 'a')) % q; 43 | } 44 | } 45 | } 46 | 47 | int main() 48 | { 49 | string T; 50 | cin >> T; 51 | string P; 52 | cin >> P; 53 | 54 | int d = 26; // radix for 26 chars 55 | int q = 1000000007; // to prevent overflow 56 | 57 | rabin_karp(T, P, d, q); 58 | } 59 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Second Smallest/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | //write your code here 7 | int a, b, c; 8 | cin>>a>>b>>c; 9 | 10 | if((a > b && a < c) || (a > c && a < b)) cout << a; 11 | if ((b > a && b < c) || (b > c && b < a)) cout << b; 12 | if((c > a && c < b) || (c > b && c < a)) cout << c; 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Second Smallest/problem.md: -------------------------------------------------------------------------------- 1 | Second Smallest 2 | You are given 3 | 3 4 | distinct integer numbers 5 | X 6 | , 7 | Y 8 | and 9 | Z 10 | . Task is to print the second smallest number among the three provided numbers. 11 | 12 | Input format 13 | Input contains 14 | 3 15 | distinct integers 16 | X 17 | , 18 | Y 19 | and 20 | Z 21 | . 22 | 23 | Output format 24 | Print the second smallest integer. 25 | 26 | Time Limit 27 | 1 28 | ​secon 29 | 30 | Constraints 31 | 1 32 | <= 33 | X 34 | , 35 | Y 36 | , 37 | Z 38 | <= 39 | 100 40 | 41 | Example 42 | Input 43 | 10 44 | 45 | 42 46 | 47 | 15 48 | 49 | Output 50 | 15 -------------------------------------------------------------------------------- /Prepbytes/Medium/Second Smallest/solution.md: -------------------------------------------------------------------------------- 1 | Check for individual cases here. 2 | i.e. Check if a is greater than b and if a is smaller than c, if that is the case then a is the second smallest. 3 | Perform this iteration for every variable. 4 | -------------------------------------------------------------------------------- /Prepbytes/Medium/Two Stacks In One Array/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class StackArray 6 | { 7 | public: 8 | int *arr; 9 | int size; 10 | int top1, top2; 11 | StackArray(int n) 12 | { 13 | size = n; 14 | arr = new int[n]; 15 | top1 = -1; 16 | top2 = size; 17 | } 18 | void push1(int data) 19 | { 20 | if (top1 < top2 - 1) 21 | { 22 | arr[++top1] = data; 23 | } 24 | else 25 | { 26 | cout << "Stack1 overflow"; 27 | } 28 | } 29 | 30 | void push2(int data) 31 | { 32 | if (top1 < top2 - 1) 33 | { 34 | arr[--top2] = data; 35 | } 36 | else 37 | { 38 | cout << "Stack1 overflow"; 39 | } 40 | } 41 | int pop1() 42 | { 43 | if (top1 > -1) 44 | { 45 | int poppedElement = arr[top1--]; 46 | cout << "Stack1 popped element= " << poppedElement << "\n"; 47 | } 48 | else 49 | { 50 | cout << "Stack1 underflow\n"; 51 | } 52 | } 53 | 54 | int pop2() 55 | { 56 | if (top2 < size) 57 | { 58 | int poppedElement = arr[top2++]; 59 | cout << "Stack2 popped element= " << poppedElement << "\n"; 60 | } 61 | else 62 | { 63 | cout << "Stack2 underflow\n"; 64 | } 65 | } 66 | 67 | void print1() 68 | { 69 | for (int i = top1; i >= 0; i--) 70 | { 71 | cout << arr[i] << " "; 72 | cout << "\n"; 73 | } 74 | 75 | void print1() 76 | { 77 | for (int i = top2; i < size; i++) 78 | { 79 | cout << arr[i] << " "; 80 | } 81 | cout << "\n"; 82 | } 83 | }; 84 | 85 | int main() 86 | { 87 | int n; 88 | cin >> n; 89 | StackArray sa(n); 90 | 91 | int stack1, stack2; 92 | cin >> stack1 >> stack2; 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /Prepbytes/Medium/Two Stacks In One Array/problem.md: -------------------------------------------------------------------------------- 1 | Implement two stacks in an array 2 | 3 | We need to implement two stacks in one single array. 4 | 5 | Operations are: 6 | 7 | 1. push1(), pop1(), print1() for stack1 8 | 2. push2(), pop2(), print2() for stack 2 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

⚡ Coding Interview Preparation ⚡

2 | 3 |
4 | 5 | Stars Badge 6 | Forks Badge 7 | GitHub contributors 8 | License Badge 9 | 10 | 11 |
12 | 13 | My coding solutions on AlgoExpert, LeetCode, FreeCodeCamp, Educative(Coding Paterns), Back To Back SWE, Coding Blocks, CodeChef, GFG, Hackerrank, Hackerearth, InterviewCake, InterviewCamp, Prepbytes and many more. 😅 14 | 15 | **Difficulty Patterns for each module :** 16 | 17 | - 🟢 Easy 18 | - 🟡 Medium 19 | - 🔴 Hard 20 | For some of the modules 21 | - ⚫️ Very Hard 22 | - 🌟 Extremely Hard 23 | 24 | # ⚡ TODO 25 | 26 | 👨‍💻 Convert into a React based web app for personal revision, Inbuilt hack IDE to test cpp code on the go, categorize by Difficulty, Tags and modules. 27 | -------------------------------------------------------------------------------- /Textbook Algorithms/Easy/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Textbook Algorithms/Easy/.keep -------------------------------------------------------------------------------- /Textbook Algorithms/Hard/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Textbook Algorithms/Hard/.keep -------------------------------------------------------------------------------- /Textbook Algorithms/Medium/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manuarora700/data-structures-algorithms-interviews/23a87b62f206da4029f8675aec9b10615d2b9ef2/Textbook Algorithms/Medium/.keep -------------------------------------------------------------------------------- /palindrome-number/README.md: -------------------------------------------------------------------------------- 1 |

9. Palindrome Number

Easy


Given an integer x, return true if x is palindrome integer.

2 | 3 |

An integer is a palindrome when it reads the same backward as forward.

4 | 5 |
    6 |
  • For example, 121 is a palindrome while 123 is not.
  • 7 |
8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: x = 121
13 | Output: true
14 | Explanation: 121 reads as 121 from left to right and from right to left.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: x = -121
20 | Output: false
21 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
22 | 
23 | 24 |

Example 3:

25 | 26 |
Input: x = 10
27 | Output: false
28 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • -231 <= x <= 231 - 1
  • 36 |
37 | 38 |

 

39 | Follow up: Could you solve it without converting the integer to a string?
-------------------------------------------------------------------------------- /palindrome-number/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | string str = to_string(x); 5 | 6 | 7 | string reversed = str; 8 | reverse(reversed.begin(), reversed.end()); 9 | 10 | cout << "str: " << str << endl; 11 | cout << "reversed: " << reversed << endl; 12 | if(str == reversed) { 13 | return true; 14 | } 15 | return false; 16 | } 17 | }; --------------------------------------------------------------------------------