├── .DS_Store ├── package.json ├── JAVA solutions ├── .DS_Store ├── strings │ ├── StringDemo.java │ ├── Patterns.java │ └── LeetcodeString.java ├── linkedlist │ ├── LLMain.java │ ├── CircularLL.java │ └── LeetcodeLL.java ├── heap │ └── HeapQuestions.java ├── stack │ └── LeetcodeStackAndQueue.java ├── subsetsAndSequence │ └── Recursion_II.java ├── hashmap │ └── HashMapLearning.java └── recursion │ └── RecursionLearning.java ├── cheatsheets and more ├── leetcode_cheatsheet.md ├── BigO_Cheatsheet.pdf ├── Resume_cheatsheet.png ├── interview_cheatsheet.pdf ├── Big-O_of_all_sortings_DSA.png ├── Master_the_Interview MIND MAP.pdf └── company.txt ├── Big-O ├── Big-O_of_all_sortings_DSA.png ├── big-o-cheat-sheet-poster.png ├── o(1).js ├── o(a+b).js ├── o(n^2).js └── O(n).js ├── algorithms ├── recursion │ ├── recursion.jpg │ ├── factorial │ │ ├── factorial.gif │ │ └── factorial.js │ ├── simpson-homer-simpson.gif │ ├── fibonacci │ │ ├── fibonacci_recursion.png │ │ └── fibonacci.js │ ├── how_recursion_actually_works.md │ ├── ActiveMarriedHowlermonkey-size_restricted.gif │ ├── recursionEx.js │ ├── decimalToBinary │ │ └── decimal_to_binary.js │ ├── sum_of_consecutive_number │ │ └── sum_of_consecutive_number.js │ ├── linkedList │ │ └── reverseLinkedListRecursively.js │ ├── merge_to_sorted_linkedlist │ │ └── merge_to_sorted_linkedlist.js │ ├── binarySearchUsingRecursion │ │ └── binarySearchUsingRecursion.js │ ├── when_to_use_recursion.txt │ ├── mergeSortUsingRecursion │ │ └── mergeSortUsingRecursion.js │ ├── isPalindrome │ │ └── isPalindrome.js │ ├── sum_using_recursion │ │ └── sum.js │ └── reverseStrWithRecursion │ │ └── reverseStrWithRecursion.js ├── searching │ ├── linear_search.gif │ ├── graph-theory │ │ ├── DFS │ │ │ ├── DFS maze.gif │ │ │ ├── dfs_for_graph.gif │ │ │ ├── Depth-First-Search.gif │ │ │ └── dfs.cpp │ │ ├── graph-theory_mindMapping.png │ │ ├── island_count │ │ │ ├── island_count.png │ │ │ ├── total number of islands using dfs.png │ │ │ └── island_count.js │ │ ├── BFS │ │ │ ├── BFS-Algorithm_for_graph.gif │ │ │ ├── Breadth-First-Search-Algorithm.gif │ │ │ ├── BFS.cpp │ │ │ └── bfs2d.cpp │ │ ├── shortest_path │ │ │ ├── K-shortest path.gif │ │ │ ├── Dijkstra shortest_path.gif │ │ │ └── shortest_path.js │ │ ├── undirected_graph │ │ │ ├── edges to graph.png │ │ │ └── undirected graph.png │ │ ├── Kosaraju_algorithm │ │ │ ├── Kosaraju_algorithm.png │ │ │ ├── Count-of-Connected-Components.png │ │ │ └── count_connected_component │ │ ├── This is how you can show how a graph is created.png │ │ ├── largest_connected_component │ │ │ ├── largetst connected component.gif │ │ │ ├── Strongly-connected-components-of-the-example-graph.png │ │ │ └── largest_connected_component.js │ │ ├── BFS vs DFS │ │ ├── DisjointSetUnion.cpp │ │ ├── minimum_island │ │ │ └── minimum_island.js │ │ ├── hasPath │ │ │ └── hasPath.js │ │ └── Dijkstra.cpp │ ├── binary-search VS sequence-search.gif │ ├── binary-search-tree-sorted-array-animation.gif │ ├── linear_search.js │ └── binary_search.js ├── sorting │ ├── timeComplexity.png │ ├── sorting_mind_map_of_arrays.png │ ├── comparison sort │ │ ├── Divide&Conquer │ │ │ ├── Quicksort.png │ │ │ ├── MergeSortVisualize.png │ │ │ ├── Quick_Sort_Example.png │ │ │ ├── Quicksort-diagram.png │ │ │ ├── Merge-Sort-Algorithm.png │ │ │ ├── quicksort-in-javascript-1.jpg │ │ │ ├── merge_sort.js │ │ │ └── quick_sort.js │ │ ├── bubble_sort.js │ │ ├── selection_sort.js │ │ └── insertion_sort.js │ ├── non-comparison_sort │ │ └── radix+count_sort │ │ │ └── links.txt │ ├── dancingAlgorithms.txt │ ├── visualizeSorting.txt │ └── interview_question_example │ │ └── ex.txt └── Abdul_bari_sir_playlist.md ├── Data structures ├── trees │ ├── binary_tree_properties.png │ ├── this_is_also_a_binary_tree.png │ ├── breadth_first_values │ │ ├── breadth_first_values.gif │ │ └── breadth_first_values.js │ ├── depth_first_value │ │ ├── Depth-First-Tree-Traversal.gif │ │ └── depth_first_values.js │ ├── tree_target_search │ │ └── binary-search-tree-sorted-array-animation.gif │ ├── invert_binary_tree │ │ └── invert_binary_tree.js │ ├── tree_sum │ │ └── tree_sum.js │ ├── max_root_to_leaf_path_sum │ │ └── max_root.js │ └── tree_min_value │ │ └── tree_min_value.js ├── graphs │ ├── graph_data.js │ └── graph.js ├── queues │ ├── queue_arr.js │ └── queue_LL.js ├── array │ ├── array.js │ └── problems │ │ └── finders_keepers.js ├── stacks │ ├── stacks_arr.js │ └── stack_LL.js └── linkedlist │ ├── Trie.cpp │ └── LinkedList.cpp ├── .gitignore ├── questions ├── dynamic_programming │ ├── dynamic_programming_matrox.png │ ├── DynamicProgramming1-660x372.jpg │ ├── Tabulation-vs-Memoization-1.png │ ├── dp.txt │ ├── Memoization │ │ ├── Tips & Tricks.md │ │ ├── gridTraveler.js │ │ ├── fibSeries.js │ │ ├── divisor-game.cpp │ │ ├── word-break.cpp │ │ ├── unique-paths.cpp │ │ ├── house-robber.cpp │ │ └── delete-earn.cpp │ ├── Tabular │ │ ├── counting-bits.cpp │ │ ├── max-subarray.cpp │ │ ├── lis.cpp │ │ ├── climbing-stairs.cpp │ │ ├── maximal-square.cpp │ │ ├── palindromic-ss.cpp │ │ ├── subarray-sum.cpp │ │ ├── mlrs.cpp │ │ ├── decode-ways.cpp │ │ └── coin-change.cpp │ └── dp.js ├── leetcode │ ├── leetcode371.js │ ├── leetcode50.js │ ├── leetcode34.js │ ├── leetcode38.js │ ├── leetcode27.js │ ├── leetcode2441.js │ ├── leetcode2399.js │ ├── leetcode9.js │ ├── leetcode14.js │ ├── leetcode26.js │ ├── leetcode198.js │ ├── leetcode2486.js │ ├── leetcode12.js │ ├── leetcode4.js │ ├── leetcode2395.js │ ├── leetcode13.js │ ├── leetcode22.js │ ├── leetcode53.js │ ├── leetcode844.js │ ├── leetcode31.js │ ├── leetcode20.js │ ├── leetcode41.js │ ├── leetcode541.js │ ├── leetcode35.js │ ├── leetcode48.js │ ├── leetcode226.js │ ├── leetcode28.js │ ├── leetcode39.js │ ├── leetcode10.js │ ├── leetcode46.js │ ├── leetcode49.js │ ├── leetcode21.js │ ├── leetcode2465.js │ ├── leetcode917.js │ ├── leetcode3.js │ ├── leetcode17.js │ ├── leetcode171.js │ ├── leetcode5.js │ ├── leetcode925.js │ ├── leetcode29.js │ ├── leetcode116.js │ ├── leetcode105.js │ ├── leetcode1616.js │ ├── leetcode42.js │ ├── leetcode7.js │ ├── leetcode8.js │ ├── leetcode131.js │ ├── leetcode6.js │ ├── leetcode345.js │ ├── leetcode997.js │ ├── leetcode43.js │ ├── leetcode347.js │ ├── leetcode33.js │ ├── leetcode16.js │ ├── leetcode130.js │ ├── leetcode44.js │ ├── leetcode103.js │ ├── leetcode19.js │ ├── leetcode11.js │ ├── leetcode1.js │ ├── leetcode23.js │ ├── leetcode15.js │ ├── leetcode73.js │ ├── leetcode36.js │ ├── leetcode79.js │ ├── leetcode30.js │ ├── leetcode149.js │ ├── leetcode2.js │ ├── leetcode37.js │ ├── leetcode2367.js │ └── leetcode279.js ├── FenwikTree.cpp ├── revStr.js ├── reverseLinkedList.js ├── two_pointers │ ├── max-product-subarray.cpp │ ├── sort-colors.cpp │ └── partition-labels.cpp ├── removeDuplicatesFromList.js ├── firstReccuringChar.js ├── mergeSortedArray.js ├── queue_using_stack.js └── containsCommonItem.js └── heap ├── top-k-freq-elem.cpp ├── merge-k-sorted-lists.cpp └── data-stream-median.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/.DS_Store -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "prompt-sync": "^4.2.0" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /JAVA solutions/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/JAVA solutions/.DS_Store -------------------------------------------------------------------------------- /cheatsheets and more/leetcode_cheatsheet.md: -------------------------------------------------------------------------------- 1 | - [@Pirate King](https://www.piratekingdom.com/leetcode/cheat-sheet) -------------------------------------------------------------------------------- /Big-O/Big-O_of_all_sortings_DSA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Big-O/Big-O_of_all_sortings_DSA.png -------------------------------------------------------------------------------- /Big-O/big-o-cheat-sheet-poster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Big-O/big-o-cheat-sheet-poster.png -------------------------------------------------------------------------------- /algorithms/recursion/recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/recursion/recursion.jpg -------------------------------------------------------------------------------- /algorithms/searching/linear_search.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/linear_search.gif -------------------------------------------------------------------------------- /algorithms/sorting/timeComplexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/timeComplexity.png -------------------------------------------------------------------------------- /cheatsheets and more/BigO_Cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/cheatsheets and more/BigO_Cheatsheet.pdf -------------------------------------------------------------------------------- /cheatsheets and more/Resume_cheatsheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/cheatsheets and more/Resume_cheatsheet.png -------------------------------------------------------------------------------- /algorithms/recursion/factorial/factorial.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/recursion/factorial/factorial.gif -------------------------------------------------------------------------------- /cheatsheets and more/interview_cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/cheatsheets and more/interview_cheatsheet.pdf -------------------------------------------------------------------------------- /Data structures/trees/binary_tree_properties.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Data structures/trees/binary_tree_properties.png -------------------------------------------------------------------------------- /algorithms/recursion/simpson-homer-simpson.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/recursion/simpson-homer-simpson.gif -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/DFS/DFS maze.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/DFS/DFS maze.gif -------------------------------------------------------------------------------- /algorithms/sorting/sorting_mind_map_of_arrays.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/sorting_mind_map_of_arrays.png -------------------------------------------------------------------------------- /cheatsheets and more/Big-O_of_all_sortings_DSA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/cheatsheets and more/Big-O_of_all_sortings_DSA.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | node_modules 3 | test.js 4 | package.json 5 | package-lock.json 6 | test.py 7 | *.class 8 | test.java 9 | .DS_Store 10 | -------------------------------------------------------------------------------- /Data structures/trees/this_is_also_a_binary_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Data structures/trees/this_is_also_a_binary_tree.png -------------------------------------------------------------------------------- /algorithms/recursion/fibonacci/fibonacci_recursion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/recursion/fibonacci/fibonacci_recursion.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/DFS/dfs_for_graph.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/DFS/dfs_for_graph.gif -------------------------------------------------------------------------------- /cheatsheets and more/Master_the_Interview MIND MAP.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/cheatsheets and more/Master_the_Interview MIND MAP.pdf -------------------------------------------------------------------------------- /algorithms/searching/binary-search VS sequence-search.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/binary-search VS sequence-search.gif -------------------------------------------------------------------------------- /algorithms/recursion/how_recursion_actually_works.md: -------------------------------------------------------------------------------- 1 | [@freeCodeCamp](https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/) -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/DFS/Depth-First-Search.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/DFS/Depth-First-Search.gif -------------------------------------------------------------------------------- /questions/dynamic_programming/dynamic_programming_matrox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/questions/dynamic_programming/dynamic_programming_matrox.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/graph-theory_mindMapping.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/graph-theory_mindMapping.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/island_count/island_count.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/island_count/island_count.png -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/Quicksort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/Quicksort.png -------------------------------------------------------------------------------- /questions/dynamic_programming/DynamicProgramming1-660x372.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/questions/dynamic_programming/DynamicProgramming1-660x372.jpg -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabulation-vs-Memoization-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/questions/dynamic_programming/Tabulation-vs-Memoization-1.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/BFS/BFS-Algorithm_for_graph.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/BFS/BFS-Algorithm_for_graph.gif -------------------------------------------------------------------------------- /Data structures/trees/breadth_first_values/breadth_first_values.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Data structures/trees/breadth_first_values/breadth_first_values.gif -------------------------------------------------------------------------------- /algorithms/recursion/ActiveMarriedHowlermonkey-size_restricted.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/recursion/ActiveMarriedHowlermonkey-size_restricted.gif -------------------------------------------------------------------------------- /algorithms/searching/binary-search-tree-sorted-array-animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/binary-search-tree-sorted-array-animation.gif -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/shortest_path/K-shortest path.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/shortest_path/K-shortest path.gif -------------------------------------------------------------------------------- /Data structures/trees/depth_first_value/Depth-First-Tree-Traversal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Data structures/trees/depth_first_value/Depth-First-Tree-Traversal.gif -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/undirected_graph/edges to graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/undirected_graph/edges to graph.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/BFS/Breadth-First-Search-Algorithm.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/BFS/Breadth-First-Search-Algorithm.gif -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/undirected_graph/undirected graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/undirected_graph/undirected graph.png -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/MergeSortVisualize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/MergeSortVisualize.png -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/Quick_Sort_Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/Quick_Sort_Example.png -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/Quicksort-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/Quicksort-diagram.png -------------------------------------------------------------------------------- /algorithms/sorting/non-comparison_sort/radix+count_sort/links.txt: -------------------------------------------------------------------------------- 1 | radix sort 2 | - https://www.geeksforgeeks.org/radix-sort/ 3 | 4 | counting sort 5 | - https://www.geeksforgeeks.org/counting-sort/ -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/Kosaraju_algorithm/Kosaraju_algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/Kosaraju_algorithm/Kosaraju_algorithm.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/shortest_path/Dijkstra shortest_path.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/shortest_path/Dijkstra shortest_path.gif -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/Merge-Sort-Algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/Merge-Sort-Algorithm.png -------------------------------------------------------------------------------- /algorithms/sorting/dancingAlgorithms.txt: -------------------------------------------------------------------------------- 1 | Go to this link and see all the AlgoRythmics problems like N-queens 2 | 3 | https://www.youtube.com/user/AlgoRythmics/videos 4 | 5 | watch at 2x speed to enjoy more -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/quicksort-in-javascript-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/sorting/comparison sort/Divide&Conquer/quicksort-in-javascript-1.jpg -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/This is how you can show how a graph is created.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/This is how you can show how a graph is created.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/island_count/total number of islands using dfs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/island_count/total number of islands using dfs.png -------------------------------------------------------------------------------- /Data structures/trees/tree_target_search/binary-search-tree-sorted-array-animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/Data structures/trees/tree_target_search/binary-search-tree-sorted-array-animation.gif -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/Kosaraju_algorithm/Count-of-Connected-Components.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/Kosaraju_algorithm/Count-of-Connected-Components.png -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/largest_connected_component/largetst connected component.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/largest_connected_component/largetst connected component.gif -------------------------------------------------------------------------------- /Big-O/o(1).js: -------------------------------------------------------------------------------- 1 | const box = new Array(100000).fill('box'); 2 | 3 | const compressBox = arr => { 4 | console.log(arr[0]); 5 | }; 6 | 7 | /* ** as we are finding only 1 thing the time complexity becomes 8 | O(1) or constant time complexity */ -------------------------------------------------------------------------------- /algorithms/sorting/visualizeSorting.txt: -------------------------------------------------------------------------------- 1 | - https://www.toptal.com/developers/sorting-algorithms 2 | 3 | stability of sorting algorithms 4 | - https://stackoverflow.com/questions/1517793/what-is-stability-in-sorting-algorithms-and-why-is-it-important 5 | -------------------------------------------------------------------------------- /questions/leetcode/leetcode371.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} a 3 | * @param {number} b 4 | * @return {number} 5 | */ 6 | var getSum = function (a, b) { 7 | if (b === 0) { 8 | return a; 9 | } 10 | return getSum(a ^ b, (a & b) << 1); 11 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode50.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/powx-n/ 2 | 3 | /** 4 | * @param {number} x 5 | * @param {number} n 6 | * @return {number} 7 | */ 8 | var myPow = function (x, n) { 9 | return Math.pow(x, n); 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Big-O/o(a+b).js: -------------------------------------------------------------------------------- 1 | const findBox = (box1, box2) => { 2 | box1.forEach((box) => { 3 | console.log(box); // O(a) 4 | }); 5 | 6 | box2.forEach((box) => { 7 | console.log(box); // O(b) 8 | }); 9 | }; 10 | 11 | // T(N) = O(a + b) -------------------------------------------------------------------------------- /algorithms/Abdul_bari_sir_playlist.md: -------------------------------------------------------------------------------- 1 | # The one & only Youtube Playlist of algorithm 2 | 3 | * [Abdul Bari](https://www.youtube.com/playlist?list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O) 4 | * [CodeEvolution](https://www.youtube.com/playlist?list=PLC3y8-rFHvwiRYB4-HHKHblh3_bQNJTMa) -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/largest_connected_component/Strongly-connected-components-of-the-example-graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saif64/Interview-prep/HEAD/algorithms/searching/graph-theory/largest_connected_component/Strongly-connected-components-of-the-example-graph.png -------------------------------------------------------------------------------- /algorithms/recursion/recursionEx.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | let count = 0; 4 | 5 | const inception = () => { 6 | console.log(count); 7 | if (count > 3) { 8 | return 'done'; 9 | } 10 | count++; 11 | return inception(); // the function calls itself untill it completes the if task 12 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/dp.txt: -------------------------------------------------------------------------------- 1 | DYnamic Programming is mainly an optimization of Programming 2 | 3 | It is very difficult to understand and very vast topic.. follow the freeCodeCamp 4 | video to learn and understand better https://www.youtube.com/watch?v=oBt53YbR9Kk&list=PL3dw3cTyGuIMtUdjhm4wwa9mQvduj_rSw&index=4 -------------------------------------------------------------------------------- /algorithms/recursion/decimalToBinary/decimal_to_binary.js: -------------------------------------------------------------------------------- 1 | const IntToBinary = (num, result = "") => { 2 | if (num === 0) return result; 3 | 4 | if (num % 2 === 0) result = "0" + result; 5 | else result = "1" + result; 6 | return IntToBinary(Math.floor(num / 2), result); 7 | }; 8 | 9 | console.log(IntToBinary(15)); -------------------------------------------------------------------------------- /algorithms/recursion/sum_of_consecutive_number/sum_of_consecutive_number.js: -------------------------------------------------------------------------------- 1 | const recursiveSum = (num) => { 2 | if (num <= 1) return num; 3 | 4 | return num + recursiveSum(num - 1); 5 | }; 6 | 7 | 8 | 9 | console.log(recursiveSum(10)); 10 | // 10 + 9 11 | // 9 + 8 12 | // 8 + 7 13 | // 7 + 6 14 | // 6 + 5 15 | //..... 1 + 0 -------------------------------------------------------------------------------- /Big-O/o(n^2).js: -------------------------------------------------------------------------------- 1 | const boxes = ['a', 'b', 'c', 'd', 'e']; 2 | function logAllPairsOfArray(array) { 3 | for (let i = 0; i < array.length; i + ) { 4 | for (let j = 0; j < array.length; j++) { 5 | console.log(array[i], array[j]); 6 | } 7 | } 8 | } 9 | 10 | logAllPairsOfArray(boxes); 11 | 12 | // O(n*n) = O(n^2 ) -------------------------------------------------------------------------------- /questions/leetcode/leetcode34.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} target 6 | * @return {number[]} 7 | */ 8 | var searchRange = function (nums, target) { 9 | return [nums.indexOf(target), nums.lastIndexOf(target)]; 10 | }; -------------------------------------------------------------------------------- /questions/FenwikTree.cpp: -------------------------------------------------------------------------------- 1 | vector tree; 2 | void update(int idx,int n,int x) 3 | { 4 | while(idx<=n) 5 | { 6 | tree[idx]+=x; 7 | idx+= idx&(-idx); 8 | } 9 | } 10 | int query(int idx){ 11 | int sum=0; 12 | while(idx>0) 13 | { 14 | sum+=tree[idx]; 15 | idx-=idx&(-idx); 16 | } 17 | return sum; 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/searching/linear_search.js: -------------------------------------------------------------------------------- 1 | var beasts = ['Centaur', 'Godzilla', 'Mosura', 'Minotaur', 'Hydra', 'Nessie']; 2 | 3 | beasts.indexOf('Godzilla'); 4 | 5 | beasts.findIndex(function (item) { 6 | return item === 'Godzilla'; 7 | }); 8 | 9 | beasts.find(function (item) { 10 | return item === 'Godzilla'; 11 | }); 12 | 13 | beasts.includes('Godzilla'); -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/Tips & Tricks.md: -------------------------------------------------------------------------------- 1 | # Make it Work 2 | - Think of a brute force solution first of all 3 | - Visualize the problem as a tree 4 | - implement the tree using recursion 5 | - test it 6 | # Make it efficient 7 | - add a memo object 8 | - add a base case to return memo values 9 | - store return values into the memo -------------------------------------------------------------------------------- /questions/leetcode/leetcode38.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/count-and-say/ 2 | 3 | /** 4 | * @param {number} n 5 | * @return {string} 6 | */ 7 | var countAndSay = function (n) { 8 | if (n === 1) return '1'; 9 | 10 | return countAndSay(n - 1) 11 | .match(/1+|2+|3+/g) 12 | .reduce((acc, nums) => acc += `${ nums.length }${ nums[0] }`, ''); 13 | }; -------------------------------------------------------------------------------- /cheatsheets and more/company.txt: -------------------------------------------------------------------------------- 1 | Appscode 2 | Konasl 3 | Enosis 4 | Bjit 5 | Brac it 6 | Dynamic solutions 7 | Well dev 8 | Reli source 9 | Selise 10 | We dev 11 | Orbitax 12 | Cefalo 13 | Reive 14 | Craftsman 15 | Benri ltd 16 | Inventive apps 17 | Debug station 18 | Kaz 19 | Southtech 20 | Grab 21 | Tigerit 22 | Therap 23 | Newscreed 24 | Kit games 25 | 52 digital -------------------------------------------------------------------------------- /questions/revStr.js: -------------------------------------------------------------------------------- 1 | // input: 'My name is Saif' 2 | // output: 'fiaS si eman yM' 3 | 4 | function reverse(str) { 5 | // check input first 6 | if (str.length < 2 || !str || typeof str !== 'string') return; 7 | 8 | return str.split('').reverse().join(''); 9 | } 10 | 11 | //new ES6 way modern way 12 | const revStr = str => [...str].reverse().join(''); 13 | 14 | console.log(revStr('My name is Saif')); -------------------------------------------------------------------------------- /questions/leetcode/leetcode27.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-element/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} val 6 | * @return {number} 7 | */ 8 | var removeElement = function (nums, val) { 9 | for (let i = nums.length - 1; i >= 0; i--) { 10 | if (nums[i] === val) { 11 | nums.splice(i, 1); 12 | } 13 | } 14 | 15 | return nums.length; 16 | }; -------------------------------------------------------------------------------- /algorithms/recursion/linkedList/reverseLinkedListRecursively.js: -------------------------------------------------------------------------------- 1 | // class Node { 2 | // constructor (value) { 3 | // this.value = value; 4 | // this.next = null; 5 | // } 6 | // } 7 | 8 | const reverList = (head) => { 9 | if (head === null || head.next === null) return head; 10 | 11 | let node = reverList(head.next); 12 | head.next.next = head; 13 | head.next = null; 14 | return node; 15 | }; -------------------------------------------------------------------------------- /algorithms/recursion/merge_to_sorted_linkedlist/merge_to_sorted_linkedlist.js: -------------------------------------------------------------------------------- 1 | /* 2 | @parm a is node 3 | @parm b is node 4 | 5 | */ 6 | 7 | const merge = (a, b) => { 8 | if (a === null) return b; 9 | if (b === null) return a; 10 | 11 | if (a.data < b.data) { 12 | a.next = merge(a.next, b); 13 | return a; 14 | } else { 15 | b.next = merge(a, b.next); 16 | return b; 17 | } 18 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2441.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/description/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var findMaxK = function (nums) { 8 | nums.sort((a, b) => a - b); 9 | for (let i = nums.length - 1; i >= 0; i--) { 10 | if (nums.includes(-nums[i])) { 11 | return nums[i]; 12 | } 13 | } 14 | return -1; 15 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2399.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/check-distances-between-same-letters/description/ 2 | 3 | var checkDistances = function (s, distance) { 4 | let arr = Array(26).fill(0); 5 | for (let i = 0; i < s.length; i++) { 6 | if (arr[s.charCodeAt(i) - 97] != 0 && i - arr[s.charCodeAt(i) - 97] != distance[s.charCodeAt(i) - 97]) 7 | return false; 8 | arr[s.charCodeAt(i) - 97] = i + 1; 9 | } 10 | return true; 11 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode9.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-number/ 2 | 3 | /** 4 | * @param {number} x 5 | * @return {boolean} 6 | */ 7 | var isPalindrome = function (x) { 8 | let num = x.toString(); 9 | let rev = ""; 10 | 11 | for (let i = num.length - 1; i >= 0; i--) { 12 | rev += num[i]; 13 | } 14 | if (num == rev) { 15 | return true; 16 | } 17 | else { 18 | return false; 19 | } 20 | }; -------------------------------------------------------------------------------- /Data structures/graphs/graph_data.js: -------------------------------------------------------------------------------- 1 | /* How to represent a graph data */ 2 | 3 | // Edge List 4 | const graph = [ 5 | [0, 2], 6 | [2, 3], 7 | [2, 1], 8 | [1, 3] 9 | ]; 10 | 11 | // Aajacent List 12 | const adjGraph = [ 13 | [2], 14 | [2, 3], 15 | [0, 1, 3], 16 | [1, 2] 17 | ]; 18 | 19 | // Adjacent Matrix 20 | const matGraph = [ 21 | [0, 0, 1, 0], 22 | [0, 0, 1, 1,], 23 | [1, 1, 0, 1], 24 | [0, 1, 1, 0] 25 | 26 | ]; -------------------------------------------------------------------------------- /questions/leetcode/leetcode14.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-common-prefix/description/ 2 | 3 | /** 4 | * @param {string[]} strs 5 | * @return {string} 6 | */ 7 | var longestCommonPrefix = function (strs) { 8 | if (strs === undefined || strs.length === 0) { return ''; } 9 | 10 | return strs.reduce((prev, next) => { 11 | let i = 0; 12 | while (prev[i] && next[i] && prev[i] === next[i]) i++; 13 | return prev.slice(0, i); 14 | }); 15 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode26.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var removeDuplicates = function (nums) { 8 | if (nums.length == 0) return 0; 9 | 10 | let i = 0; 11 | for (let j = 1; j < nums.length; j++) { 12 | if (nums[j] !== nums[i]) { 13 | i++; 14 | nums[i] = nums[j]; 15 | } 16 | } 17 | 18 | return i + 1; 19 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode198.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | // O(n) time | O(1) space 6 | var rob = function (nums) { 7 | if (nums === null || nums.length === 0) { 8 | return 0; 9 | } 10 | let dp = new Array(nums.length); 11 | dp[0] = nums[0]; 12 | dp[1] = Math.max(nums[0], nums[1]); 13 | for (let i = 2; i < nums.length; i++) { 14 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 15 | } 16 | return dp[nums.length - 1]; 17 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2486.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/append-characters-to-string-to-make-subsequence/description/ 2 | 3 | /** 4 | * @param {string} s 5 | * @param {string} t 6 | * @return {number} 7 | */ 8 | var appendCharacters = function (s, t) { 9 | let i = 0; 10 | let j = 0; 11 | 12 | while (i < s.length && j < t.length) { 13 | if (s[i] === t[j]) { 14 | j++; 15 | } 16 | i++; 17 | } 18 | 19 | return t.length - j; 20 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode12.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/integer-to-roman/ 2 | 3 | /** 4 | * @param {number} num 5 | * @return {string} 6 | */ 7 | var intToRoman = function (N) { 8 | const val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; 9 | const rom = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; 10 | 11 | let ans = ""; 12 | for (let i = 0; N; i++) 13 | while (N >= val[i]) ans += rom[i], N -= val[i]; 14 | return ans; 15 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode4.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | 3 | /** 4 | * @param {number[]} nums1 5 | * @param {number[]} nums2 6 | * @return {number} 7 | */ 8 | var findMedianSortedArrays = function (nums1, nums2) { 9 | const nums = [...nums1, ...nums2].sort((a, b) => a - b); 10 | const len = nums.length; 11 | const mid = Math.floor(len / 2); 12 | if (len % 2 == 1) return nums[mid]; 13 | return (nums[mid] + nums[mid - 1]) / 2; 14 | }; 15 | 16 | -------------------------------------------------------------------------------- /algorithms/recursion/binarySearchUsingRecursion/binarySearchUsingRecursion.js: -------------------------------------------------------------------------------- 1 | const binarySearchRecursively = (arr, left, right, key) => { 2 | arr.sort((a, b) => a - b); 3 | if (left > right) return -1; 4 | 5 | let mid = (left + right) / 2; 6 | 7 | if (key === arr[mid]) return mid; 8 | 9 | if (key < arr[mid]) { 10 | return binarySearchRecursively(arr, left, mid - 1, key); // goes left 11 | } 12 | return binarySearchRecursively(arr, mid + 1, right, key); // goes right 13 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2395.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-subarrays-with-equal-sum/description/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {boolean} 6 | */ 7 | var findSubarrays = function (nums) { 8 | let sums = new Set(); 9 | 10 | for (let i = 0; i < nums.length - 1; i++) { 11 | if (sums.has(nums[i] + nums[i + 1])) { 12 | return true; 13 | } else { 14 | sums.add(nums[i] + nums[i + 1]); 15 | } 16 | } 17 | 18 | return false; 19 | }; -------------------------------------------------------------------------------- /JAVA solutions/strings/StringDemo.java: -------------------------------------------------------------------------------- 1 | package leetcode.strings; 2 | 3 | public class StringDemo { 4 | public static void main(String[] args) { 5 | String a = "abaa"; 6 | 7 | System.out.println(isPalindrome(a)); 8 | } 9 | 10 | static boolean isPalindrome(String s) { 11 | StringBuilder sb = new StringBuilder(); 12 | 13 | for (int i = 0; i < s.length(); i++) { 14 | sb.append(s.charAt(i)); 15 | } 16 | 17 | return sb.reverse().toString().equals(s); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /questions/leetcode/leetcode13.js: -------------------------------------------------------------------------------- 1 | // This is Important 2 | 3 | // https://leetcode.com/problems/roman-to-integer 4 | 5 | /** 6 | * @param {string} s 7 | * @return {number} 8 | */ 9 | var romanToInt = function (s) { 10 | const roman = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; 11 | let sum = 0; 12 | 13 | s.split('').forEach(function (num, i) { 14 | if (roman[num] < roman[s[i + 1]]) return sum -= roman[num]; 15 | else return sum += roman[num]; 16 | }); 17 | return sum; 18 | }; -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/BFS vs DFS: -------------------------------------------------------------------------------- 1 | //If you know a solution is not far from the root of the tree: 2 | BFS 3 | 4 | //If the tree is very deep and solutions are rare, 5 | BFS (DFS will take long time. ) 6 | 7 | //If the tree is very wide: 8 | DFS (BFS will need too much memory) 9 | 10 | //If solutions are frequent but located deep in the tree 11 | DFS 12 | 13 | //determining whether a path exists between two nodes 14 | DFS 15 | 16 | //Finding the shortest path 17 | BFS 18 | 19 | https://visualgo.net/en/dfsbfs?slide=1 -------------------------------------------------------------------------------- /questions/leetcode/leetcode22.js: -------------------------------------------------------------------------------- 1 | // important 2 | // https://leetcode.com/problems/generate-parentheses/ 3 | 4 | /** 5 | * @param {number} n 6 | * @return {string[]} 7 | */ 8 | const generateParenthesis = function (n, str = '', left = 0, right = 0) { 9 | let arr = []; 10 | if (str.length == n * 2) return str; 11 | if (left < n) arr = arr.concat(generateParenthesis(n, str + '(', left + 1, right)); 12 | if (right < n && right < left) arr = arr.concat(generateParenthesis(n, str + ')', left, right + 1)); 13 | return arr; 14 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode53.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray/description/?envType=study-plan&id=data-structure-i 2 | // important question 3 | 4 | var maxSubArray = function (nums) { 5 | var maxHere = nums[0]; 6 | var maxSoFar = nums[0]; 7 | 8 | for (var i = 1; i < nums.length; i++) { 9 | maxHere = Math.max(nums[i], maxHere + nums[i]); 10 | maxSoFar = Math.max(maxHere, maxSoFar); 11 | } 12 | 13 | return maxSoFar; 14 | }; 15 | 16 | console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); -------------------------------------------------------------------------------- /questions/leetcode/leetcode844.js: -------------------------------------------------------------------------------- 1 | const backspaceCompare = (S, T) => { 2 | return edit(S) === edit(T); 3 | 4 | function edit(str) { 5 | let result = ''; 6 | let backspaces = 0; 7 | 8 | for (let i = str.length - 1; i >= 0; i -= 1) { 9 | if (str[i] === '#') { 10 | backspaces += 1; 11 | } else if (backspaces > 0) { 12 | backspaces -= 1; 13 | } else { 14 | result = str[i] + result; 15 | } 16 | } 17 | 18 | return result; 19 | } 20 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode31.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/next-permutation/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {void} Do not return anything, modify nums in-place instead. 6 | */ 7 | var nextPermutation = function (N) { 8 | const swap = (a, b) => [N[a], N[b]] = [N[b], N[a]]; 9 | let len = N.length - 1, i, j; 10 | for (i = len - 1; N[i] >= N[i + 1];) i--; 11 | for (let k = i + 1; len > k; k++, len--) swap(k, len); 12 | if (~i) { 13 | for (j = i + 1; N[i] >= N[j];) j++; 14 | swap(i, j); 15 | } 16 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode20.js: -------------------------------------------------------------------------------- 1 | // very important 2 | // https://leetcode.com/problems/valid-parentheses/ 3 | 4 | /** 5 | * @param {string} s 6 | * @return {boolean} 7 | */ 8 | var isValid = function (s) { 9 | let brac = { 10 | '(': ')', 11 | '{': '}', 12 | '[': ']' 13 | }; 14 | let stack = []; 15 | 16 | for (let i of s) { 17 | if (brac[i]) { 18 | stack.push(brac[i]); 19 | } else { 20 | if (stack.pop() !== i) return false; 21 | } 22 | } 23 | return !stack.length; 24 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode41.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var firstMissingPositive = function (nums) { 6 | var i = 0; 7 | 8 | if (!nums.includes(1)) 9 | return 1; 10 | 11 | nums.sort((a, b) => a - b); 12 | while (i < nums.length) { 13 | if (nums[i] < 0 || nums[i] + 1 > nums[i + 1]) { 14 | i++; 15 | continue; 16 | } 17 | if (nums[i + 1] && nums[i] + 1 != nums[i + 1]) { 18 | return nums[i] + 1; 19 | } 20 | i++; 21 | } 22 | 23 | return nums[i - 1] + 1; 24 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode541.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string-ii/description/ 2 | 3 | /** 4 | * @param {string} s 5 | * @param {number} k 6 | * @return {string} 7 | */ 8 | var reverseStr = function (str, k) { 9 | str = str.split(''); 10 | for (let i = 0; i < str.length; i += 2 * k) { 11 | let start = i; 12 | let end = start + k - 1; 13 | if (end > str.length - 1) end = str.length - 1; 14 | 15 | while (start < end) { 16 | [[str[start++]], [str[end--]]] = [[str[end]], [str[start]]]; 17 | } 18 | } 19 | return str.join(''); 20 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/counting-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 3 | 4 | Example 1: 5 | Input: n = 2 6 | Output: [0,1,1] 7 | Explanation: 8 | 0 --> 0 9 | 1 --> 1 10 | 2 --> 10 11 | */ 12 | 13 | // Leetcode 338 14 | class Solution { 15 | public: 16 | vector countBits(int n) { 17 | vector ans(n+1); 18 | ans[0] = 0; 19 | for(int i=1;i<=n;i++) { 20 | ans[i] = ans[i/2] + i%2; 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode35.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-insert-position/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} target 6 | * @return {number} 7 | */ 8 | var searchInsert = function (nums, target) { 9 | let start = 0; 10 | let end = nums.length - 1; 11 | 12 | while (start < end) { 13 | let mid = Math.floor((start + end) / 2); 14 | if (nums[mid] === target) return mid; 15 | nums[mid] > target ? end = mid : start = mid + 1; 16 | } 17 | if (start === end) { 18 | return target <= nums[start] ? start : start + 1; 19 | } 20 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode48.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/rotate-image/ 2 | 3 | /** 4 | * @param {number[][]} matrix 5 | * @return {void} Do not return anything, modify matrix in-place instead. 6 | */ 7 | var rotate = function (matrix) { 8 | for (let i = 0; i < matrix.length; i++) { 9 | for (let j = i; j < matrix[0].length; j++) { 10 | let temp = matrix[i][j]; 11 | matrix[i][j] = matrix[j][i]; 12 | matrix[j][i] = temp; 13 | } 14 | } 15 | for (let m of matrix) { 16 | let first = matrix.shift(); 17 | matrix.push(first.reverse()); 18 | } 19 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode226.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/invert-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * function TreeNode(val, left, right) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.left = (left===undefined ? null : left) 8 | * this.right = (right===undefined ? null : right) 9 | * } 10 | */ 11 | /** 12 | * @param {TreeNode} root 13 | * @return {TreeNode} 14 | */ 15 | var invertTree = function (root) { 16 | if (root) { 17 | [root.left, root.right] = [invertTree(root.right), invertTree(root.left)]; 18 | } 19 | return root; 20 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode28.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ 2 | 3 | 4 | /** 5 | * @param {string} haystack 6 | * @param {string} needle 7 | * @return {number} 8 | */ 9 | var strStr = function (haystack, needle) { 10 | if (!needle) return 0; 11 | let idx = 0; 12 | for (let i = 0; i < haystack.length; i++) { 13 | if (haystack[i] != needle[idx]) { 14 | i = i - idx; 15 | idx = 0; 16 | } else { 17 | if (idx == needle.length - 1) return i - idx; 18 | idx++; 19 | } 20 | } 21 | return -1; 22 | }; -------------------------------------------------------------------------------- /questions/reverseLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {ListNode} 11 | */ 12 | var reverseList = function (head) { 13 | if (!head) return head; 14 | 15 | let node = head; 16 | let prev = null; 17 | 18 | while (node) { 19 | let tempNode = node.next; 20 | node.next = prev; 21 | prev = node; 22 | node = tempNode; 23 | } 24 | 25 | return prev; 26 | }; -------------------------------------------------------------------------------- /Data structures/trees/invert_binary_tree/invert_binary_tree.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/invert-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * function TreeNode(val, left, right) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.left = (left===undefined ? null : left) 8 | * this.right = (right===undefined ? null : right) 9 | * } 10 | */ 11 | /** 12 | * @param {TreeNode} root 13 | * @return {TreeNode} 14 | */ 15 | var invertTree = function (root) { 16 | if (root) { 17 | [root.left, root.right] = [invertTree(root.right), invertTree(root.left)]; 18 | } 19 | return root; 20 | }; -------------------------------------------------------------------------------- /algorithms/recursion/when_to_use_recursion.txt: -------------------------------------------------------------------------------- 1 | PROS | CONS 2 | ----------------|------------------- 3 | DRY | 4 | More Readable | Large Stack 5 | | 6 | | 7 | | 8 | 9 | 10 | Every time you are using a tree or converting Something into a tree 11 | consider using recursion 12 | 1. Divided into a number of subproblems that are smaller instances of the same problem 13 | 2. Each instances of the subproblem is identical in nature 14 | 3. The solutions of each subproblem can be combined to solve problem at hand 15 | 16 | Divide And Conqure recursion -------------------------------------------------------------------------------- /questions/leetcode/leetcode39.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} candidates 3 | * @param {number} target 4 | * @return {number[][]} 5 | */ 6 | function combinationSum(candidates, target) { 7 | var buffer = []; 8 | var result = []; 9 | search(0, target); 10 | return result; 11 | 12 | function search(startIdx, target) { 13 | if (target === 0) return result.push(buffer.slice()); 14 | if (target < 0) return; 15 | if (startIdx === candidates.length) return; 16 | buffer.push(candidates[startIdx]); 17 | search(startIdx, target - candidates[startIdx]); 18 | buffer.pop(); 19 | search(startIdx + 1, target); 20 | } 21 | } -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/bubble_sort.js: -------------------------------------------------------------------------------- 1 | const arr = [2, 3, 1, 4, 7, 5]; 2 | 3 | 4 | // TC = O(n^2) 5 | // SC = O(n) 6 | const bubbleSort = (arr) => { 7 | for (let i = 0; i < arr.length; i++) { 8 | for (let j = 0; j < arr.length - 1; j++) { 9 | if (arr[j] > arr[j + 1]) { // arr.sort((a,b) => a - b) change to arr[j] < arr[j+1] for descending order 10 | // swap Number 11 | let temp = arr[j]; 12 | arr[j] = arr[j + 1]; 13 | arr[j + 1] = temp; 14 | } 15 | } 16 | } 17 | return arr; 18 | }; 19 | 20 | console.log(bubbleSort(arr)); // [1,2,3,4,5,7] -------------------------------------------------------------------------------- /questions/leetcode/leetcode10.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/regular-expression-matching/ 2 | 3 | /** 4 | * @param {string} s 5 | * @param {string} p 6 | * @return {boolean} 7 | */ 8 | var isMatch = function (s, p) { 9 | if (p.length === 0) { 10 | return s.length === 0; 11 | } 12 | 13 | const firstMatch = s.length > 0 && (s[0] === p[0] || p[0] === "."); 14 | 15 | if (p.length >= 2 && p[1] === "*") { 16 | return ( 17 | isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)) 18 | ); 19 | } else { 20 | return firstMatch && isMatch(s.substring(1), p.substring(1)); 21 | } 22 | }; -------------------------------------------------------------------------------- /algorithms/searching/binary_search.js: -------------------------------------------------------------------------------- 1 | function binarySearch(sortedArray, key) { 2 | let start = 0; 3 | let end = sortedArray.length - 1; 4 | 5 | while (start <= end) { 6 | let middle = Math.floor((start + end) / 2); 7 | 8 | if (sortedArray[middle] === key) { 9 | // found the key 10 | return middle; 11 | } else if (sortedArray[middle] < key) { 12 | // continue searching to the right 13 | start = middle + 1; 14 | } else { 15 | // search searching to the left 16 | end = middle - 1; 17 | } 18 | } 19 | // key wasn't found 20 | return -1; 21 | } -------------------------------------------------------------------------------- /questions/leetcode/leetcode46.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutations/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number[][]} 6 | */ 7 | var permute = function (nums) { 8 | let result = []; 9 | 10 | const dfs = (i, nums) => { 11 | if (i === nums.length) { 12 | result.push(nums.slice()); 13 | return; 14 | } 15 | 16 | for (let j = i; j < nums.length; j++) { 17 | [nums[i], nums[j]] = [nums[j], nums[i]]; 18 | dfs(i + 1, nums); 19 | [nums[i], nums[j]] = [nums[j], nums[i]]; 20 | } 21 | }; 22 | 23 | dfs(0, nums); 24 | return result; 25 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode49.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/group-anagrams/ 2 | 3 | /** 4 | * @param {string[]} strs 5 | * @return {string[][]} 6 | */ 7 | const groupAnagrams = (strs) => { 8 | // Sorting 9 | const strSort = strs.map(word => word.split('').sort().join('')); 10 | // Create HashMap 11 | const hashMap = {}; 12 | 13 | // Iterate with normal For-Loop 14 | for (let i = 0; i < strs.length; i++) { 15 | if (!hashMap[strSort[i]]) { 16 | hashMap[strSort[i]] = [strs[i]]; 17 | } else { 18 | hashMap[strSort[i]].push(strs[i]); 19 | } 20 | } 21 | return Object.values(hashMap); 22 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/max-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, find the subarray with the largest sum, and return its sum. 3 | 4 | Example 1: 5 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 6 | Output: 6 7 | Explanation: The subarray [4,-1,2,1] has the largest sum 6. 8 | */ 9 | 10 | // Leetcode 53 11 | class Solution { 12 | public: 13 | int maxSubArray(vector& nums) { 14 | int max_sum = INT_MIN; 15 | int current_sum = 0; 16 | 17 | for(int n:nums) { 18 | current_sum = max(n, current_sum+n); 19 | max_sum = max(current_sum, max_sum); 20 | } 21 | 22 | return max_sum; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Data structures/queues/queue_arr.js: -------------------------------------------------------------------------------- 1 | // https://visualgo.net/en/list?slide=11 2 | 3 | 4 | class Queue { //FIFO - First in First Out 5 | constructor () { 6 | this.arr = []; 7 | } 8 | 9 | isEmpty() { 10 | return 0; 11 | } 12 | 13 | peek() { 14 | return this.arr[0]; 15 | } 16 | 17 | queue(value) { 18 | return this.arr.push(value); 19 | } 20 | 21 | deQueue() { 22 | return this.arr.shift(); 23 | } 24 | } 25 | 26 | 27 | const myQueue = new Queue(); 28 | 29 | myQueue.queue('saif'); 30 | myQueue.queue('ananna'); 31 | myQueue.queue('rafiq'); 32 | 33 | console.log(myQueue.peek()); -------------------------------------------------------------------------------- /questions/leetcode/leetcode21.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-sorted-lists/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * function ListNode(val, next) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.next = (next===undefined ? null : next) 8 | * } 9 | */ 10 | /** 11 | * @param {ListNode} list1 12 | * @param {ListNode} list2 13 | * @return {ListNode} 14 | */ 15 | var mergeTwoLists = function (l1, l2) { 16 | if (!l1 || !l2) return l1 || l2; 17 | 18 | if (l1.val > l2.val) { 19 | l2.next = mergeTwoLists(l1, l2.next); 20 | return l2; 21 | } 22 | l1.next = mergeTwoLists(l2, l1.next); 23 | return l1; 24 | }; -------------------------------------------------------------------------------- /Data structures/array/array.js: -------------------------------------------------------------------------------- 1 | const strings = ['a', 'b', 'c', 'd']; 2 | const numbers = [1, 2, 3, 4, 5]; 3 | // Variable array is somewhere in memory and the computer knows it. 4 | // When I do array[2], i'm telling the computer, hey go to the array and grab the 3rd item from where the array is stored. 5 | 6 | /* Adding the string 'e' to the end of the array. */ 7 | strings.push('e'); 8 | 9 | 10 | /* Removing the last item from the array. */ 11 | strings.pop(); 12 | strings.pop(); 13 | 14 | /* Adding the string 'x' to the beginning of the array. */ 15 | strings.unshift('x'); 16 | 17 | /* Adding the string 'alien' to the array at index 2. */ 18 | strings.splice(2, 0, 'alien'); 19 | 20 | console.log(strings); -------------------------------------------------------------------------------- /questions/leetcode/leetcode2465.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-distinct-averages/description/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @return {number} 6 | */ 7 | var distinctAverages = function (nums) { 8 | //Sort the array from min to max number 9 | nums = nums.sort((a, b) => a - b); 10 | //Create set to store only distint averages 11 | let s = new Set(); 12 | //Loop from 0 to middle and calculate average of min element and max (at the end of the sorted array), then add it to the set 13 | for (let i = 0; i < (nums.length / 2); i++) { 14 | s.add((nums[i] + nums[nums.length - i - 1]) / 2); 15 | } return s.size; //the size of the set is the answer (distinct averages) 16 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode917.js: -------------------------------------------------------------------------------- 1 | // (A <= char <= Z) || (a <= char <= z) 2 | var isLetter = function (c) { 3 | return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); 4 | }; 5 | 6 | var swap = function (array, a, b) { 7 | [array[a], array[b]] = [array[b], array[a]]; 8 | }; 9 | 10 | var reverseOnlyLetters = function (S) { 11 | var result = S.split(''); 12 | let l = 0; 13 | let r = result.length - 1; 14 | 15 | while (l < r) { 16 | if (!isLetter(result[l].charCodeAt())) { 17 | l++; 18 | } else if (!isLetter(result[r].charCodeAt())) { 19 | r--; 20 | } else { 21 | swap(result, l++, r--); 22 | } 23 | } 24 | 25 | return result.join(''); 26 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode3.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | 3 | /** 4 | * @param {string} s 5 | * @return {number} 6 | */ 7 | var lengthOfLongestSubstring = function (s) { 8 | const n = s.length; 9 | 10 | let left = 0; 11 | let right = 0; 12 | let max = 0; 13 | let set = new Set(); 14 | 15 | while (right < n) { 16 | const character = s[right]; 17 | if (!set.has(character)) { 18 | set.add(character); 19 | right++; 20 | max = Math.max(set.size, max); 21 | } else { 22 | set.delete(s[left]); 23 | left++; 24 | } 25 | } 26 | return max; 27 | 28 | }; -------------------------------------------------------------------------------- /algorithms/recursion/mergeSortUsingRecursion/mergeSortUsingRecursion.js: -------------------------------------------------------------------------------- 1 | const mergeSort = (array) => { 2 | if (array.length == 1) { // when you have one item left, return to the previous branch 3 | return array; 4 | } else { // otherwise 5 | let half = Math.floor(array.length / 2); // get a halfway point for your array 6 | mergeSort(array.slice(0, array.length - half)); // split the first half into the left branch 7 | mergeSort(array.slice(0 - half)); // and the right half into the right branch 8 | return; // do something with your branches as you pull back ... 9 | } 10 | }; 11 | 12 | let arr = [-5, 3, 20, 10, 2, 0]; 13 | mergeSort(arr, 0, arr.length - 1); // run and debug in vscode to show the call stack 14 | -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/lis.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, return the length of the longest strictly increasing subsequence. 3 | 4 | Input: nums = [10,9,2,5,3,7,101,18] 5 | Output: 4 6 | Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 7 | */ 8 | 9 | // Leetcode 300 10 | class Solution { 11 | public: 12 | int lengthOfLIS(vector& nums) { 13 | int n = nums.size(); 14 | vector dp(n, 1); 15 | for(int i=1;i nums[j]) { 18 | dp[i] = max(dp[i], dp[j]+1); 19 | } 20 | } 21 | } 22 | return *max_element(dp.begin(), dp.end()); 23 | } 24 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a staircase. It takes n steps to reach the top. 3 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | Example 1: 6 | Input: n = 2 7 | Output: 2 8 | Explanation: There are two ways to climb to the top. 9 | 1. 1 step + 1 step 10 | 2. 2 steps 11 | */ 12 | 13 | // Leetcode 70 14 | class Solution { 15 | public: 16 | int climbStairs(int n) { 17 | if(n < 2) return 1; 18 | 19 | int steps[n+1]; 20 | steps[0] = 1; 21 | steps[1] = 1; 22 | 23 | for(int i=2;i<=n;i++) { 24 | steps[i] = steps[i-1] + steps[i-2]; 25 | } 26 | 27 | return steps[n]; 28 | } 29 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode17.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} digits 3 | * @return {string[]} 4 | */ 5 | var letterCombinations = function (digits) { 6 | if (!digits) return []; 7 | const kb = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; 8 | let str = [], 9 | res = []; 10 | BT(); 11 | return res; 12 | function BT(idx = 0) { 13 | if (idx === digits.length) { 14 | res.push(str.join("")); 15 | return; 16 | } 17 | let digit = digits[idx], charStr = kb[+digit]; 18 | //each layer we start from index 0. 19 | for (let i = 0; i < charStr.length; i++) { 20 | str.push(charStr[i]); 21 | BT(idx + 1); 22 | str.pop(); 23 | } 24 | } 25 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode171.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} columnTitle 3 | * @return {number} 4 | */ 5 | var titleToNumber = function (columnTitle) { 6 | let result = 0; 7 | let length = columnTitle.length; 8 | for (let i = 0; i < length; i++) { 9 | result += (columnTitle.charCodeAt(i) - 64) * Math.pow(26, length - (i + 1)); 10 | } 11 | return result; 12 | }; 13 | 14 | 15 | /* 16 | Very simple charCode of a upper case character - 64 = their alphabet position and 26 pow position of the character (starting from right) - so length - (i+1) means that the last character will end up being just it's alphabet position (character * 1), the one before is going to be * 26, the one before * 26 * 26 and so on. 17 | Simple math solution that works just fine. 18 | */ -------------------------------------------------------------------------------- /questions/leetcode/leetcode5.js: -------------------------------------------------------------------------------- 1 | // this is important 2 | 3 | //https://leetcode.com/problems/zigzag-conversion/ 4 | 5 | /** 6 | * @param {string} s 7 | * @param {number} numRows 8 | * @return {string} 9 | */ 10 | const convert = (s, numRows) => { 11 | // 1. Make an array with the zigzag sequence 12 | const zigzag = [...new Array(numRows).keys()]; 13 | zigzag.push(...zigzag.slice(1, -1).reverse()); 14 | // 2. Make an array with as many strings as we need rows 15 | const rows = new Array(numRows).fill(''); 16 | // 3. Append the characters to the row strings in zigzag sequence 17 | [...s].forEach((c, i) => (rows[zigzag[i % zigzag.length]] += c)); 18 | // 4. Join the row strings in the array together 19 | return rows.join(''); 20 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode925.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} name 3 | * @param {string} typed 4 | * @return {boolean} 5 | */ 6 | var isLongPressedName = function (name, typed) { 7 | let start = 0; 8 | let end = 0; 9 | 10 | for (let i = 0; i < name.length; i++) { 11 | end = start; 12 | if (name[i] !== typed[start]) return false; 13 | 14 | while (name[i] === name[i + 1] && name[i] === typed[start] && name[i + 1] === typed[start + 1]) { 15 | start++; 16 | i++; 17 | } 18 | while (name[i] === typed[start] && name[i] !== name[i + 1]) { 19 | start++; 20 | } 21 | if (start === end) return false; 22 | } 23 | if (start !== typed.length) return false; 24 | 25 | return true; 26 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/gridTraveler.js: -------------------------------------------------------------------------------- 1 | /* You are a traveler on a 2D grid. YOu begin in the top-left corder and your goal 2 | is to travel to the bottom to the bottom right. You may only move down or right. 3 | 4 | In how many ways can you travel to the goal on a grid with dimensions m * n ? 5 | */ 6 | 7 | 8 | const gridTraveler = (m, n, memo = {}) => { 9 | const key = m + ',' + n; 10 | 11 | if (key in memo) return memo[key]; 12 | if (m === 1 && n === 1) return 1; 13 | if (m === 0 || n === 0) return 0; 14 | memo[key] = gridTraveler(m - 1, n, memo) + gridTraveler(m, n - 1, memo); 15 | return memo[key]; 16 | }; 17 | 18 | console.log(gridTraveler(18, 18)); 19 | console.log(gridTraveler(0, 1)); 20 | console.log(gridTraveler(3, 3)); -------------------------------------------------------------------------------- /algorithms/sorting/interview_question_example/ex.txt: -------------------------------------------------------------------------------- 1 | //#1 - Sort 10 schools around your house by distance: 2 | insertion sort 3 | 4 | //#2 - eBay sorts listings by the current Bid amount: 5 | radix or counting sort 6 | 7 | //#3 - Sort scores on ESPN 8 | Quick sort 9 | 10 | //#4 - Massive database (can't fit all into memory) needs to sort through past year's user data 11 | Merge Sort 12 | 13 | //#5 - Almost sorted Udemy review data needs to update and add 2 new reviews 14 | Insertion Sort 15 | 16 | //#6 - Temperature Records for the past 50 years in Canada 17 | radix or counting Sort 18 | Quick sort if decimal places 19 | 20 | //#7 - Large user name database needs to be sorted. Data is very random. 21 | Quick sort 22 | 23 | //#8 - You want to teach sorting 24 | Bubble sort -------------------------------------------------------------------------------- /algorithms/recursion/factorial/factorial.js: -------------------------------------------------------------------------------- 1 | // 5! = 5 * 4 * 3 * 2 * 1 2 | 3 | 4 | let t0 = performance.now(); 5 | function findFactorialRecursively(n) { 6 | 7 | if (n === 2) { 8 | return 2; 9 | } 10 | return n * findFactorialRecursively(n - 1); 11 | } 12 | let t1 = performance.now(); 13 | // console.log(t1 - t0); 14 | 15 | // using loop method which iterates over the number 16 | let t3 = performance.now(); 17 | function findFactorialIteratively(num) { 18 | let answer = 1; 19 | for (let i = 2; i <= num; i++) { 20 | answer *= i; 21 | } 22 | return answer; 23 | } 24 | let t4 = performance.now(); 25 | // console.log(t4 - t3); 26 | 27 | // console.log(findFactorialIteratively(5)); 28 | // console.log(findFactorialRecursively(5)); 29 | -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/selection_sort.js: -------------------------------------------------------------------------------- 1 | // TC = O(n^2) 2 | // SC = O(1) 3 | 4 | const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]; 5 | 6 | function selectionSort(array) { 7 | const length = array.length; 8 | for (let i = 0; i < length; i++) { 9 | // set current index as minimum 10 | let min = i; 11 | let temp = array[i]; 12 | for (let j = i + 1; j < length; j++) { 13 | if (array[j] < array[min]) { 14 | //update minimum if current is lower that what we had previously 15 | min = j; 16 | } 17 | } 18 | array[i] = array[min]; 19 | array[min] = temp; 20 | } 21 | return array; 22 | } 23 | 24 | selectionSort(numbers); 25 | console.log(numbers); -------------------------------------------------------------------------------- /questions/leetcode/leetcode29.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/divide-two-integers/ 2 | 3 | /** 4 | * @param {number} dividend 5 | * @param {number} divisor 6 | * @return {number} 7 | */ 8 | var divide = function (dividend, divisor) { 9 | if (dividend === -2147483648 && divisor === -1) { 10 | return 2147483647; 11 | } 12 | var isNeg = dividend > 0 ^ divisor > 0; 13 | var res = 0; 14 | 15 | dividend = Math.abs(dividend); 16 | subtract(Math.abs(divisor), 1); 17 | 18 | function subtract(d, q) { 19 | if (dividend > d) { 20 | subtract(d + d, q + q); 21 | } 22 | if (dividend >= d) { 23 | dividend -= d; 24 | res += q; 25 | } 26 | } 27 | 28 | return isNeg ? -res : res; 29 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode116.js: -------------------------------------------------------------------------------- 1 | /** 2 | * // Definition for a Node. 3 | * function Node(val, left, right, next) { 4 | * this.val = val === undefined ? null : val; 5 | * this.left = left === undefined ? null : left; 6 | * this.right = right === undefined ? null : right; 7 | * this.next = next === undefined ? null : next; 8 | * }; 9 | */ 10 | 11 | /** 12 | * @param {Node} root 13 | * @return {Node} 14 | */ 15 | var connect = function (root) { 16 | let ptr = root; 17 | while (root && root.left) { 18 | let temp = root; 19 | 20 | while (temp) { 21 | temp.left.next = temp.right; 22 | temp.right.next = temp.next ? temp.next.left : null; 23 | temp = temp.next; 24 | } 25 | root = root.left; 26 | } 27 | return ptr; 28 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode105.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {number[]} preorder 11 | * @param {number[]} inorder 12 | * @return {TreeNode} 13 | */ 14 | var buildTree = function (preorder, inorder) { 15 | p = i = 0; 16 | build = function (stop) { 17 | if (inorder[i] != stop) { 18 | var root = new TreeNode(preorder[p++]); 19 | root.left = build(root.val); 20 | i++; 21 | root.right = build(stop); 22 | return root; 23 | } 24 | return null; 25 | }; 26 | return build(); 27 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode1616.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} a 3 | * @param {string} b 4 | * @return {boolean} 5 | */ 6 | var checkPalindromeFormation = function (a, b) { 7 | const isPal = (s, start, end) => { 8 | while (start < end) { 9 | if (s[start] === s[end]) start++, end--; 10 | else return false; 11 | } 12 | return true; 13 | }; 14 | 15 | // ap + bs 16 | let start = 0, end = b.length - 1; 17 | while (start < end && a[start] === b[end]) start++, end--; 18 | if (isPal(a, start, end) || isPal(b, start, end)) return true; 19 | 20 | //bs + ap 21 | start = 0, end = a.length - 1; 22 | while (start < end && b[start] === a[end]) start++, end--; 23 | if (isPal(a, start, end) || isPal(b, start, end)) return true; 24 | 25 | return false; 26 | }; -------------------------------------------------------------------------------- /questions/two_pointers/max-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, find a subarray that has the largest product, and return the product. 3 | The test cases are generated so that the answer will fit in a 32-bit integer. 4 | 5 | Example 1: 6 | Input: nums = [2,3,-2,4] 7 | Output: 6 8 | Explanation: [2,3] has the largest product 6. 9 | */ 10 | 11 | // Leetcode 152 12 | class Solution { 13 | public: 14 | int maxProduct(vector& nums) { 15 | int left = 1, right = 1, result = nums[0]; 16 | for(int i=0;i 0) water += count; 17 | else maxL = height[left]; 18 | left++; 19 | } else { 20 | let count = maxR - height[right]; 21 | if (count > 0) water += count; 22 | else maxR = height[right]; 23 | right--; 24 | } 25 | } 26 | return water; 27 | 28 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode7.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/ 2 | 3 | /** 4 | * @param {number} x 5 | * @return {number} 6 | */ 7 | var reverse = function (x) { 8 | let num = x.toString(); 9 | let rev = ""; 10 | 11 | if (num.includes('-')) { 12 | let without = num.split('-')[1]; 13 | for (let i = without.length - 1; i >= 0; i--) { 14 | rev += without[i]; 15 | } 16 | } 17 | else { 18 | for (let i = num.length - 1; i >= 0; i--) { 19 | rev += num[i]; 20 | } 21 | } 22 | let number = parseInt(rev); 23 | 24 | if (number < Math.pow(-2, 31) || number > Math.pow(2, 31) - 1) return 0; 25 | 26 | else if (num.includes('-')) return number * -1; 27 | else return number; 28 | 29 | 30 | 31 | }; -------------------------------------------------------------------------------- /questions/removeDuplicatesFromList.js: -------------------------------------------------------------------------------- 1 | // ref: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ 2 | 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * function ListNode(val, next) { 7 | * this.val = (val===undefined ? 0 : val) 8 | * this.next = (next===undefined ? null : next) 9 | * } 10 | */ 11 | /** 12 | * @param {ListNode} head 13 | * @return {ListNode} 14 | */ 15 | 16 | var deleteDuplicates = function (head) { 17 | var currentNode = head; 18 | 19 | while (currentNode) { 20 | if (currentNode.next !== null && currentNode.val == currentNode.next.val) { 21 | currentNode.next = currentNode.next.next; 22 | } else { 23 | currentNode = currentNode.next; 24 | } 25 | } 26 | 27 | return head; 28 | }; -------------------------------------------------------------------------------- /algorithms/recursion/isPalindrome/isPalindrome.js: -------------------------------------------------------------------------------- 1 | const isPalindrome = (input) => { 2 | // The base case or Stopping condition 3 | if (input.length < 2) return true; 4 | 5 | // Some work to shrink the problem space 6 | if (input[0] === input[input.length - 1]) { 7 | return isPalindrome(input.substr(1, input.length - 2)); 8 | } 9 | 10 | // Additional base case to handle non-palindromes 11 | return false; 12 | }; 13 | 14 | console.log(isPalindrome('abba')); 15 | 16 | /* 17 | ! PsedoCode for other language 18 | 19 | function isPalindrome(str) { 20 | if (str.length < 2) { 21 | return true; 22 | } 23 | 24 | if (firstCharacter(str) === lastCharacter(str)) { 25 | return isPalindrome(middleCharacters(str)); 26 | } 27 | 28 | return false; 29 | } 30 | */ -------------------------------------------------------------------------------- /questions/leetcode/leetcode8.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/string-to-integer-atoi/ 2 | 3 | /** 4 | * @param {string} s 5 | * @return {number} 6 | */ 7 | var myAtoi = function (str) { 8 | var i = 0; 9 | var sign = 1; 10 | var res = 0; 11 | var len = str.length; 12 | var INT_MAX = 2147483647; 13 | var INT_MIN = - INT_MAX - 1; 14 | 15 | while (str[i] === ' ') i++; 16 | 17 | if (str[i] === '+' || str[i] === '-') { 18 | sign = str[i] === '+' ? 1 : -1; 19 | i++; 20 | } 21 | 22 | while (str[i] >= '0' && str[i] <= '9') { 23 | res = (res * 10) + (str[i] - 0); 24 | if (sign === 1 && res > INT_MAX) return INT_MAX; 25 | if (sign === -1 && res > INT_MAX + 1) return INT_MIN; 26 | i++; 27 | } 28 | 29 | return res * sign; 30 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode131.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string[][]} 4 | */ 5 | var partition = function (s) { 6 | 7 | function isPalindrome(str) { 8 | let left = 0, right = str.length - 1; 9 | 10 | while (left < right) { 11 | if (str[left] !== str[right]) return false; 12 | left++; 13 | right--; 14 | } 15 | return true; 16 | } 17 | 18 | const result = []; 19 | 20 | function permute(arr, str) { 21 | if (!str.length) result.push(arr); 22 | 23 | for (let i = 1; i <= str.length; i++) { 24 | const subStr = str.slice(0, i); 25 | if (isPalindrome(subStr)) { 26 | permute([...arr, subStr], str.slice(i)); 27 | } 28 | } 29 | } 30 | permute([], s); 31 | return result; 32 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode6.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/description/ 2 | 3 | /** 4 | * @param {number} x 5 | * @return {number} 6 | */ 7 | var reverse = function (x) { 8 | let num = x.toString(); 9 | let rev = ""; 10 | 11 | if (num.includes('-')) { 12 | let without = num.split('-')[1]; 13 | for (let i = without.length - 1; i >= 0; i--) { 14 | rev += without[i]; 15 | } 16 | } 17 | else { 18 | for (let i = num.length - 1; i >= 0; i--) { 19 | rev += num[i]; 20 | } 21 | } 22 | let number = parseInt(rev); 23 | 24 | if (number < Math.pow(-2, 31) || number > Math.pow(2, 31) - 1) return 0; 25 | 26 | else if (num.includes('-')) return number * -1; 27 | else return number; 28 | 29 | 30 | 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /questions/leetcode/leetcode345.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-vowels-of-a-string/description/ 2 | 3 | /** 4 | * @param {string} s 5 | * @return {string} 6 | */ 7 | 8 | var reverseVowels = function (s) { 9 | const vowels = ['a', 'e', 'i', 'o', 'u']; 10 | let ans = s.split(''); 11 | let start = 0; 12 | let end = s.length - 1; 13 | 14 | while (start < end) { 15 | if (vowels.includes(s[start].toLowerCase()) && vowels.includes(s[end].toLowerCase())) { 16 | [ans[start], ans[end]] = [ans[end], ans[start]]; 17 | start++; 18 | end--; 19 | } 20 | if (!vowels.includes(s[start].toLowerCase())) { 21 | start++; 22 | } 23 | if (!vowels.includes(s[end].toLowerCase())) { 24 | end--; 25 | } 26 | } 27 | 28 | return ans.join(''); 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /Data structures/stacks/stacks_arr.js: -------------------------------------------------------------------------------- 1 | // https://visualgo.net/en/list?slide=1 2 | 3 | class Stack { 4 | constructor () { 5 | this.arr = []; 6 | } 7 | 8 | isEmpty() { 9 | return 0; 10 | } 11 | 12 | peek() { 13 | return this.arr[this.arr.length - 1]; 14 | } 15 | 16 | push(value) { 17 | return this.arr.push(value); 18 | } 19 | 20 | pop() { 21 | return this.arr.pop(); 22 | } 23 | 24 | } 25 | 26 | const myStack = new Stack(); 27 | myStack.push(5); 28 | myStack.push(4); 29 | myStack.push(7); 30 | myStack.push(1); 31 | 32 | // console.log(myStack.peek()); 33 | // myStack.pop(); 34 | // console.log(myStack.peek()); 35 | 36 | console.log(myStack); 37 | 38 | /* LIFO- Last In First Out 39 | 40 | 1 41 | 7 42 | 4 43 | 5 44 | 45 | */ -------------------------------------------------------------------------------- /heap/top-k-freq-elem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 3 | 4 | Example 1: 5 | Input: nums = [1,1,1,2,2,3], k = 2 6 | Output: [1,2] 7 | */ 8 | 9 | // Leetcode 347 10 | class Solution { 11 | public: 12 | vector topKFrequent(vector& nums, int k) { 13 | unordered_map umap; 14 | priority_queue> pq; 15 | vector ans; 16 | 17 | for(int n:nums) { 18 | umap[n]++; 19 | } 20 | 21 | for(auto it = umap.begin();it != umap.end(); it++) { 22 | pq.push({ it->second, it->first }); 23 | } 24 | 25 | for(int i=0;i { 4 | if (arr.length === 0) return 0; 5 | const rest = arr.slice(1); // this will bottleneck for sure 6 | return arr[0] + sum(rest); 7 | }; 8 | /* 9 | Time: O(n^2) :( 10 | Space: O(n) 11 | */ 12 | 13 | // ----------------------------------------------------------------------------------- 14 | 15 | // More optimized and efficient method 16 | const sum2 = (arr) => { 17 | return _sum(arr, 0); 18 | }; 19 | 20 | const _sum = (arr, idx) => { 21 | if (idx === arr.length) return 0; 22 | return arr[idx] + _sum(arr, (idx + 1)); 23 | }; 24 | /* 25 | Time: O(n) :) 26 | Space: O(n) 27 | */ 28 | 29 | 30 | 31 | 32 | console.log(sum2([1, 5, 2, -1])); // 11 33 | console.log(sum2([1, 2, 3, 5, 4, 6])); // 21 34 | 35 | -------------------------------------------------------------------------------- /algorithms/recursion/reverseStrWithRecursion/reverseStrWithRecursion.js: -------------------------------------------------------------------------------- 1 | // Normal approach 2 | function reverseString(str) { 3 | let arrayStr = str.split(""); 4 | let reversedArray = []; 5 | //We are using closure here so that we don't add the above variables to the global scope. 6 | function addToArray(array) { 7 | 8 | if (array.length > 0) { 9 | reversedArray.push(array.pop()); 10 | addToArray(array); 11 | } 12 | return; 13 | } 14 | addToArray(arrayStr); 15 | return reversedArray.join(""); 16 | } 17 | 18 | reverseString('yoyo master'); 19 | 20 | // Recursive approach 21 | function reverseStringRecursive(str) { 22 | if (str === "") { 23 | return ""; 24 | } else { 25 | return reverseStringRecursive(str.substr(1)) + str.charAt(0); 26 | } 27 | } 28 | 29 | reverseStringRecursive('yoyo master'); -------------------------------------------------------------------------------- /questions/leetcode/leetcode43.js: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/multiply-strings/ 2 | 3 | /** 4 | * @param {string} num1 5 | * @param {string} num2 6 | * @return {string} 7 | */ 8 | var multiply = function (num1, num2) { 9 | var result = Array(num1.length + num2.length).fill(0); 10 | for (var j = num2.length - 1; j >= 0; j--) { 11 | // k is the index in the result: where to add to 12 | var k = num1.length + j; 13 | var overflow = 0; 14 | for (var i = num1.length - 1; i >= 0; i--) { 15 | product = num2[j] * num1[i] + overflow + result[k]; 16 | result[k] = product % 10; 17 | overflow = (product - result[k]) / 10; 18 | k--; 19 | } 20 | result[k] += overflow; 21 | } 22 | // Convert result to string, removing any prepadded zeroes 23 | return result.join('').replace(/^0+(.)/, '$1'); 24 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/maximal-square.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 3 | */ 4 | 5 | // Leetcode 221 6 | class Solution { 7 | public: 8 | int maximalSquare(vector>& matrix) { 9 | int m = matrix.size(); 10 | int n = matrix[0].size(); 11 | vector> dp(m, vector(n)); 12 | int ms = 0; 13 | 14 | for(int i=0;i& nums) { 15 | int left = 0, right = nums.size()-1, k = 0; 16 | while(k <= right) { 17 | if(nums[k] == 0) { 18 | swap(nums[k++], nums[left++]); 19 | } else if(nums[k] == 1) { 20 | k++; 21 | } else { 22 | swap(nums[k], nums[right--]); 23 | } 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode347.js: -------------------------------------------------------------------------------- 1 | 2 | /* * *@param {number[]} nums 3 | * @param {number} k 4 | * @return {number[]} 5 | */ 6 | 7 | var topKFrequent = function (nums, k) { 8 | 9 | let map = new Map(); 10 | let maxHeap = new MaxPriorityQueue((item) => item.value); 11 | 12 | 13 | // O(n) Time complexity 14 | for (let num of nums) { 15 | if (!map.get(num)) { 16 | map.set(num, 1); 17 | } else { 18 | map.set(num, map.get(num) + 1); 19 | } 20 | } 21 | 22 | 23 | 24 | let ans = []; 25 | // We are building a maxHeap for the D unique item 26 | // O(D) time complexity 27 | for (let [key, value] of map) { 28 | maxHeap.enqueue(key, value); 29 | } 30 | 31 | 32 | 33 | for (let i = 0; i < k; i++) { 34 | // We are dequeuing the k elements which can take upto O(klogD) 35 | let _item = maxHeap.dequeue(); 36 | ans.push(_item.element); 37 | } 38 | 39 | return ans; 40 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode33.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-in-rotated-sorted-array/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} target 6 | * @return {number} 7 | */ 8 | var search = function (nums, target) { 9 | let startIndex = 0; 10 | let endIndex = nums.length - 1; 11 | 12 | if (startIndex > endIndex) return -1; 13 | 14 | while (startIndex <= endIndex) { 15 | let midIndex = startIndex + Math.floor((endIndex - startIndex) / 2); 16 | 17 | if (nums[midIndex] === target) return midIndex; 18 | 19 | if (nums[startIndex] <= nums[midIndex]) { 20 | if (nums[startIndex] <= target && target < nums[midIndex]) endIndex = midIndex - 1; 21 | else startIndex = midIndex + 1; 22 | } else { 23 | if (nums[midIndex] < target && target <= nums[endIndex]) startIndex = midIndex + 1; 24 | else endIndex = midIndex - 1; 25 | } 26 | } 27 | 28 | return -1; 29 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/palindromic-ss.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, return the number of palindromic substrings in it. 3 | A string is a palindrome when it reads the same backward as forward. 4 | A substring is a contiguous sequence of characters within the string. 5 | 6 | Example 1: 7 | Input: s = "abc" 8 | Output: 3 9 | Explanation: Three palindromic strings: "a", "b", "c". 10 | */ 11 | 12 | // Leetcode 647 13 | class Solution { 14 | public: 15 | int isPalindrome(string s, int start, int end) { 16 | while(start < end) { 17 | if(s[start++] != s[end--]) return 0; 18 | } 19 | return 1; 20 | } 21 | 22 | int countSubstrings(string s) { 23 | int dp[s.length()]; 24 | dp[0] = 1; 25 | 26 | for(int i=1;i a - b); 10 | 11 | let min = Number.MAX_SAFE_INTEGER; 12 | let ans = 0; 13 | const n = nums.length; 14 | 15 | for (let i = 0; i < n; i++) { 16 | let j = i + 1; 17 | let k = n - 1; 18 | 19 | while (j < k) { 20 | const sum = nums[i] + nums[j] + nums[k]; 21 | 22 | if (min > Math.abs(target - sum)) { 23 | min = Math.abs(target - sum); 24 | ans = sum; 25 | } 26 | 27 | if (sum > target) { 28 | k--; 29 | } else if (sum < target) { 30 | j++; 31 | } else { 32 | return sum; 33 | } 34 | } 35 | } 36 | 37 | return ans; 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/fibSeries.js: -------------------------------------------------------------------------------- 1 | /* write a function that takes in a number as an argument. 2 | The function should return the n-th number of the Fibonacci series. 3 | 4 | n: 1, 2, 3, 4, 5, 6, 7, 8 5 | fib(n): 1, 1, 2, 3, 5, 8, 13, 21 6 | */ 7 | 8 | 9 | // const fib = (n) => { 10 | // if (n <= 2) return 1; 11 | // return fib(n - 1) + fib(n - 2); 12 | // }; 13 | 14 | // if I use fib(50) it will take a long time to finish this job. It is too slow. 15 | // So we will try to improve it's efficiancy and make it into DP 16 | 17 | /* Memoization */ 18 | // JS object, Keys will be args to fn, value will be the return value 19 | 20 | const fibDP = (n, memo = {}) => { 21 | // Base case 22 | if (n in memo) return memo[n]; 23 | if (n <= 2) return 1; 24 | 25 | // Recursive case 26 | memo[n] = fibDP(n - 1, memo) + fibDP(n - 2, memo); 27 | return memo[n]; 28 | }; 29 | 30 | console.log(fibDP(50)); 31 | 32 | // this is way faster than the upper one or the tradditional one. :) -------------------------------------------------------------------------------- /questions/leetcode/leetcode130.js: -------------------------------------------------------------------------------- 1 | var solve = function (board) { 2 | if (board.length == 0) return; 3 | 4 | // dfs searching for '0' 5 | var recur = function (i, j) { 6 | if (i < 0 || i >= board.length || j < 0 || j >= board[i].length) return; 7 | if (board[i][j] != 'O') return; 8 | board[i][j] = '-'; 9 | recur(i + 1, j); 10 | recur(i - 1, j); 11 | recur(i, j + 1); 12 | recur(i, j - 1); 13 | }; 14 | 15 | // check left & right boundary 16 | for (let i = 0; i < board.length; i++) { 17 | recur(i, 0); 18 | recur(i, board[0].length - 1); 19 | } 20 | 21 | // check top & bot boundary 22 | for (let i = 0; i < board[0].length; i++) { 23 | recur(0, i); 24 | recur(board.length - 1, i); 25 | } 26 | 27 | for (let i = 0; i < board.length; i++) { 28 | for (let j = 0; j < board[0].length; j++) { 29 | if (board[i][j] == 'O') board[i][j] = "X"; 30 | if (board[i][j] == '-') board[i][j] = "O"; 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode44.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} p 4 | * @return {boolean} 5 | */ 6 | var isMatch = function (text1, text2) { 7 | let arr = new Array(text1.length + 1); 8 | for (let a = 0; a < arr.length; a++) { 9 | arr[a] = new Array(text2.length + 1).fill(false); 10 | } 11 | for (let i = 0; i < arr.length; i++) { 12 | for (let j = 0; j < arr[0].length; j++) { 13 | if (j == 0 && i == 0) arr[i][j] = true; 14 | if (i > 0 && j == 0) arr[i][j] = false; 15 | if (i == 0 && j > 0) arr[i][j] = text2[j - 1] == '*' ? arr[i][j - 1] : false; 16 | } 17 | } 18 | for (let i = 1; i < arr.length; i++) { 19 | for (let j = 1; j < arr[0].length; j++) { 20 | if (text1[i - 1] == text2[j - 1] || text2[j - 1] == '?') arr[i][j] = arr[i - 1][j - 1]; 21 | else if (text2[j - 1] == '*') arr[i][j] = arr[i][j - 1] || arr[i - 1][j]; 22 | else arr[i][j] = false; 23 | } 24 | } 25 | return arr[text1.length][text2.length]; 26 | }; -------------------------------------------------------------------------------- /JAVA solutions/linkedlist/LLMain.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | public class LLMain { 4 | public static void main(String[] args) { 5 | LL list = new LL(); 6 | // LL test = new LL(); 7 | // 8 | // test.deleteAt(3); 9 | 10 | list.addFirst(2); 11 | list.addFirst(3); 12 | list.addLast(5); 13 | list.addLast(7); 14 | list.addLast(8); 15 | list.addLast(9); 16 | list.addAt(10, 3); 17 | list.insertRec(25, 3); 18 | list.printList(); 19 | 20 | System.out.println(list.getValueAt(4)); 21 | System.out.println(list.size()); 22 | 23 | CircularLL cList = new CircularLL(); 24 | 25 | cList.add(1); 26 | cList.add(2); 27 | cList.add(3); 28 | cList.add(4); 29 | cList.add(5); 30 | 31 | cList.deleteAt(3); 32 | 33 | cList.printList(); 34 | 35 | // list.deleteFirst(); 36 | // list.deleteLast(); 37 | // list.deleteAt(3); 38 | 39 | // list.reversePrint(); 40 | 41 | 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/recursion/fibonacci/fibonacci.js: -------------------------------------------------------------------------------- 1 | // Given a number N return the index value of the Fibonacci sequence, where the sequence is: 2 | 3 | // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ... 4 | // the pattern of the sequence is that each value is the sum of the 2 previous values, that means that for N=5 → 2+3 5 | 6 | //For example: fibonacciRecursive(6) should return 8 7 | 8 | function fibonacciIterative(n) { 9 | let arr = [0, 1]; 10 | 11 | for (let i = 2; i < n + 1; i++) { 12 | arr.push(arr[i - 2] + arr[i - 1]); 13 | } 14 | return arr[n]; 15 | } 16 | console.log(fibonacciIterative(3)); 17 | 18 | function fibonacciRecursive(n) { 19 | if (n < 2) { 20 | return n; 21 | } 22 | return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); 23 | } 24 | 25 | console.log(fibonacciRecursive(3)); 26 | 27 | // if the value if 40 the time complexity will increase by O(2^N) which is worst 28 | 29 | /* https://2ality.com/2015/06/tail-call-optimization.html read it to understand 30 | the recursion vs iteration 31 | */ -------------------------------------------------------------------------------- /questions/leetcode/leetcode103.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {number[][]} 12 | */ 13 | const zigzagLevelOrder = (root) => { 14 | if (root === null) return []; 15 | 16 | let level = [root]; 17 | let zigzag = []; 18 | while (level.length > 0) { 19 | zigzag.push(level.map(node => node.val)); 20 | level = level.flatMap(node => [node.left, node.right]).filter(Boolean); 21 | // The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately. 22 | } 23 | 24 | return zigzag.map((level, index) => index % 2 === 1 ? level.reverse() : level); 25 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/divisor-game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Alice and Bob take turns playing a game, with Alice starting first. 3 | 4 | Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: 5 | 6 | Choosing any x with 0 < x < n and n % x == 0. 7 | Replacing the number n on the chalkboard with n - x. 8 | Also, if a player cannot make a move, they lose the game. 9 | 10 | Return true if and only if Alice wins the game, assuming both players play optimally. 11 | */ 12 | 13 | // Leetcode 1025 14 | class Solution { 15 | public: 16 | int dp[1001]; 17 | 18 | int executeGame(int n) { 19 | if(n==1) return 0; 20 | if(dp[n]!=-1) return dp[n]; 21 | 22 | for(int i=1;i*i<=n;i++) { 23 | if(n%i==0) { 24 | if(executeGame(n-i)==0) return dp[n]=1; 25 | if((i!=1) && (executeGame(n-(n/i))==0)) return dp[n]=1; 26 | } 27 | } 28 | 29 | return dp[n]=0; 30 | } 31 | 32 | bool divisorGame(int n) { 33 | memset(dp, -1, sizeof dp); 34 | return executeGame(n); 35 | } 36 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode19.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * function ListNode(val, next) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.next = (next===undefined ? null : next) 8 | * } 9 | */ 10 | /** 11 | * @param {ListNode} head 12 | * @param {number} n 13 | * @return {ListNode} 14 | */ 15 | var removeNthFromEnd = function (head, n) { 16 | let headNode = head; 17 | let nodes = []; 18 | while (headNode.next !== null) { 19 | nodes.push(headNode); 20 | headNode = headNode.next; 21 | } 22 | nodes.push(headNode); 23 | if (nodes.length === 1 && n === 1) { 24 | return null; 25 | } 26 | const removedNodeIndex = nodes.length - n; 27 | if (removedNodeIndex === 0) { 28 | return nodes[1]; 29 | } else if (removedNodeIndex === nodes.length - 1) { 30 | nodes[nodes.length - 2].next = null; 31 | } else { 32 | nodes[removedNodeIndex - 1].next = nodes[removedNodeIndex + 1]; 33 | } 34 | return nodes[0]; 35 | }; -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/insertion_sort.js: -------------------------------------------------------------------------------- 1 | // efficient than bubble and selection sort 2 | // TC = O(n^2) 3 | // SC = O(1) 4 | 5 | const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]; 6 | 7 | function insertionSort(arr) { 8 | const length = arr.length; 9 | for (let i = 0; i < length; i++) { 10 | if (arr[i] < arr[0]) { 11 | //move number to the first position 12 | arr.unshift(arr.splice(i, 1)[0]); 13 | } else { 14 | // only sort number smaller than number on the left of it. This is the part of insertion sort that makes it fast if the arr is almost sorted. 15 | if (arr[i] < arr[i - 1]) { 16 | //find where number should go 17 | for (var j = 1; j < i; j++) { 18 | if (arr[i] >= arr[j - 1] && arr[i] < arr[j]) { 19 | //move number to the right spot 20 | arr.splice(j, 0, arr.splice(i, 1)[0]); 21 | } 22 | } 23 | } 24 | } 25 | } 26 | } 27 | 28 | insertionSort(numbers); 29 | console.log(numbers); -------------------------------------------------------------------------------- /questions/leetcode/leetcode11.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water/ 2 | 3 | /** 4 | * @param {number[]} height 5 | * @return {number} 6 | */ 7 | 8 | // brute force solution 9 | const maxWater = (arr) => { 10 | let maxArea = 0; 11 | for (let i = 0; i < arr.length; i++) { 12 | for (let j = i + 1; j < arr.length; j++) { 13 | let min = Math.min(arr[i], arr[j]) * (j - i); 14 | if (maxArea < min) { 15 | maxArea = min; 16 | } 17 | } 18 | } 19 | return maxArea; 20 | }; 21 | 22 | // optimized 23 | var maxArea = function (height) { 24 | const len = height.length; 25 | let L = 0; 26 | let R = len - 1; 27 | let max = 0; 28 | while (L < R) { 29 | let width = R - L; 30 | let length = Math.min(height[L], height[R]); 31 | max = Math.max(max, width * length); 32 | if (height[L] > height[R]) { 33 | R--; 34 | } else if (height[R] > height[L]) { 35 | L++; 36 | } else { 37 | R--; 38 | } 39 | } 40 | return max; 41 | }; -------------------------------------------------------------------------------- /Data structures/array/problems/finders_keepers.js: -------------------------------------------------------------------------------- 1 | /* 2 | Create a function that looks through an array arr 3 | and returns the first element in it that passes a 'truth test'. This means that given an element x, 4 | the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined. 5 | 6 | findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8. 7 | findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) should return undefined. 8 | */ 9 | 10 | function findElement(arr, func) { 11 | let num = 0; 12 | 13 | for (let i = 0; i < arr.length; i++) { 14 | num = arr[i]; 15 | if (func(num)) { 16 | return num; 17 | } 18 | } 19 | 20 | return undefined; 21 | } 22 | 23 | 24 | // ES6 approach 25 | function findElement(arr, func) { 26 | return arr[arr.map(func).indexOf(true)]; 27 | } 28 | 29 | // ** Recursive Solution** 30 | function findElement(arr, func) { 31 | if (arr.length > 0 && !func(arr[0])) { 32 | return findElement(arr.slice(1), func); 33 | } else { 34 | return arr[0]; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of positive integers nums and a positive integer target, return the minimal length of a 3 | subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. 4 | 5 | Example 1: 6 | 7 | Input: target = 7, nums = [2,3,1,2,4,3] 8 | Output: 2 9 | Explanation: The subarray [4,3] has the minimal length under the problem constraint. 10 | */ 11 | 12 | // Leetcode 209 13 | class Solution { 14 | public: 15 | int minSubArrayLen(int target, vector& nums) { 16 | int sum = 0; 17 | int len = INT_MAX; 18 | 19 | int left = 0, right = 0; 20 | 21 | while(right < nums.size()) { 22 | sum += nums[right]; 23 | if(sum >= target) { 24 | while(sum >= target) { 25 | sum -= nums[left++]; 26 | if(sum < target) { 27 | len = min(len, right-left+2); 28 | } 29 | } 30 | } 31 | right++; 32 | } 33 | 34 | return len == INT_MAX ? 0 : len; 35 | } 36 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode1.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number} target 6 | * @return {number[]} 7 | */ 8 | const twoSum = (nums, target) => { 9 | for (let i = 0; i < nums.length; i++) { 10 | const numTofind = target - nums[i]; 11 | for (let j = i + 1; j < nums.length; j++) { 12 | if (numTofind === nums[j]) { 13 | return [i, j]; 14 | } 15 | } 16 | } 17 | return null; 18 | }; 19 | 20 | let arr = [1, 2, 5, 3, 6]; 21 | console.log(twoSum(arr, 8)); // this case fails to find all the solution as 5+3=8 as well 22 | 23 | 24 | // more efficient solution using HashMap 25 | 26 | const twoSumHash = (nums, target) => { 27 | const map = {}; 28 | for (let i = 0; i < nums.length; i++) { 29 | const currentVal = map[nums[i]]; 30 | if (currentVal >= 0) return [currentVal, i]; 31 | else { 32 | const numToFind = target - nums[i]; 33 | map[numToFind] = i; 34 | } 35 | } 36 | return null; 37 | }; 38 | 39 | console.log(twoSumHash(arr, 8)); -------------------------------------------------------------------------------- /questions/leetcode/leetcode23.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode[]} lists 10 | * @return {ListNode} 11 | */ 12 | var mergeKLists = function (lists) { 13 | // Return early if no ListNodes were supplied 14 | if (!lists.length) return null; 15 | 16 | // Loop through the supplied ListNodes 17 | for (let i = 1; i < lists.length; i++) { 18 | // Merge each ListNode with the first 19 | lists[0] = merge(lists[0], lists[i]); 20 | } 21 | 22 | // Return the merged ListNode 23 | return lists[0]; 24 | }; 25 | 26 | var merge = function (l1, l2) { 27 | // If either list is empty, return the other list's node 28 | if (l1 == null) return l2; 29 | if (l2 == null) return l1; 30 | 31 | // If l1 is lower 32 | if (l1.val < l2.val) { 33 | l1.next = merge(l1.next, l2); 34 | return l1; 35 | } 36 | // If l2 is lower 37 | else { 38 | l2.next = merge(l1, l2.next); 39 | return l2; 40 | } 41 | }; -------------------------------------------------------------------------------- /Data structures/linkedlist/Trie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Trie{ 5 | bool endmark; 6 | Trie *next[27]; 7 | Trie() 8 | { 9 | endmark=false; 10 | for(int i=0;i<26;i++) 11 | { 12 | next[i]=NULL; 13 | } 14 | } 15 | }; 16 | Trie *root = new Trie(); 17 | void add(string s) 18 | { 19 | Trie *cur =root; 20 | for(int i=0;inext[ch]==NULL) 24 | { 25 | cur->next[ch]=new Trie(); 26 | } 27 | cur=cur->next[ch]; 28 | } 29 | cur->endmark=true; 30 | } 31 | 32 | bool Search(string s) 33 | { 34 | Trie *cur = root; 35 | for(int i=0;inext[ch]==NULL) 39 | return false; 40 | cur=cur->next[ch]; 41 | } 42 | return cur->endmark; 43 | } 44 | 45 | int main() 46 | { 47 | 48 | add("abu"); 49 | add("abbu"); 50 | add("obu"); 51 | if(Search("abddu")) 52 | cout<<"abu is found"< a - b); 11 | let result = []; 12 | 13 | for (let i = 0; i < nums.length - 2; i++) { 14 | if (i > 0 && nums[i] === nums[i - 1]) continue; 15 | 16 | let start = i + 1; 17 | let end = nums.length - 1; 18 | 19 | while (start < end) { 20 | if (nums[i] + nums[start] + nums[end] === 0) { 21 | result.push([nums[i], nums[start], nums[end]]); 22 | 23 | while (start < end && nums[start] === nums[start + 1]) { 24 | start++; 25 | } 26 | start++; 27 | 28 | while (start < end && nums[end] === nums[end - 1]) { 29 | end--; 30 | } 31 | end--; 32 | } 33 | else if (nums[i] + nums[start] + nums[end] > 0) end--; 34 | else start++; 35 | } 36 | } 37 | return result; 38 | }; 39 | 40 | console.log(threeSum([-1, 0, 1, 2, -1, 4])); -------------------------------------------------------------------------------- /questions/leetcode/leetcode73.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | var setZeroes = function (matrix) { 6 | let row = matrix.length; 7 | let row0 = false; 8 | let col0 = false; 9 | let column = matrix[0].length; 10 | for (let i = 0; i < row; i++) { 11 | for (let j = 0; j < column; j++) { 12 | if (matrix[i][j] === 0) { 13 | if (i === 0) { 14 | row0 = true; 15 | } 16 | if (j === 0) { 17 | col0 = true; 18 | } 19 | 20 | matrix[i][0] = 0; 21 | matrix[0][j] = 0; 22 | } 23 | } 24 | } 25 | 26 | for (let i = 1; i < row; i++) { 27 | for (let j = 1; j < column; j++) { 28 | if (matrix[i][0] === 0 || matrix[0][j] === 0) { 29 | matrix[i][j] = 0; 30 | } 31 | } 32 | } 33 | 34 | if (row0) { 35 | for (let j = 0; j < column; j++) { 36 | matrix[0][j] = 0; 37 | } 38 | } 39 | if (col0) { 40 | for (let i = 0; i < row; i++) { 41 | matrix[i][0] = 0; 42 | } 43 | } 44 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode36.js: -------------------------------------------------------------------------------- 1 | var isValidSudoku = function (board) { 2 | for (let i = 0; i < 9; i++) { 3 | for (let j = 0; j < 9; j++) { 4 | if (board[i][j] !== ".") { 5 | var val = board[i][j]; 6 | if (i < 8) { 7 | for (let t = i + 1; t < 9; t++) { 8 | if (board[t][j] === val) { 9 | return false; 10 | } 11 | } 12 | } 13 | if (j < 8) { 14 | for (let t = j + 1; t < 9; t++) { 15 | if (board[i][t] === val) { 16 | return false; 17 | } 18 | } 19 | } 20 | if (i % 3 < 2) { 21 | for (let p = i + 1; p < i - i % 3 + 3; p++) { 22 | for (let q = j - j % 3; q < j - j % 3 + 3; q++) { 23 | if (q !== j && board[p][q] === val) { 24 | return false; 25 | } 26 | } 27 | } 28 | } 29 | 30 | } 31 | } 32 | } 33 | return true; 34 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/mlrs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. 3 | 4 | Example 1: 5 | Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 6 | Output: 3 7 | Explanation: The repeated subarray with maximum length is [3,2,1]. 8 | */ 9 | 10 | // Leetcode 718 11 | class Solution { 12 | public: 13 | int findLength(vector& nums1, vector& nums2) { 14 | int m = nums1.size(); 15 | int n = nums2.size(); 16 | int ans = 0; 17 | vector> dp(m, vector(n)); 18 | 19 | for(int i=0;i { // O(n^2) 13 | for (let i = 0; i < input.length; i++) { 14 | for (let j = i + 1; j < input.length; j++) { 15 | if (input[i] === input[j]) return input[i]; 16 | } 17 | } 18 | return -1; 19 | }; 20 | 21 | // console.log(firstRecurringCharacter([1, 5, 1, 1, 3, 5, 1, 2, 4])); 22 | 23 | 24 | const hashMethod = (arr) => { //O(n) 25 | let map = {}; 26 | for (let i = 0; i < arr.length; i++) { 27 | if (map[arr[i]] !== undefined) { 28 | return arr[i]; 29 | } else { 30 | map[arr[i]] = i; 31 | } 32 | console.log(map); 33 | } 34 | // console.log(map); 35 | return -1; 36 | }; 37 | 38 | // console.log(hashMethod([1, 5, 5, 1, 3, 5, 1, 2, 4])); 39 | console.log(hashMethod([2, 5, 5, 2, 3, 5, 1, 2, 4])); 40 | 41 | //Bonus... What if we had this: 42 | // [2,5,5,2,3,5,1,2,4] 43 | // return 5 because the pairs are before 2,2 -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/decode-ways.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A message containing letters from A-Z can be encoded into numbers using the following mapping: 3 | 4 | 'A' -> "1" 5 | 'B' -> "2" 6 | ... 7 | 'Z' -> "26" 8 | To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: 9 | 10 | "AAJF" with the grouping (1 1 10 6) 11 | "KJF" with the grouping (11 10 6) 12 | Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". 13 | 14 | Given a string s containing only digits, return the number of ways to decode it. 15 | 16 | The test cases are generated so that the answer fits in a 32-bit integer. 17 | */ 18 | 19 | // Leetcode 91 20 | class Solution { 21 | public: 22 | int numDecodings(string s) { 23 | int n = s.length(); 24 | int dp[n+1]; 25 | dp[n] = 1; 26 | 27 | for(int i=n-1;i>=0;i--) { 28 | if(s[i] == '0') dp[i] = 0; 29 | else { 30 | dp[i] = dp[i+1]; 31 | if(i= board.length || c >= board[0].length) return; // out of boundary 11 | if (board[r][c] != word[i]) return; // wrong character 12 | if (i == word.length - 1) { // got to the end means we found a correct path 13 | result = true; 14 | return; 15 | } 16 | board[r][c] = null; // mark our path so we dont go back and forth 17 | // try all directions 18 | check(r + 1, c, i + 1); 19 | check(r - 1, c, i + 1); 20 | check(r, c + 1, i + 1); 21 | check(r, c - 1, i + 1); 22 | board[r][c] = word[i]; // reset our board , very important 23 | } 24 | }; 25 | 26 | for (let i = 0; i < board.length; i++) { 27 | for (let j = 0; j < board[0].length; j++) { 28 | if (board[i][j] == word[0]) { 29 | check(i, j, 0); 30 | if (result) return result; 31 | } 32 | } 33 | } 34 | 35 | return result; 36 | }; -------------------------------------------------------------------------------- /heap/merge-k-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. 3 | Merge all the linked-lists into one sorted linked-list and return it. 4 | 5 | Example 1: 6 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 7 | Output: [1,1,2,3,4,4,5,6] 8 | Explanation: The linked-lists are: 9 | [ 10 | 1->4->5, 11 | 1->3->4, 12 | 2->6 13 | ] 14 | merging them into one sorted list: 15 | 1->1->2->3->4->4->5->6 16 | */ 17 | 18 | // Leetcode 23 19 | class Solution { 20 | public: 21 | ListNode* mergeKLists(vector& lists) { 22 | priority_queue, vector>, greater>> pq; 23 | 24 | for(auto l:lists) { 25 | ListNode* temp = l; 26 | while(temp!=NULL) { 27 | pq.push({temp->val, temp}); 28 | temp = temp->next; 29 | } 30 | } 31 | 32 | if(pq.size() == 0) return NULL; 33 | 34 | ListNode* head = pq.top().second; 35 | pq.pop(); 36 | ListNode* cur = head; 37 | 38 | while(!pq.empty()) { 39 | cur->next = pq.top().second; 40 | cur = cur->next; 41 | pq.pop(); 42 | } 43 | 44 | return head; 45 | } 46 | }; -------------------------------------------------------------------------------- /questions/dynamic_programming/Tabular/coin-change.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 3 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 4 | You may assume that you have an infinite number of each kind of coin. 5 | 6 | Input: coins = [1,2,5], amount = 11 7 | Output: 3 8 | Explanation: 11 = 5 + 5 + 1 9 | */ 10 | 11 | // Leetcode 322 12 | class Solution { 13 | public: 14 | int coinChange(vector& coins, int amount) { 15 | int n = coins.size(); 16 | int dp[n+1][amount+1]; 17 | 18 | for(int i=0;i<=n;i++) { 19 | for(int j=0;j<=amount;j++) { 20 | dp[i][j] = i==0 ? INT_MAX - 1 : 0; 21 | } 22 | } 23 | 24 | for(int i=1;i<=n;i++) { 25 | for(int j=1;j<=amount;j++) { 26 | if(j < coins[i-1]) { 27 | dp[i][j] = dp[i-1][j]; 28 | } else { 29 | dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i-1]] + 1); 30 | } 31 | } 32 | } 33 | 34 | return dp[n][amount] == INT_MAX - 1 ? -1 : dp[n][amount]; 35 | } 36 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode30.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/substring-with-concatenation-of-all-words/ 2 | 3 | /** 4 | * @param {string} s 5 | * @param {string[]} words 6 | * @return {number[]} 7 | */ 8 | var findSubstring = function (s, words) { 9 | let n = words.length, 10 | wordLen = words[0].length, 11 | stringLen = s.length, 12 | map = new Map(), 13 | result = []; 14 | //basic test cases 15 | if (stringLen < n * wordLen) return []; 16 | if (s == words.join("")) return [0]; 17 | // creating the hashmap 18 | for (let i = 0, j; i < n; i++) { 19 | if (map.get(words[i]) == undefined) { 20 | j = -1; 21 | while ((j = words.indexOf(words[i], j + 1)) >= 0) 22 | map.set(words[i], map.get(words[i]) + 1 || 1); 23 | } 24 | } 25 | 26 | for (let i = 0, j, ch, mapCopy; stringLen - i >= n * wordLen; i++) { 27 | j = i; 28 | ch = s.slice(j, j + wordLen); 29 | mapCopy = new Map(map); 30 | while (j - i <= n * wordLen && mapCopy.get(ch) > 0) { 31 | mapCopy.set(ch, mapCopy.get(ch) - 1); 32 | j += wordLen; 33 | ch = s.slice(j, j + wordLen); 34 | } 35 | if (j - i == n * wordLen) result.push(i); 36 | } 37 | return result; 38 | }; -------------------------------------------------------------------------------- /questions/mergeSortedArray.js: -------------------------------------------------------------------------------- 1 | // merge two sorted arrays in one 2 | 3 | 4 | /* my solution */ 5 | const merge = (arr1, arr2) => { 6 | let res = []; 7 | for (let i = 0; i < arr1.length; i++) { 8 | res.push(arr1[i]); 9 | res.push(arr2[i]); 10 | } 11 | return res.sort((a, b) => a - b); 12 | }; 13 | 14 | console.log(merge([1, 2], [3])); 15 | 16 | 17 | /* optimal solution */ 18 | function mergeSortedArrays(array1, array2) { 19 | const mergedArray = []; 20 | let array1Item = array1[0]; 21 | let array2Item = array2[0]; 22 | let i = 1; 23 | let j = 1; 24 | 25 | //We should actually move these 2 if statements to line 2 so that we do the checks before we do assignments in line 3 and 4! 26 | if (array1.length === 0) { 27 | return array2; 28 | } 29 | if (array2.length === 0) { 30 | return array1; 31 | } 32 | 33 | while (array1Item || array2Item) { 34 | if (array2Item === undefined || array1Item < array2Item) { 35 | mergedArray.push(array1Item); 36 | array1Item = array1[i]; 37 | i++; 38 | } 39 | else { 40 | mergedArray.push(array2Item); 41 | array2Item = array2[j]; 42 | j++; 43 | } 44 | } 45 | return mergedArray; 46 | } 47 | -------------------------------------------------------------------------------- /questions/queue_using_stack.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/implement-queue-using-stacks/description/ 2 | 3 | /** 4 | * Initialize your data structure here. 5 | */ 6 | var MyQueue = function () { 7 | this.stack = []; 8 | }; 9 | 10 | /** 11 | * Push element x to the back of queue. 12 | * @param {number} x 13 | * @return {void} 14 | */ 15 | MyQueue.prototype.push = function (x) { 16 | this.stack.push(x); 17 | }; 18 | 19 | /** 20 | * Removes the element from in front of queue and returns that element. 21 | * @return {number} 22 | */ 23 | MyQueue.prototype.pop = function () { 24 | if (!this.stack.length) return null; 25 | return this.stack.shift(); 26 | }; 27 | 28 | /** 29 | * Get the front element. 30 | * @return {number} 31 | */ 32 | MyQueue.prototype.peek = function () { 33 | if (!this.stack.length) return null; 34 | return this.stack[0]; 35 | }; 36 | 37 | /** 38 | * Returns whether the queue is empty. 39 | * @return {boolean} 40 | */ 41 | MyQueue.prototype.empty = function () { 42 | return this.stack.length === 0; 43 | }; 44 | 45 | /** 46 | * Your MyQueue object will be instantiated and called as such: 47 | * var obj = new MyQueue() 48 | * obj.push(x) 49 | * var param_2 = obj.pop() 50 | * var param_3 = obj.peek() 51 | * var param_4 = obj.empty() 52 | */ -------------------------------------------------------------------------------- /Big-O/O(n).js: -------------------------------------------------------------------------------- 1 | const arr = ['saif']; 2 | const large = new Array(10000).fill('saif'); 3 | 4 | const findName = arr => { 5 | let t0 = performance.now(); 6 | for (let i = 0; i < arr.length; i++) { 7 | if (arr[i] === 'saif') { 8 | console.log('found the name'); 9 | break; // this is to so that the loop does not run for arr.length times 10 | } 11 | } 12 | let t1 = performance.now(); 13 | let time = t1 - t0; 14 | console.log(`took ${ time } miliseconds`); 15 | }; 16 | 17 | // alternatively we can write in ES6 version 18 | const findNameAlt = arr => { 19 | arr.forEach(element => console.log(element)); 20 | }; 21 | 22 | // * O(n) --> Linear time 23 | findName(large); 24 | findNameAlt(large); 25 | 26 | 27 | 28 | /* 29 | ! another example of rule 2 30 | */ 31 | function printFirstItemThenFirstHalfThenSayHi100Times(items) { 32 | console.log(items[0]); 33 | 34 | var middleIndex = Math.floor(items.length / 2); 35 | var index = 0; 36 | 37 | while (index < middleIndex) { 38 | console.log(items[index]); 39 | index++; 40 | } 41 | 42 | for (var i = 0; i < 100; i++) { 43 | console.log('hi'); 44 | } 45 | } 46 | 47 | /* 48 | * o(1 + n/2 + 100) 49 | * = O(n/2 + 101) 50 | * = O(n/2) 51 | * = O(n) 52 | */ 53 | 54 | -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/merge_sort.js: -------------------------------------------------------------------------------- 1 | // TC = O(nlogn) 2 | 3 | const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]; 4 | 5 | function mergeSort(array) { 6 | if (array.length === 1) { 7 | return array; 8 | } 9 | // Split Array in into right and left 10 | const length = array.length; 11 | const middle = Math.floor(length / 2); 12 | const left = array.slice(0, middle); 13 | const right = array.slice(middle); 14 | // console.log('left:', left); 15 | // console.log('right:', right); 16 | 17 | 18 | return merge( 19 | mergeSort(left), 20 | mergeSort(right) 21 | ); 22 | } 23 | 24 | function merge(left, right) { 25 | const result = []; 26 | let leftIndex = 0; 27 | let rightIndex = 0; 28 | while (leftIndex < left.length && 29 | rightIndex < right.length) { 30 | if (left[leftIndex] < right[rightIndex]) { 31 | result.push(left[leftIndex]); 32 | leftIndex++; 33 | } else { 34 | result.push(right[rightIndex]); 35 | rightIndex++; 36 | } 37 | } 38 | // console.log(left, right) 39 | return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); 40 | } 41 | 42 | 43 | const answer = mergeSort(numbers); 44 | console.log(answer); 45 | -------------------------------------------------------------------------------- /algorithms/sorting/comparison sort/Divide&Conquer/quick_sort.js: -------------------------------------------------------------------------------- 1 | // TC = O(nlogn) 2 | 3 | const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]; 4 | 5 | function quickSort(array, left, right) { 6 | const len = array.length; 7 | let pivot; 8 | let partitionIndex; 9 | 10 | if (left < right) { 11 | pivot = right; 12 | partitionIndex = partition(array, pivot, left, right); 13 | 14 | //sort left and right 15 | quickSort(array, left, partitionIndex - 1); 16 | quickSort(array, partitionIndex + 1, right); 17 | } 18 | return array; 19 | } 20 | 21 | function partition(array, pivot, left, right) { 22 | let pivotValue = array[pivot]; 23 | let partitionIndex = left; 24 | 25 | for (let i = left; i < right; i++) { 26 | if (array[i] < pivotValue) { 27 | swap(array, i, partitionIndex); 28 | partitionIndex++; 29 | } 30 | } 31 | swap(array, right, partitionIndex); 32 | return partitionIndex; 33 | } 34 | 35 | function swap(array, firstIndex, secondIndex) { 36 | var temp = array[firstIndex]; 37 | array[firstIndex] = array[secondIndex]; 38 | array[secondIndex] = temp; 39 | } 40 | 41 | //Select first and last index as 2nd and 3rd parameters 42 | quickSort(numbers, 0, numbers.length - 1); 43 | console.log(numbers); -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/word-break.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | Note that the same word in the dictionary may be reused multiple times in the segmentation. 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "leetcode", wordDict = ["leet","code"] 9 | Output: true 10 | Explanation: Return true because "leetcode" can be segmented as "leet code". 11 | */ 12 | 13 | // Leetcode 139 14 | class Solution { 15 | public: 16 | int dp[301]; 17 | int helper(int position, string s, unordered_set& wordSet) { 18 | if(position == s.size()) return 1; 19 | if(dp[position] != -1) return dp[position]; 20 | string temp; 21 | for(int i=position;i& wordDict) { 31 | memset(dp, -1, sizeof dp); 32 | unordered_set wordSet; 33 | for(string word:wordDict) { 34 | wordSet.insert(word); 35 | } 36 | return helper(0, s, wordSet); 37 | } 38 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode149.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} points 3 | * @return {number} 4 | */ 5 | 6 | var maxPoints = function (points) { 7 | if (points.length === 1) { 8 | return 1; 9 | } 10 | 11 | const slopes = {}; 12 | let dx, dy; 13 | let xbase, ybase; 14 | let xref, yref, key; 15 | const INFINITE_SLOPE = 'infinite'; 16 | 17 | for (let i = 0; i < points.length; i++) { 18 | [xbase, ybase] = points[i]; 19 | 20 | for (let j = i + 1; j < points.length; j++) { 21 | 22 | [xref, yref] = points[j]; 23 | 24 | if (xref === xbase) { 25 | key = `x = ${ xref }`; 26 | 27 | } else { 28 | dx = xref - xbase; 29 | dy = yref - ybase; 30 | 31 | let m = dy / dx; 32 | let c = yref - m * xref; 33 | 34 | m = m.toFixed(4); 35 | c = c.toFixed(4); 36 | 37 | key = `y = ${ m }x + ${ c }`; 38 | } 39 | 40 | slopes[key] || (slopes[key] = 0); 41 | slopes[key]++; 42 | } 43 | } 44 | 45 | const maxPairs = Math.max(...Object.values(slopes)); 46 | 47 | if (maxPairs === 2) { 48 | return 2; 49 | } 50 | 51 | for (let i = 1; i <= 300; i++) { 52 | if (i * (i - 1) / 2 === maxPairs) { 53 | return i; 54 | } 55 | } 56 | 57 | return 0; 58 | }; -------------------------------------------------------------------------------- /questions/two_pointers/partition-labels.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. 3 | Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. 4 | Return a list of integers representing the size of these parts. 5 | 6 | Example 1: 7 | Input: s = "ababcbacadefegdehijhklij" 8 | Output: [9,7,8] 9 | Explanation: 10 | The partition is "ababcbaca", "defegde", "hijhklij". 11 | This is a partition so that each letter appears in at most one part. 12 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 13 | */ 14 | 15 | // Leetcode 763 16 | class Solution { 17 | public: 18 | vector partitionLabels(string s) { 19 | vector ans; 20 | int size = 0; 21 | vector lastIndices(26, 0); 22 | for(int i=0;i { 18 | // let newMap = new Map(); // this is the new method 19 | let map = {}; 20 | for (let i = 0; i < arr1.length; i++) { 21 | if (!map[arr1[i]]) { 22 | const item = arr1[i]; 23 | map[item] = true; 24 | // map.set(arr1[i], true); // this is the new method 25 | } 26 | } 27 | // console.log(map); 28 | for (let j = 0; j < arr2.length; j++) { 29 | if (map[arr2[j]]) { 30 | return true; 31 | } 32 | } 33 | return false; 34 | }; 35 | 36 | console.log(containsItem(array1, array2)); 37 | 38 | // using JS built-in method 39 | 40 | const containsItem2 = (arr1, arr2) => { 41 | return arr1.some(item => arr2.includes(item)); 42 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-two-numbers/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * function ListNode(val, next) { 6 | * this.val = (val===undefined ? 0 : val) 7 | * this.next = (next===undefined ? null : next) 8 | * } 9 | */ 10 | /** 11 | * @param {ListNode} l1 12 | * @param {ListNode} l2 13 | * @return {ListNode} 14 | */ 15 | var addTwoNumbers = function (l1, l2) { 16 | let result = new ListNode(0); 17 | let current = result; 18 | let carry = 0; 19 | // explanation: we set carry to 0, and then we will add the values of l1 and l2 20 | // and then we will add the carry to the result 21 | while (l1 || l2 || carry) { 22 | let sum = carry; 23 | if (l1) { 24 | sum += l1.val; 25 | l1 = l1.next; 26 | // we will add the values of l1 to the sum 27 | // then move on to the next node 28 | } 29 | if (l2) { 30 | sum += l2.val; 31 | l2 = l2.next; 32 | // we will add the values of l2 to the sum 33 | // then move on to the next node 34 | } 35 | carry = Math.floor(sum / 10); 36 | current.next = new ListNode(sum % 10); 37 | // we set the current.next to the new ListNode with the value of sum % 10 38 | // and then we set the current to the current.next 39 | current = current.next; 40 | } 41 | return result.next; 42 | }; -------------------------------------------------------------------------------- /JAVA solutions/linkedlist/CircularLL.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | public class CircularLL { 4 | private Node head; 5 | private Node tail; 6 | 7 | public CircularLL() { 8 | this.head = null; 9 | this.tail = null; 10 | } 11 | 12 | public Node get(int index) { 13 | Node node = head; 14 | for (int i = 0; i < index; i++) { 15 | node = node.next; 16 | } 17 | return node; 18 | } 19 | 20 | public void add(int value) { 21 | Node node = new Node(value); 22 | if (head == null) { 23 | head = node; 24 | tail = node; 25 | } 26 | 27 | tail.next = node; 28 | node.next = head; 29 | tail = node; 30 | } 31 | 32 | public void deleteAt(int index) { 33 | Node temp = get(index); 34 | Node prev = get(index - 1); 35 | 36 | prev.next = temp.next; 37 | } 38 | 39 | 40 | public void printList() { 41 | Node temp = head; 42 | 43 | do { 44 | System.out.print("[" + temp.value + "] => "); 45 | temp = temp.next; 46 | } while (temp != head); 47 | System.out.println("HEAD"); 48 | } 49 | 50 | private class Node { 51 | int value; 52 | Node next; 53 | 54 | public Node(int value) { 55 | this.value = value; 56 | } 57 | 58 | public Node(int value, Node next) { 59 | this.value = value; 60 | this.next = next; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/Kosaraju_algorithm/count_connected_component: -------------------------------------------------------------------------------- 1 | /* 2 | test_00: 3 | connectedComponentsCount({ 4 | 0: [8, 1, 5], 5 | 1: [0], 6 | 5: [0, 8], 7 | 8: [0, 5], 8 | 2: [3, 4], 9 | 3: [2, 4], 10 | 4: [3, 2] 11 | }); // -> 2 12 | 13 | test_01: 14 | connectedComponentsCount({ 15 | 1: [2], 16 | 2: [1,8], 17 | 6: [7], 18 | 9: [8], 19 | 7: [6, 8], 20 | 8: [9, 7, 2] 21 | }); // -> 1 22 | 23 | test_02: 24 | connectedComponentsCount({ 25 | 3: [], 26 | 4: [6], 27 | 6: [4, 5, 7, 8], 28 | 8: [6], 29 | 7: [6], 30 | 5: [6], 31 | 1: [2], 32 | 2: [1] 33 | }); // -> 3 34 | 35 | test_03: 36 | connectedComponentsCount({}); // -> 0 37 | test_04: 38 | connectedComponentsCount({ 39 | 0: [4,7], 40 | 1: [], 41 | 2: [], 42 | 3: [6], 43 | 4: [0], 44 | 6: [3], 45 | 7: [0], 46 | 8: [] 47 | }); // -> 5 48 | */ 49 | 50 | // Depth first recursive approach https://www.youtube.com/watch?v=RpgcYiky7uw (Theory) 51 | const connectedComponentsCount = (graph) => { 52 | const visited = new Set(); 53 | let count = 0; 54 | for (let node in graph) { 55 | if (explore(graph, node, visited) === true) { 56 | count += 1; 57 | } 58 | } 59 | return count; 60 | }; 61 | 62 | 63 | const explore = (graph, current, visited) => { 64 | if (visited.has(String(current))) return false; 65 | 66 | visited.add(String(current)); 67 | 68 | for (let neighbor of graph[current]) { 69 | explore(graph, neighbor, visited); 70 | } 71 | 72 | return true; 73 | }; -------------------------------------------------------------------------------- /Data structures/queues/queue_LL.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor (value) { 3 | this.value = value; 4 | this.next = null; 5 | } 6 | } 7 | 8 | class Queue { 9 | constructor () { 10 | this.first = null; 11 | this.last = null; 12 | this.length = 0; 13 | } 14 | 15 | isEmpty() { 16 | return true; 17 | } 18 | 19 | peek() { 20 | return this.first; 21 | } 22 | 23 | enqueue(value) { 24 | const newNode = new Node(value); 25 | if (this.length === 0) { 26 | this.first = newNode; 27 | this.last = newNode; 28 | } else { 29 | this.last.next = newNode; 30 | this.last = newNode; 31 | } 32 | this.length++; 33 | return this; 34 | } 35 | 36 | dequeue() { 37 | if (!this.first) { 38 | return null; 39 | } 40 | if (this.first === this.last) { 41 | this.last = null; 42 | } 43 | // const holdingPointer = this.first; 44 | this.first = this.first.next; 45 | this.length--; 46 | return this; 47 | } 48 | } 49 | 50 | const myQueue = new Queue(); 51 | myQueue.enqueue('saif'); 52 | myQueue.enqueue('ananna'); 53 | myQueue.enqueue('rafiq'); 54 | 55 | // console.log(myQueue.peek()); 56 | myQueue.dequeue(); // removes the first one 57 | // console.log(myQueue.peek()); 58 | 59 | console.log(myQueue); 60 | 61 | /* FIFO 62 | counter: saif <-- ananna <-- rafiq 63 | */ -------------------------------------------------------------------------------- /Data structures/graphs/graph.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor () { 3 | this.numberOfNodes = 0; 4 | this.adjacentList = {}; 5 | } 6 | addVertex(node) { 7 | this.adjacentList[node] = []; 8 | this.numberOfNodes++; 9 | } 10 | 11 | addEdge(node1, node2) { 12 | //undirected Graph 13 | this.adjacentList[node1].push(node2); 14 | this.adjacentList[node2].push(node1); 15 | } 16 | showConnections() { 17 | const allNodes = Object.keys(this.adjacentList); 18 | for (let node of allNodes) { 19 | let nodeConnections = this.adjacentList[node]; 20 | let connections = ""; 21 | let vertex; 22 | for (vertex of nodeConnections) { 23 | connections += vertex + " "; 24 | } 25 | console.log(node + " --> " + connections); 26 | } 27 | } 28 | } 29 | 30 | const myGraph = new Graph(); 31 | myGraph.addVertex('0'); 32 | myGraph.addVertex('1'); 33 | myGraph.addVertex('2'); 34 | myGraph.addVertex('3'); 35 | myGraph.addVertex('4'); 36 | myGraph.addVertex('5'); 37 | myGraph.addVertex('6'); 38 | myGraph.addEdge('3', '1'); 39 | myGraph.addEdge('3', '4'); 40 | myGraph.addEdge('4', '2'); 41 | myGraph.addEdge('4', '5'); 42 | myGraph.addEdge('1', '2'); 43 | myGraph.addEdge('1', '0'); 44 | myGraph.addEdge('0', '2'); 45 | myGraph.addEdge('6', '5'); 46 | 47 | myGraph.showConnections(); 48 | //Answer: 49 | // 0-->1 2 50 | // 1-->3 2 0 51 | // 2-->4 1 0 52 | // 3-->1 4 53 | // 4-->3 2 5 54 | // 5-->4 6 55 | // 6-->5 -------------------------------------------------------------------------------- /Data structures/linkedlist/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node{ 5 | int data; 6 | node *next; 7 | }; 8 | node *root=NULL; 9 | void add(int x) 10 | { 11 | if(root==NULL) 12 | { 13 | root=new node(); 14 | root->data=x; 15 | root->next=NULL; 16 | } 17 | else 18 | { 19 | node *cur_node=root; 20 | while(cur_node->next != NULL) //Find the last node 21 | { 22 | cur_node = cur_node->next; //go to next address 23 | } 24 | node *new_node= new node(); 25 | new_node->data=x; 26 | new_node->next=NULL; 27 | cur_node->next=new_node; //link the last node with new node 28 | } 29 | } 30 | 31 | void print() 32 | { 33 | node *cur_node=root; 34 | while(cur_node!=NULL) //loop until you reach null 35 | { 36 | cout<<(cur_node->data)<<" "; 37 | cur_node=cur_node->next; 38 | } 39 | } 40 | 41 | void deleteNode(int x) 42 | { 43 | node *cur_node=root; 44 | node *prev_node=root; 45 | while(cur_node->data!=x) 46 | { 47 | prev_node=cur_node; 48 | cur_node=cur_node->next; 49 | } 50 | if(cur_node==root) 51 | { 52 | node *temp=cur_node; 53 | root=root->next; 54 | delete(temp); 55 | } 56 | else 57 | { 58 | prev_node->next=cur_node->next; 59 | delete(cur_node); 60 | } 61 | } 62 | int main() 63 | { 64 | add(1); 65 | add(11); 66 | add(111); 67 | add(1111); 68 | print(); 69 | deleteNode(111); 70 | print(); 71 | } 72 | -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/unique-paths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 3 | Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 4 | The test cases are generated so that the answer will be less than or equal to 2 * 109. 5 | 6 | Input: m = 3, n = 7 7 | Output: 28 8 | */ 9 | 10 | // Leetcode 62 11 | // recursive memoization 12 | class Solution { 13 | public: 14 | int dp[101][101]; 15 | int findUniquePaths(int m, int n) { 16 | if(m < 0 || n < 0) return 0; 17 | if(m == 1 && n == 1) return 1; 18 | if(dp[m][n] != -1) return dp[m][n]; 19 | return dp[m][n] = findUniquePaths(m-1, n) + findUniquePaths(m, n-1); 20 | } 21 | 22 | int uniquePaths(int m, int n) { 23 | memset(dp, -1, sizeof(dp)); 24 | return findUniquePaths(m, n); 25 | } 26 | }; 27 | 28 | // tabular dp 29 | class Solution { 30 | public: 31 | int uniquePaths(int m, int n) { 32 | int dp[101][101]; 33 | for(int i=0;i& nums, vector& dp, int house) { 19 | if(house >= nums.size()) return 0; 20 | if(dp[house] != -1) return dp[house]; 21 | 22 | return dp[house] = max(nums[house] + helper(nums, dp, house+2), helper(nums, dp, house + 1)); 23 | } 24 | 25 | int rob(vector& nums) { 26 | vector dp(nums.size(), -1); 27 | return helper(nums, dp, 0); 28 | } 29 | }; 30 | 31 | // tabular 32 | class Solution { 33 | public: 34 | int rob(vector& nums) { 35 | int n = nums.size(); 36 | int dp[n+1]; 37 | dp[n] = 0; 38 | for(int i=nums.size()-1;i>=0;i--) { 39 | int sum = nums[i]; 40 | if(i+2 < n) sum += dp[i+2]; 41 | dp[i] = max(sum, dp[i + 1]); 42 | } 43 | return dp[0]; 44 | } 45 | }; -------------------------------------------------------------------------------- /Data structures/stacks/stack_LL.js: -------------------------------------------------------------------------------- 1 | // https://visualgo.net/en/list?slide=1 2 | 3 | class Node { 4 | constructor (value) { 5 | this.value = value; 6 | this.next = null; 7 | } 8 | } 9 | 10 | class Stack { 11 | constructor () { 12 | this.top = null; 13 | this.bottom = null; 14 | this.length = 0; 15 | } 16 | 17 | isEmpty() { 18 | return 0; 19 | } 20 | 21 | peek() { 22 | if (this.isEmpty()) { 23 | return 0; 24 | } 25 | else { 26 | return this.top; 27 | } 28 | } 29 | 30 | push(value) { 31 | const newNode = new Node(value); 32 | if (this.length === 0) { 33 | this.top = newNode; 34 | this.bottom = newNode; 35 | } else { 36 | const holdingPointer = this.top; 37 | this.top = newNode; 38 | this.top.next = holdingPointer; 39 | } 40 | this.length++; 41 | return this; 42 | } 43 | 44 | pop() { 45 | if (!this.top) { 46 | return null; 47 | } 48 | if (this.top === this.bottom) { 49 | this.bottom = null; 50 | } 51 | // const holdingPointer = this.top; 52 | this.top = this.top.next; 53 | this.length--; 54 | return this; 55 | } 56 | 57 | } 58 | 59 | const myStack = new Stack(); 60 | myStack.push(5); 61 | myStack.push(4); 62 | myStack.push(7); 63 | 64 | console.log(myStack.peek()); 65 | myStack.pop(); 66 | 67 | // console.log(myStack); 68 | 69 | /* LIFO 70 | 7 71 | 4 72 | 5 73 | */ -------------------------------------------------------------------------------- /JAVA solutions/strings/LeetcodeString.java: -------------------------------------------------------------------------------- 1 | package leetcode.strings; 2 | 3 | public class LeetcodeString { 4 | //https://leetcode.com/problems/reverse-prefix-of-word/ 5 | public String reversePrefix(String word, char ch) { 6 | StringBuilder sb = new StringBuilder(); 7 | int index = word.indexOf(ch); 8 | sb.append(word.substring(0, index + 1)); 9 | sb.reverse(); 10 | sb.append(word.substring(index + 1)); 11 | return sb.toString(); 12 | 13 | } 14 | 15 | //https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ 16 | public int mostWordsFound(String[] sentences) { 17 | int count = 0; 18 | for (int i = 0; i < sentences.length; i++) { 19 | String[] len = sentences[i].split(" "); 20 | int size = len.length; 21 | if (size > count) count = size; 22 | } 23 | return count; 24 | } 25 | 26 | //https://leetcode.com/problems/circular-sentence/ 27 | public boolean isCircularSentence(String s) { 28 | for (int i = 0; i < s.length(); i++) { 29 | if (s.charAt(i) == ' ') { 30 | if (s.charAt(i - 1) != s.charAt(i + 1)) { 31 | return false; 32 | } 33 | } 34 | } 35 | return s.charAt(0) == s.charAt(s.length() - 1); 36 | } 37 | 38 | //https://leetcode.com/problems/adding-spaces-to-a-string/ 39 | public String addSpaces(String s, int[] spaces) { 40 | StringBuilder sb = new StringBuilder(s); 41 | 42 | for (int i = 0; i < spaces.length; i++) { 43 | sb.insert(spaces[i] + i, " "); 44 | } 45 | 46 | return sb.toString(); 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /heap/data-stream-median.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. 3 | 4 | For example, for arr = [2,3,4], the median is 3. 5 | For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. 6 | Implement the MedianFinder class: 7 | 8 | MedianFinder() initializes the MedianFinder object. 9 | void addNum(int num) adds the integer num from the data stream to the data structure. 10 | double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted. 11 | */ 12 | 13 | // Leetcode 295 14 | class MedianFinder { 15 | priority_queue lower; 16 | priority_queue, greater> upper; 17 | 18 | public: 19 | // Adds a number into the data structure. 20 | void addNum(int num) 21 | { 22 | if(lower.empty()) { 23 | lower.push(num); 24 | } else if(lower.size() == upper.size()) { 25 | if(num < upper.top()) { 26 | lower.push(num); 27 | } else { 28 | upper.push(num); 29 | lower.push(upper.top()); 30 | upper.pop(); 31 | } 32 | } else { 33 | if(num > lower.top()) { 34 | upper.push(num); 35 | } else { 36 | lower.push(num); 37 | upper.push(lower.top()); 38 | lower.pop(); 39 | } 40 | } 41 | } 42 | 43 | // Returns the median of current data stream 44 | double findMedian() 45 | { 46 | return lower.size() == upper.size() ? (lower.top() + upper.top())/2.0 : lower.top(); 47 | } 48 | }; -------------------------------------------------------------------------------- /JAVA solutions/heap/HeapQuestions.java: -------------------------------------------------------------------------------- 1 | package heap; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.PriorityQueue; 6 | 7 | public class HeapQuestions { 8 | public static void main(String[] args) { 9 | int[] arr = {18, 6, 2, 5, 12, 5, 17, 16}; 10 | int[] nearlySorted = {2, 3, 1, 4, 6, 7, 5, 8, 9}; 11 | // System.out.println(kLargestEelm(arr, 3)); 12 | System.out.println(kSortedList(nearlySorted, 2)); 13 | } 14 | 15 | // return k number of items in the list that are largest 16 | public static List kLargestEelm(int[] arr, int k) { 17 | PriorityQueue pq = new PriorityQueue<>(); 18 | List list = new ArrayList<>(); 19 | 20 | for (int i = 0; i < arr.length; i++) { 21 | if (i < k) { 22 | pq.add(arr[i]); 23 | } else { 24 | if (arr[i] > pq.peek()) { 25 | pq.remove(); 26 | pq.add(arr[i]); 27 | } 28 | } 29 | } 30 | while (pq.size() > 0) { 31 | list.add(pq.remove()); 32 | } 33 | return list; 34 | } 35 | 36 | public static List kSortedList(int[] arr, int k) { 37 | PriorityQueue pq = new PriorityQueue<>(); 38 | List list = new ArrayList<>(); 39 | 40 | for (int i = 0; i <= k; i++) { 41 | pq.add(arr[i]); 42 | } 43 | 44 | for (int i = k + 1; i < arr.length; i++) { 45 | list.add(pq.remove()); 46 | pq.add(arr[i]); 47 | } 48 | 49 | while (pq.size() > 0) { 50 | list.add(pq.remove()); 51 | } 52 | return list; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /questions/leetcode/leetcode37.js: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/sudoku-solver/ 2 | // Hard 3 | 4 | /** 5 | * @param {character[][]} board 6 | * @return {void} Do not return anything, modify board in-place instead. 7 | */ 8 | var solveSudoku = function (board) { 9 | solver(board); 10 | }; 11 | 12 | const solver = board => { 13 | for (let i = 0; i < 9; i++) { 14 | for (let j = 0; j < 9; j++) { 15 | if (board[i][j] === ".") { 16 | let char = "1"; 17 | while (+char <= 9) { 18 | if (isValidSudoku(i, j, board, char)) { 19 | board[i][j] = char; 20 | if (solver(board)) { 21 | return true; 22 | } else { 23 | board[i][j] = "."; 24 | } 25 | } 26 | char = (+char + 1).toString(); 27 | } 28 | return false; 29 | } 30 | } 31 | } 32 | return true; 33 | }; 34 | 35 | const isValidSudoku = (row, col, board, char) => { 36 | for (let i = 0; i < 9; i++) { 37 | if (board[row][i] == char) { 38 | return false; 39 | } 40 | } 41 | 42 | for (let i = 0; i < 9; i++) { 43 | if (board[i][col] == char) { 44 | return false; 45 | } 46 | } 47 | 48 | const x = ~~(row / 3) * 3; 49 | const y = ~~(col / 3) * 3; 50 | for (let i = 0; i < 3; i++) { 51 | for (let j = 0; j < 3; j++) { 52 | if (board[x + i][y + j] == char) { 53 | return false; 54 | } 55 | } 56 | } 57 | 58 | return true; 59 | }; -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/largest_connected_component/largest_connected_component.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, largestComponent, that takes in the adjacency list of an undirected graph. 3 | The function should return the size of the largest connected component in the graph. 4 | 5 | test_00: 6 | largestComponent({ 7 | 0: ['8', '1', '5'], 8 | 1: ['0'], 9 | 5: ['0', '8'], 10 | 8: ['0', '5'], 11 | 2: ['3', '4'], 12 | 3: ['2', '4'], 13 | 4: ['3', '2'] 14 | }); // -> 4 15 | 16 | test_01: 17 | largestComponent({ 18 | 1: ['2'], 19 | 2: ['1','8'], 20 | 6: ['7'], 21 | 9: ['8'], 22 | 7: ['6', '8'], 23 | 8: ['9', '7', '2'] 24 | }); // -> 6 25 | 26 | test_02: 27 | largestComponent({ 28 | 3: [], 29 | 4: ['6'], 30 | 6: ['4', '5', '7', '8'], 31 | 8: ['6'], 32 | 7: ['6'], 33 | 5: ['6'], 34 | 1: ['2'], 35 | 2: ['1'] 36 | }); // -> 5 37 | 38 | test_03: 39 | largestComponent({}); // -> 0 40 | test_04: 41 | largestComponent({ 42 | 0: ['4','7'], 43 | 1: [], 44 | 2: [], 45 | 3: ['6'], 46 | 4: ['0'], 47 | 6: ['3'], 48 | 7: ['0'], 49 | 8: [] 50 | }); // -> 3 51 | */ 52 | 53 | // depth first 54 | const largestComponent = (graph) => { 55 | const visited = new Set(); 56 | let largest = 0; 57 | 58 | for (let node in graph) { 59 | const size = exploreSize(graph, node, visited); 60 | if (size > largest) largest = size; 61 | } 62 | 63 | return largest; 64 | }; 65 | 66 | const exploreSize = (graph, node, visited) => { 67 | if (visited.has(node)) return 0; 68 | 69 | visited.add(node); 70 | 71 | let size = 1; 72 | for (let neighbor of graph[node]) { 73 | size += exploreSize(graph, neighbor, visited); 74 | } 75 | 76 | return size; 77 | }; -------------------------------------------------------------------------------- /questions/leetcode/leetcode2367.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-arithmetic-triplets/description/ 2 | 3 | // initial brute force solution using 3 loops 4 | /** 5 | * @param {number[]} nums 6 | * @param {number} diff 7 | * @return {number} 8 | */ 9 | var arithmeticTriplets = function (nums, diff) { 10 | let count = 0; 11 | for (let i = 0; i < nums.length; i++) { 12 | for (let j = i + 1; j < nums.length; j++) { 13 | for (let k = j + 1; k < nums.length; k++) { 14 | if (nums[j] - nums[i] === diff && nums[k] - nums[j] === diff) { 15 | count++; 16 | } 17 | } 18 | } 19 | } 20 | return count; 21 | }; 22 | 23 | // optimized solution 24 | var arithmeticTripletsOptimized = function (nums, diff) { 25 | let count = 0; 26 | for (let num of nums) { 27 | if (nums.includes(num + diff) && nums.includes(num + diff * 2)) { 28 | count++; 29 | } 30 | } 31 | return count; 32 | }; 33 | 34 | var arithmeticTripletsOptimized2 = function (nums, diff) { 35 | let count = 0; 36 | for (let i = nums.length - 1; i > 0; i--) { 37 | if (nums.includes(nums[i] - diff) && nums.includes(nums[i] - diff * 2)) { 38 | count++; 39 | } 40 | } 41 | return count; 42 | }; 43 | 44 | // Set solution 45 | const arithmeticTripletsSet = (nums, diff) => { 46 | let count = 0; 47 | const set = new Set(nums); 48 | 49 | for (let i = nums.length - 1; i > 0; i--) { 50 | if (set.has(nums[i] - diff) && set.has(nums[i] - diff * 2)) { 51 | count++; 52 | } 53 | } 54 | return count; 55 | 56 | }; 57 | 58 | const nums = [4, 5, 6, 7, 8, 9], diff = 2; 59 | 60 | console.log(arithmeticTripletsSet(nums, diff)); 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/DisjointSetUnion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ll long long 4 | #define pb push_back 5 | #define eps 1e-9 6 | #define ff first 7 | #define ss second 8 | #define pi acos(-1) 9 | #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 10 | #define Precision(x) cout.setf(ios::fixed); cout.precision(x); 11 | 12 | using namespace std; 13 | typedef long double ld; 14 | inline int nxt(){int aaa;scanf("%d",&aaa);return aaa;} 15 | inline ll lxt(){ll aaa;scanf("%lld",&aaa);return aaa;} 16 | #ifdef ARnAb 17 | #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) 18 | template < typename Arg1 > 19 | void __f(const char* name, Arg1&& arg1){ 20 | cerr << name << " is " << arg1 << std::endl; 21 | } 22 | template < typename Arg1, typename... Args> 23 | void __f(const char* names, Arg1&& arg1, Args&&... args){ 24 | const char* comma = strchr(names+1, ','); 25 | cerr.write(names, comma - names) << " is " << arg1 <<" "; 26 | __f(comma+1, args...); 27 | } 28 | #else 29 | #define debug(...) 30 | #endif 31 | ///******************************************START****************************************** 32 | int cs=0; 33 | int par[100005]; 34 | void DSU() 35 | { 36 | for(int i=1;i<=100;i++) 37 | { 38 | par[i]=i; 39 | } 40 | 41 | } 42 | void mergeSet(int x, int y){ 43 | par[y]=x; 44 | } 45 | int findUnion(int x) 46 | { 47 | if(par[x]==x) return x; 48 | return findUnion(par[x]); 49 | } 50 | void solve() 51 | { 52 | DSU(); 53 | for(int i=0;i<10;i++){ 54 | int u=nxt(),v=nxt(); 55 | if(findUnion(u)!=findUnion(v)){ 56 | mergeSet(u,v); 57 | }else cout<<"ho ek tor ki?"< 3 15 | test_01: 16 | const grid = [ 17 | ['L', 'W', 'W', 'L', 'W'], 18 | ['L', 'W', 'W', 'L', 'L'], 19 | ['W', 'L', 'W', 'L', 'W'], 20 | ['W', 'W', 'W', 'W', 'W'], 21 | ['W', 'W', 'L', 'L', 'L'], 22 | ]; 23 | 24 | islandCount(grid); // -> 4 25 | test_02: 26 | const grid = [ 27 | ['L', 'L', 'L'], 28 | ['L', 'L', 'L'], 29 | ['L', 'L', 'L'], 30 | ]; 31 | 32 | islandCount(grid); // -> 1 33 | test_03: 34 | const grid = [ 35 | ['W', 'W'], 36 | ['W', 'W'], 37 | ['W', 'W'], 38 | ]; 39 | 40 | islandCount(grid); // -> 0 41 | 42 | */ 43 | 44 | // depth first; 45 | const islandCount = (grid) => { 46 | const visited = new Set(); 47 | 48 | let count = 0; 49 | for (let r = 0; r < grid.length; r += 1) { 50 | for (let c = 0; c < grid[0].length; c += 1) { 51 | if (explore(grid, r, c, visited) === true) { 52 | count += 1; 53 | } 54 | } 55 | } 56 | 57 | return count; 58 | }; 59 | 60 | const explore = (grid, r, c, visited) => { 61 | const rowInbounds = 0 <= r && r < grid.length; 62 | const colInbounds = 0 <= c && c < grid[0].length; 63 | if (!rowInbounds || !colInbounds) return false; 64 | 65 | if (grid[r][c] === 'W') return false; 66 | 67 | const pos = r + ',' + c; 68 | if (visited.has(pos)) return false; 69 | visited.add(pos); 70 | 71 | explore(grid, r - 1, c, visited); 72 | explore(grid, r + 1, c, visited); 73 | explore(grid, r, c - 1, visited); 74 | explore(grid, r, c + 1, visited); 75 | return true; 76 | }; -------------------------------------------------------------------------------- /Data structures/trees/tree_sum/tree_sum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, treeSum, that takes in the root of a binary tree that contains number values. 3 | The function should return the total sum of all values in the tree. 4 | 5 | test_00: 6 | 7 | const a = new Node(3); 8 | const b = new Node(11); 9 | const c = new Node(4); 10 | const d = new Node(4); 11 | const e = new Node(-2); 12 | const f = new Node(1); 13 | 14 | a.left = b; 15 | a.right = c; 16 | b.left = d; 17 | b.right = e; 18 | c.right = f; 19 | 20 | 3 21 | / \ 22 | 11 4 23 | / \ \ 24 | 4 -2 1 25 | 26 | treeSum(a); // -> 21 27 | 28 | test_01: 29 | 30 | const a = new Node(1); 31 | const b = new Node(6); 32 | const c = new Node(0); 33 | const d = new Node(3); 34 | const e = new Node(-6); 35 | const f = new Node(2); 36 | const g = new Node(2); 37 | const h = new Node(2); 38 | 39 | a.left = b; 40 | a.right = c; 41 | b.left = d; 42 | b.right = e; 43 | c.right = f; 44 | e.left = g; 45 | f.right = h; 46 | 47 | 1 48 | / \ 49 | 6 0 50 | / \ \ 51 | 3 -6 2 52 | / \ 53 | 2 2 54 | 55 | treeSum(a); // -> 10 56 | 57 | test_02: 58 | 59 | treeSum(null); // -> 0 60 | */ 61 | 62 | // *depth first + recursive 63 | /* 64 | n = number of nodes 65 | Time: O(n) 66 | Space: O(n) 67 | 68 | */ 69 | const treeSumD = (root) => { 70 | if (root === null) return 0; 71 | 72 | return root.val + treeSumD(root.left) + treeSumD(root.right); 73 | }; 74 | 75 | 76 | //*bredth first 77 | /* 78 | n = number of nodes 79 | Time: O(n) 80 | Space: O(n) 81 | Note: this solution should really be considered O(n^2) runtime 82 | because the JavaScript shift() methods runs in O(n). 83 | JavaScript does not have a native queue data structure that is maximally efficient. 84 | */ 85 | const treeSumB = (root) => { 86 | if (root === null) return 0; 87 | 88 | const queue = [root]; 89 | let totalSum = 0; 90 | while (queue.length > 0) { 91 | const node = queue.shift(); 92 | totalSum += node.val; 93 | if (node.left !== null) queue.push(node.left); 94 | if (node.right !== null) queue.push(node.right); 95 | } 96 | 97 | return totalSum; 98 | }; 99 | -------------------------------------------------------------------------------- /Data structures/trees/max_root_to_leaf_path_sum/max_root.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, maxPathSum, 3 | that takes in the root of a binary tree that contains number values. 4 | The function should return the maximum sum of any root to leaf path within the tree. 5 | 6 | You may assume that the input tree is non - empty.; 7 | 8 | test_00: 9 | 10 | const a = new Node(3); 11 | const b = new Node(11); 12 | const c = new Node(4); 13 | const d = new Node(4); 14 | const e = new Node(-2); 15 | const f = new Node(1); 16 | 17 | a.left = b; 18 | a.right = c; 19 | b.left = d; 20 | b.right = e; 21 | c.right = f; 22 | 23 | 3 24 | / \ 25 | 11 4 26 | / \ \ 27 | 4 -2 1 28 | 29 | maxPathSum(a); // -> 18 30 | 31 | test_01: 32 | 33 | const a = new Node(5); 34 | const b = new Node(11); 35 | const c = new Node(54); 36 | const d = new Node(20); 37 | const e = new Node(15); 38 | const f = new Node(1); 39 | const g = new Node(3); 40 | 41 | a.left = b; 42 | a.right = c; 43 | b.left = d; 44 | b.right = e; 45 | e.left = f; 46 | e.right = g; 47 | 48 | 5 49 | / \ 50 | 11 54 51 | / \ 52 | 20 15 53 | / \ 54 | 1 3 55 | 56 | maxPathSum(a); // -> 59 57 | 58 | test_02: 59 | 60 | const a = new Node(-1); 61 | const b = new Node(-6); 62 | const c = new Node(-5); 63 | const d = new Node(-3); 64 | const e = new Node(0); 65 | const f = new Node(-13); 66 | const g = new Node(-1); 67 | const h = new Node(-2); 68 | 69 | a.left = b; 70 | a.right = c; 71 | b.left = d; 72 | b.right = e; 73 | c.right = f; 74 | e.left = g; 75 | f.right = h; 76 | 77 | -1 78 | / \ 79 | -6 -5 80 | / \ \ 81 | -3 0 -13 82 | / \ 83 | -1 -2 84 | 85 | maxPathSum(a); // -> -8 86 | 87 | test_03: 88 | 89 | const a = new Node(42); 90 | 91 | 42 92 | 93 | maxPathSum(a); // -> 42 94 | */ 95 | 96 | 97 | // depth first (recursive) 98 | const maxPathSum = (root) => { 99 | if (root === null) return -Infinity; 100 | if (root.left === null && root.right === null) return root.val; 101 | return root.val + Math.max(maxPathSum(root.left), maxPathSum(root.right)); 102 | }; -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/DFS/dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ll long long 4 | #define pb push_back 5 | #define eps 1e-9 6 | #define pi acos(-1) 7 | #define ff first 8 | #define ss second 9 | #define case cout<<"Case "<<++cs<<": "; 10 | #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 11 | #define Precision(x) cout.setf(ios::fixed); cout.precision(x); 12 | 13 | using namespace std; 14 | typedef long double ld; 15 | #ifdef ARnAb 16 | #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) 17 | template < typename Arg1 > 18 | void __f(const char* name, Arg1&& arg1){ 19 | cerr << name << " is " << arg1 << std::endl; 20 | } 21 | template < typename Arg1, typename... Args> 22 | void __f(const char* names, Arg1&& arg1, Args&&... args){ 23 | const char* comma = strchr(names+1, ','); 24 | cerr.write(names, comma - names) << " is " << arg1 <<" "; 25 | __f(comma+1, args...); 26 | } 27 | #else 28 | #define debug(...) 29 | #endif 30 | ///******************************************START****************************************** 31 | int cs=0; 32 | int node,edge; 33 | vector adj[100005]; 34 | bool vis[100005]; 35 | int dis[100005]; 36 | 37 | void dfs(int sp) 38 | { 39 | vis[sp]=1; 40 | debug(sp); 41 | for(int i=0;i>node; 53 | cin>>edge; 54 | for(int i=0;i>a>>b; 58 | adj[a].pb(b); 59 | //adj[b].pb(a); 60 | } 61 | int fuck,chuda; 62 | cin>>chuda>>fuck; 63 | dfs(chuda); 64 | if(vis[fuck]) cout<<"YES"<>tc; 78 | while(tc--) 79 | solve(); 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /JAVA solutions/stack/LeetcodeStackAndQueue.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class LeetcodeStackAndQueue { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | 11 | //https://leetcode.com/problems/largest-rectangle-in-histogram/description/ 12 | public int largestRectangleArea(int[] h) { 13 | int n = h.length, i = 0, max = 0; 14 | 15 | Stack s = new Stack<>(); 16 | 17 | while (i < n) { 18 | // as long as the current bar is shorter than the last one in the stack 19 | // we keep popping out the stack and calculate the area based on 20 | // the popped bar 21 | while (!s.isEmpty() && h[i] < h[s.peek()]) { 22 | // tricky part is how to handle the index of the left bound 23 | max = Math.max(max, h[s.pop()] * (i - (s.isEmpty() ? 0 : s.peek() + 1))); 24 | } 25 | // put current bar's index to the stack 26 | s.push(i++); 27 | } 28 | 29 | // finally pop out any bar left in the stack and calculate the area based on it 30 | while (!s.isEmpty()) { 31 | max = Math.max(max, h[s.pop()] * (n - (s.isEmpty() ? 0 : s.peek() + 1))); 32 | } 33 | 34 | return max; 35 | } 36 | } 37 | 38 | //https://leetcode.com/problems/implement-queue-using-stacks/description/ 39 | class MyQueue { 40 | private Stack first; 41 | private Stack second; 42 | 43 | public MyQueue() { 44 | first = new Stack<>(); 45 | second = new Stack<>(); 46 | } 47 | 48 | public void push(int x) { 49 | first.push(x); 50 | } 51 | 52 | public int pop() { 53 | while (!first.isEmpty()) { 54 | second.push(first.pop()); 55 | } 56 | int removed = second.pop(); 57 | while (!second.isEmpty()) { 58 | first.push(second.pop()); 59 | } 60 | return removed; 61 | } 62 | 63 | public int peek() { 64 | while (!first.isEmpty()) { 65 | second.push(first.pop()); 66 | } 67 | int peeked = second.peek(); 68 | while (!second.isEmpty()) { 69 | first.push(second.pop()); 70 | } 71 | return peeked; 72 | } 73 | 74 | public boolean empty() { 75 | return first.isEmpty(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /questions/dynamic_programming/Memoization/delete-earn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: 3 | Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1. 4 | Return the maximum number of points you can earn by applying the above operation some number of times. 5 | 6 | Example 1: 7 | Input: nums = [3,4,2] 8 | Output: 6 9 | Explanation: You can perform the following operations: 10 | - Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2]. 11 | - Delete 2 to earn 2 points. nums = []. 12 | You earn a total of 6 points. 13 | */ 14 | 15 | // Leetcode 740 16 | // memoised recursive 17 | class Solution { 18 | public: 19 | int dp[20001]; 20 | int helper(vector& nums, int position) { 21 | if(position >= nums.size()) return 0; 22 | if(dp[position] != -1) return dp[position]; 23 | 24 | int curSum = 0; 25 | int i = position; 26 | while(i < nums.size() && nums[i]==nums[position]) { 27 | curSum += nums[i]; 28 | i++; 29 | } 30 | 31 | while(i < nums.size() && nums[i]==nums[position]+1) { 32 | i++; 33 | } 34 | 35 | return dp[position] = max(curSum + helper(nums, i), helper(nums, position + 1)); 36 | } 37 | 38 | int deleteAndEarn(vector& nums) { 39 | sort(nums.begin(), nums.end()); 40 | memset(dp, -1, sizeof dp); 41 | return helper(nums, 0); 42 | } 43 | }; 44 | 45 | // tabular approach 46 | class Solution { 47 | public: 48 | int deleteAndEarn(vector& nums) { 49 | int dp[nums.size()+1]; 50 | dp[nums.size()] = 0; 51 | sort(nums.begin(), nums.end()); 52 | for(int i=nums.size()-1;i>=0;i--) { 53 | int current = i; 54 | int sum = 0; 55 | int value = nums[i]; 56 | while(current < nums.size() && value == nums[current]) { 57 | sum += nums[current++]; 58 | } 59 | while(current < nums.size() && value+1 == nums[current]) { 60 | current++; 61 | } 62 | dp[i] = max(sum+dp[current], dp[i+1]); 63 | } 64 | return dp[0]; 65 | } 66 | }; -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/minimum_island/minimum_island.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, minimumIsland, that takes in a grid containing Ws and Ls. 3 | W represents water and L represents land. 4 | The function should return the size of the smallest island. An island is a vertically or horizontally connected region of land. 5 | 6 | You may assume that the grid contains at least one island. 7 | 8 | test_00: 9 | const grid = [ 10 | ['W', 'L', 'W', 'W', 'W'], 11 | ['W', 'L', 'W', 'W', 'W'], 12 | ['W', 'W', 'W', 'L', 'W'], 13 | ['W', 'W', 'L', 'L', 'W'], 14 | ['L', 'W', 'W', 'L', 'L'], 15 | ['L', 'L', 'W', 'W', 'W'], 16 | ]; 17 | 18 | minimumIsland(grid); // -> 2 19 | test_01: 20 | const grid = [ 21 | ['L', 'W', 'W', 'L', 'W'], 22 | ['L', 'W', 'W', 'L', 'L'], 23 | ['W', 'L', 'W', 'L', 'W'], 24 | ['W', 'W', 'W', 'W', 'W'], 25 | ['W', 'W', 'L', 'L', 'L'], 26 | ]; 27 | 28 | minimumIsland(grid); // -> 1 29 | test_02: 30 | const grid = [ 31 | ['L', 'L', 'L'], 32 | ['L', 'L', 'L'], 33 | ['L', 'L', 'L'], 34 | ]; 35 | 36 | minimumIsland(grid); // -> 9 37 | test_03: 38 | const grid = [ 39 | ['W', 'W'], 40 | ['L', 'L'], 41 | ['W', 'W'], 42 | ['W', 'L'] 43 | ]; 44 | 45 | minimumIsland(grid); // -> 1 46 | */ 47 | 48 | 49 | // depth first; 50 | const minimumIsland = (grid) => { 51 | const visited = new Set(); 52 | 53 | let minSize = Infinity; 54 | for (let r = 0; r < grid.length; r += 1) { 55 | for (let c = 0; c < grid[0].length; c += 1) { 56 | const size = exploreSize(grid, r, c, visited); 57 | if (size > 0 && size < minSize) { 58 | minSize = size; 59 | } 60 | } 61 | } 62 | 63 | return minSize; 64 | }; 65 | 66 | const exploreSize = (grid, r, c, visited) => { 67 | const rowInbounds = 0 <= r && r < grid.length; 68 | const colInbounds = 0 <= c && c < grid[0].length; 69 | if (!rowInbounds || !colInbounds) return 0; 70 | 71 | if (grid[r][c] === 'W') return 0; 72 | 73 | const pos = r + ',' + c; 74 | if (visited.has(pos)) return 0; 75 | visited.add(pos); 76 | 77 | let size = 1; 78 | size += exploreSize(grid, r - 1, c, visited); 79 | size += exploreSize(grid, r + 1, c, visited); 80 | size += exploreSize(grid, r, c - 1, visited); 81 | size += exploreSize(grid, r, c + 1, visited); 82 | return size; 83 | }; 84 | -------------------------------------------------------------------------------- /JAVA solutions/subsetsAndSequence/Recursion_II.java: -------------------------------------------------------------------------------- 1 | package recursion.subsetsAndSequence; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Recursion_II { 7 | public static void main(String[] args) { 8 | String s = "baaacd"; 9 | String seq = "abc"; 10 | // skipChar("", s, 'c'); 11 | // System.out.println(skipStr("University", "ver")); 12 | // seqOfString("", seq); 13 | System.out.println(seqOfStringRet("", seq)); 14 | System.out.println("total subsets are: " + (int) Math.pow(2, seq.length())); // to find how many subsets there can be of a string 15 | } 16 | 17 | // ******* String ********* 18 | static void skipChar(String ans, String initalStr, char wantToSkip) { 19 | if (initalStr.isEmpty()) { 20 | System.out.println(ans); 21 | return; 22 | } 23 | char ch = initalStr.charAt(0); 24 | if (ch == wantToSkip) { 25 | skipChar(ans, initalStr.substring(1), wantToSkip); 26 | } else { 27 | skipChar(ans + ch, initalStr.substring(1), wantToSkip); 28 | } 29 | } 30 | 31 | static String skipStr(String str, String wantToSkip) { 32 | if (str.isEmpty()) return ""; 33 | 34 | if (str.startsWith(wantToSkip)) { 35 | return skipStr(str.substring(wantToSkip.length()), wantToSkip); 36 | } else { 37 | return str.charAt(0) + skipStr(str.substring(1), wantToSkip); 38 | } 39 | } 40 | 41 | // ******* Subsets & Sequence ********* 42 | static void seqOfString(String p, String up) { // p --> processed || up --> unprocessed 43 | if (up.isEmpty()) { 44 | System.out.println(p); 45 | return; 46 | } 47 | char ch = up.charAt(0); 48 | 49 | seqOfString(p + ch, up.substring(1)); 50 | seqOfString(p, up.substring(1)); 51 | } 52 | 53 | static List seqOfStringRet(String p, String up) { // p --> processed || up --> unprocessed 54 | if (up.isEmpty()) { 55 | List list = new ArrayList<>(); 56 | list.add(p); 57 | return list; 58 | } 59 | char ch = up.charAt(0); 60 | 61 | List left = seqOfStringRet(p + ch, up.substring(1)); 62 | List right = seqOfStringRet(p, up.substring(1)); 63 | 64 | left.addAll(right); 65 | return left; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/hasPath/hasPath.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, hasPath, t 3 | hat takes in an object representing the adjacency list of a directed acyclic graph 4 | and two nodes (src, dst). 5 | The function should return 6 | a boolean indicating whether or not there exists a directed path between the source and destination nodes. 7 | 8 | 9 | test_00: 10 | 11 | const graph = { 12 | f: ['g', 'i'], 13 | g: ['h'], 14 | h: [], 15 | i: ['g', 'k'], 16 | j: ['i'], 17 | k: [] 18 | }; 19 | 20 | hasPath(graph, 'f', 'k'); // true 21 | 22 | test_01: 23 | 24 | const graph = { 25 | f: ['g', 'i'], 26 | g: ['h'], 27 | h: [], 28 | i: ['g', 'k'], 29 | j: ['i'], 30 | k: [] 31 | }; 32 | 33 | hasPath(graph, 'f', 'j'); // false 34 | 35 | test_02: 36 | 37 | const graph = { 38 | f: ['g', 'i'], 39 | g: ['h'], 40 | h: [], 41 | i: ['g', 'k'], 42 | j: ['i'], 43 | k: [] 44 | }; 45 | 46 | hasPath(graph, 'i', 'h'); // true 47 | 48 | test_03: 49 | 50 | const graph = { 51 | v: ['x', 'w'], 52 | w: [], 53 | x: [], 54 | y: ['z'], 55 | z: [], 56 | }; 57 | 58 | hasPath(graph, 'v', 'w'); // true 59 | 60 | test_04: 61 | 62 | const graph = { 63 | v: ['x', 'w'], 64 | w: [], 65 | x: [], 66 | y: ['z'], 67 | z: [], 68 | }; 69 | 70 | hasPath(graph, 'v', 'z'); // false 71 | */ 72 | 73 | 74 | // depth first 75 | /* 76 | n = number of nodes 77 | e = number edges 78 | Time: O(e) 79 | Space: O(n) 80 | */ 81 | const hasPathD = (graph, src, dst) => { 82 | if (src === dst) return true; 83 | 84 | for (let neighbor of graph[src]) { 85 | if (hasPathD(graph, neighbor, dst) === true) { 86 | return true; 87 | } 88 | } 89 | 90 | return false; 91 | }; 92 | 93 | 94 | // breadth first 95 | /* 96 | n = number of nodes 97 | e = number edges 98 | Time: O(e) 99 | Space: O(n) 100 | */ 101 | const hasPathB = (graph, src, dst) => { 102 | const queue = [src]; 103 | 104 | while (queue.length) { 105 | const current = queue.shift(); 106 | if (current === dst) return true; 107 | 108 | for (let neighbor of graph[current]) { 109 | queue.push(neighbor); 110 | } 111 | } 112 | 113 | return false; 114 | }; 115 | 116 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/BFS/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ll long long 4 | #define pb push_back 5 | #define eps 1e-9 6 | #define pi acos(-1) 7 | #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 8 | #define Precision(x) cout.setf(ios::fixed); cout.precision(x); 9 | 10 | using namespace std; 11 | typedef long double ld; 12 | #ifdef ARnAb 13 | #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) 14 | template < typename Arg1 > 15 | void __f(const char* name, Arg1&& arg1){ 16 | cerr << name << " is " << arg1 << std::endl; 17 | } 18 | template < typename Arg1, typename... Args> 19 | void __f(const char* names, Arg1&& arg1, Args&&... args){ 20 | const char* comma = strchr(names+1, ','); 21 | cerr.write(names, comma - names) << " is " << arg1 <<" "; 22 | __f(comma+1, args...); 23 | } 24 | #else 25 | #define debug(...) 26 | #endif 27 | ///******************************************START****************************************** 28 | int node,edge; 29 | bool adj[1000][1000]; 30 | int color[1000]; 31 | int parent[1000]; 32 | int dis[1000]; 33 | 34 | void bfs(int sn) 35 | { 36 | for(int i=0;idq; 44 | dq.push_back(sn); 45 | while(!dq.empty()) 46 | { 47 | int x; 48 | x=dq.front(); 49 | dq.pop_front(); 50 | color[x]=2; 51 | for(int i=0;i>node>>edge; 70 | for(int i=0;i>a>>b; 74 | adj[a][b]=1; 75 | adj[a][b]=1; 76 | } 77 | bfs(0); 78 | } 79 | int main() 80 | { 81 | Fast_Read 82 | Precision(2) 83 | #ifdef ARnAb 84 | double start_time = clock(); 85 | ///freopen ("output.txt","w",stdout); 86 | ///freopen ("input.txt","r",stdin); 87 | #endif 88 | int tc=1; 89 | //cin>>tc; 90 | while(tc--) 91 | solve(); 92 | return 0; 93 | } 94 | 95 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/BFS/bfs2d.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ll long long 4 | #define pb push_back 5 | #define eps 1e-9 6 | #define ff first 7 | #define ss second 8 | #define pi acos(-1) 9 | #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 10 | #define Precision(x) cout.setf(ios::fixed); cout.precision(x); 11 | 12 | using namespace std; 13 | typedef long double ld; 14 | #ifdef ARnAb 15 | #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) 16 | template < typename Arg1 > 17 | void __f(const char* name, Arg1&& arg1){ 18 | cerr << name << " is " << arg1 << std::endl; 19 | } 20 | template < typename Arg1, typename... Args> 21 | void __f(const char* names, Arg1&& arg1, Args&&... args){ 22 | const char* comma = strchr(names+1, ','); 23 | cerr.write(names, comma - names) << " is " << arg1 <<" "; 24 | __f(comma+1, args...); 25 | } 26 | #else 27 | #define debug(...) 28 | #endif 29 | ///******************************************START****************************************** 30 | bool vis[9][9]; 31 | int dis[9][9]; 32 | int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 33 | int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; 34 | void BFS(int spx,int spy) 35 | { 36 | dis[spx][spy]=0; 37 | vis[spx][spy]=1; 38 | queue< pair >q; 39 | q.push({spx,spy}); 40 | while(!q.empty()) 41 | { 42 | pair x=q.front(); 43 | q.pop(); 44 | for(int i=0;i<8;i++) 45 | { 46 | int pp=x.ff+X[i]; 47 | int qq=x.ss+Y[i]; 48 | if(!vis[pp][qq] && pp>=0 && qq>=0 && pp<8 && qq<8) 49 | { 50 | q.push({pp,qq}); 51 | vis[pp][qq]=1; 52 | dis[pp][qq]=dis[x.ff][x.ss]+1; 53 | } 54 | } 55 | } 56 | } 57 | int cs=0; 58 | void solve() 59 | { 60 | string sp,ep; 61 | while(cin>>sp>>ep) 62 | { 63 | int x,y; 64 | x=sp[0]-'a'; 65 | y=sp[1]-'1'; 66 | BFS(x,y); 67 | cout<<"To get from "<>tc; 84 | while(tc--) 85 | solve(); 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /questions/leetcode/leetcode279.js: -------------------------------------------------------------------------------- 1 | function numSquares(n) { 2 | 3 | // General strategy is to build up a memoization array with the smallest amount of squares needed to make the number at each index 4 | // since the only square in the beginning is 1, until we see 4, it's very boring: 5 | // to make 1, we use 1, to make 2 we use two 1's, to make 3, we use three 1's 6 | // mem[1] = 1, d[2] = 2, mem[3] = 3 7 | // initially, mem[4] will also use 1s and end up at 4 8 | // but now we can consider 2^2 too since the inner loop now allows it 9 | // we then compare, is what we have calculated so far better? or using this new square? 10 | // To answer that, we subtract the current square (4) from i (4) and look up in our mem lookup to see how many steps that took 11 | // mem[0] is zero of course, so we end up with Math.min(4, 0 + 1). The 2nd is less of course, so we set mem[4] to 1 12 | 13 | // Our memory lookup. Others often name this 'dp' 14 | let mem = [0]; 15 | let i, j; 16 | 17 | // Outer loop, where we build up till we reach n 18 | for (i = 1; i <= n; i++) { 19 | 20 | // Initially, we have no idea how many steps it will take 21 | mem[i] = Infinity; 22 | 23 | // Now loop over all squares that are smaller or equal to the current i. 24 | for (j = 1; j * j <= i; j++) { 25 | 26 | // The smalles amount of squares is either what we already have, or what we can build with a new square and remainder 27 | mem[i] = Math.min(mem[i], mem[i - j * j] + 1); 28 | } 29 | 30 | 31 | } 32 | return mem[n]; 33 | } 34 | 35 | // Math solution (https://leetcode.com/problems/perfect-squares/solutions/476318/math-solution-explained-beats-100-javascript-whiteboard/?orderBy=most_votes&languageTags=javascript) 36 | 37 | var numSquares = n => { 38 | 39 | //returns if the number x is a valid square root ( can be represented as the square of an integer) 40 | let isSquare = x => Math.floor(Math.sqrt(x)) ** 2 === x; 41 | 42 | if (isSquare(n)) 43 | return 1; // that would be the fact that its equal to itself 44 | 45 | // Legendre's three square theorem: A natural number n can be represented as 46 | // the sum of AT MOST three squares of integers if and only if : n!= 4^x ( 8*m+7) 47 | while (n % 4 === 0) 48 | n /= 4; 49 | //Try contradicting Legendre 50 | if (n % 8 === 7) 51 | return 4; 52 | 53 | // Manually checking for result 2, because Legendre states AT MOST 3, 54 | // so 2 is possible aswell 55 | for (let i = 0; i <= n; i++) 56 | // if x=n-i*i and x is a valid square then OBVIOUSLY 57 | // n=i^2 +sqrt(x)^2 ,so n is a square of two numbers 58 | if (isSquare(n - i * i)) 59 | return 2; 60 | 61 | // Legendre applies 62 | return 3; 63 | }; -------------------------------------------------------------------------------- /JAVA solutions/hashmap/HashMapLearning.java: -------------------------------------------------------------------------------- 1 | package hashmap; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public class HashMapLearning { 9 | public static void main(String[] args) { 10 | String s = "abracadabra"; 11 | int[] a1 = {1, 1, 1, 2, 2, 3, 4, 5}; 12 | int[] a2 = {1, 1, 2, 2, 5}; 13 | // System.out.println(highestFreqChar(s)); 14 | // System.out.println(commonElem(a1, a2)); 15 | System.out.println(commonElm2(a1, a2)); 16 | } 17 | 18 | 19 | public static char highestFreqChar(String s) { 20 | Map map = new HashMap<>(); 21 | 22 | for (int i = 0; i < s.length(); i++) { 23 | char ch = s.charAt(i); 24 | if (map.containsKey(ch)) { 25 | int of = map.get(ch); 26 | int nf = of + 1; 27 | map.put(ch, nf); 28 | } else { 29 | map.put(ch, 1); 30 | } 31 | } 32 | char mfc = s.charAt(0); 33 | for (Character key : map.keySet()) { 34 | if (map.get(key) > map.get(mfc)) { 35 | mfc = key; 36 | } 37 | } 38 | return mfc; 39 | } 40 | 41 | public static List commonElem(int[] arr1, int[] arr2) { 42 | Map map = new HashMap<>(); 43 | List list = new ArrayList<>(); 44 | 45 | for (int i = 0; i < arr1.length; i++) { 46 | if (map.containsKey(arr1[i])) { 47 | int of = map.get(arr1[i]); 48 | int nf = of + 1; 49 | map.put(arr1[i], nf); 50 | } else { 51 | map.put(arr1[i], 1); 52 | } 53 | } 54 | for (int i = 0; i < arr2.length; i++) { 55 | if (map.containsKey(arr2[i])) { 56 | list.add(arr2[i]); 57 | map.remove(arr2[i]); 58 | } 59 | } 60 | return list; 61 | } 62 | 63 | public static List commonElm2(int[] a1, int[] a2) { 64 | Map map = new HashMap<>(); 65 | List list = new ArrayList<>(); 66 | 67 | for (int val : a1) { 68 | if (map.containsKey(val)) { 69 | int of = map.get(val); 70 | int nf = of + 1; 71 | map.put(val, nf); 72 | } else { 73 | map.put(val, 1); 74 | } 75 | } 76 | 77 | for (int val : a2) { 78 | if (map.containsKey(val) && map.get(val) > 0) { 79 | list.add(val); 80 | int of = map.get(val); 81 | int nf = of - 1; 82 | map.put(val, nf); 83 | } 84 | } 85 | return list; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /JAVA solutions/linkedlist/LeetcodeLL.java: -------------------------------------------------------------------------------- 1 | package leetcode.linkedlist; 2 | 3 | public class LeetcodeLL { 4 | public ListNode reverse(ListNode head) { 5 | if (head == null) return head; 6 | 7 | ListNode prev = null; 8 | ListNode current = head; 9 | ListNode next = current.next; 10 | 11 | while (current != null) { 12 | current.next = prev; 13 | prev = current; 14 | current = next; 15 | if (next != null) { 16 | next = next.next; 17 | } 18 | } 19 | return prev; 20 | } 21 | 22 | //https://leetcode.com/problems/linked-list-cycle/ 23 | public boolean hasCycle(ListNode head) { 24 | ListNode fast = head; 25 | ListNode slow = head; 26 | 27 | while (fast != null && fast.next != null) { 28 | fast = fast.next.next; 29 | slow = slow.next; 30 | if (fast == slow) return true; 31 | } 32 | return false; 33 | } 34 | 35 | public int lengthOfCycle(ListNode head) { 36 | ListNode fast = head; 37 | ListNode slow = head; 38 | 39 | while (fast != null && fast.next != null) { 40 | fast = fast.next.next; 41 | slow = slow.next; 42 | if (fast == slow) { 43 | ListNode temp = slow; 44 | int len = 0; 45 | do { 46 | temp = temp.next; 47 | len++; 48 | } while (temp != slow); 49 | return len; 50 | } 51 | } 52 | return 0; 53 | } 54 | 55 | //https://leetcode.com/problems/linked-list-cycle-ii/ 56 | public ListNode detectCycle(ListNode head) { 57 | ListNode fast = head; 58 | ListNode slow = head; 59 | int index = 0; 60 | 61 | while (fast != null && fast.next != null) { 62 | fast = fast.next.next; 63 | slow = slow.next; 64 | if (fast == slow) { 65 | index = lengthOfCycle(slow); 66 | break; 67 | } 68 | } 69 | 70 | if (index == 0) return null; 71 | 72 | //find the start Node 73 | ListNode f = head; 74 | ListNode s = head; 75 | 76 | while (index > 0) { 77 | s = s.next; 78 | index--; 79 | } 80 | 81 | while (f != s) { 82 | f = f.next; 83 | s = s.next; 84 | } 85 | return s; 86 | } 87 | 88 | // Definition for singly-linked list. 89 | class ListNode { 90 | int val; 91 | ListNode next; 92 | 93 | ListNode(int x) { 94 | val = x; 95 | next = null; 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /Data structures/trees/breadth_first_values/breadth_first_values.js: -------------------------------------------------------------------------------- 1 | //Write a function, breadthFirstValues, that takes in the root of a binary tree. 2 | // The function should return an array containing all values of the tree in breadth - first order. 3 | 4 | /* 5 | !test_00: 6 | 7 | const a = new Node('a'); 8 | const b = new Node('b'); 9 | const c = new Node('c'); 10 | const d = new Node('d'); 11 | const e = new Node('e'); 12 | const f = new Node('f'); 13 | 14 | a.left = b; 15 | a.right = c; 16 | b.left = d; 17 | b.right = e; 18 | c.right = f; 19 | 20 | a 21 | / \ 22 | b c 23 | / \ \ 24 | d e f 25 | 26 | breadthFirstValues(a); 27 | -> ['a', 'b', 'c', 'd', 'e', 'f'] 28 | 29 | !test_01: 30 | 31 | const a = new Node('a'); 32 | const b = new Node('b'); 33 | const c = new Node('c'); 34 | const d = new Node('d'); 35 | const e = new Node('e'); 36 | const f = new Node('f'); 37 | const g = new Node('g'); 38 | const h = new Node('h'); 39 | 40 | a.left = b; 41 | a.right = c; 42 | b.left = d; 43 | b.right = e; 44 | c.right = f; 45 | e.left = g; 46 | f.right = h; 47 | 48 | a 49 | / \ 50 | b c 51 | / \ \ 52 | d e f 53 | / \ 54 | g h 55 | 56 | breadthFirstValues(a); 57 | -> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 58 | 59 | !test_02: 60 | 61 | const a = new Node('a'); 62 | 63 | a 64 | 65 | breadthFirstValues(a); 66 | -> ['a'] 67 | 68 | !test_03: 69 | 70 | const a = new Node('a'); 71 | const b = new Node('b'); 72 | const c = new Node('c'); 73 | const d = new Node('d'); 74 | const e = new Node('e'); 75 | const x = new Node('x'); 76 | 77 | a.right = b; 78 | b.left = c; 79 | c.left = x; 80 | c.right = d; 81 | d.right = e; 82 | 83 | a 84 | \ 85 | b 86 | / 87 | c 88 | / \ 89 | x d 90 | \ 91 | e 92 | 93 | breadthFirstValues(a); 94 | -> ['a', 'b', 'c', 'x', 'd', 'e'] 95 | 96 | !test_04: 97 | 98 | breadthFirstValues(null); 99 | -> [] 100 | */ 101 | 102 | 103 | // class Node { 104 | // constructor(val) { 105 | // this.val = val; 106 | // this.left = null; 107 | // this.right = null; 108 | // } 109 | // } 110 | 111 | 112 | /* 113 | n = number of nodes; 114 | Time: O(n); 115 | Space: O(n) 116 | 117 | *Note: this solution should really be considered O(n^2) runtime 118 | *because the JavaScript shift() methods runs in O(n). 119 | *JavaScript does not have a native queue data structure that is maximally efficient. 120 | */ 121 | const breadthFirstValues = (root) => { 122 | if (root === null) return []; 123 | 124 | const values = []; 125 | const queue = [root]; 126 | 127 | while (queue.length > 0) { 128 | const currentNode = queue.shift(); 129 | values.push(currentNode.val); 130 | 131 | if (currentNode.left !== null) queue.push(currentNode.left); 132 | 133 | if (currentNode.right !== null) queue.push(currentNode.right); 134 | } 135 | return values; 136 | }; 137 | 138 | -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/shortest_path/shortest_path.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, shortestPath, that takes in an array of edges for an undirected graph and two nodes (nodeA, nodeB). 3 | The function should return the length of the shortest path between A and B. Consider the length as the number of edges in the path, 4 | not the number of nodes. If there is no path between A and B, then return -1. 5 | 6 | test_00: 7 | const edges = [ 8 | ['w', 'x'], 9 | ['x', 'y'], 10 | ['z', 'y'], 11 | ['z', 'v'], 12 | ['w', 'v'] 13 | ]; 14 | 15 | shortestPath(edges, 'w', 'z'); // -> 2 16 | test_01: 17 | const edges = [ 18 | ['w', 'x'], 19 | ['x', 'y'], 20 | ['z', 'y'], 21 | ['z', 'v'], 22 | ['w', 'v'] 23 | ]; 24 | 25 | shortestPath(edges, 'y', 'x'); // -> 1 26 | test_02: 27 | const edges = [ 28 | ['a', 'c'], 29 | ['a', 'b'], 30 | ['c', 'b'], 31 | ['c', 'd'], 32 | ['b', 'd'], 33 | ['e', 'd'], 34 | ['g', 'f'] 35 | ]; 36 | 37 | shortestPath(edges, 'a', 'e'); // -> 3 38 | test_03: 39 | const edges = [ 40 | ['a', 'c'], 41 | ['a', 'b'], 42 | ['c', 'b'], 43 | ['c', 'd'], 44 | ['b', 'd'], 45 | ['e', 'd'], 46 | ['g', 'f'] 47 | ]; 48 | 49 | shortestPath(edges, 'e', 'c'); // -> 2 50 | test_04: 51 | const edges = [ 52 | ['a', 'c'], 53 | ['a', 'b'], 54 | ['c', 'b'], 55 | ['c', 'd'], 56 | ['b', 'd'], 57 | ['e', 'd'], 58 | ['g', 'f'] 59 | ]; 60 | 61 | shortestPath(edges, 'b', 'g'); // -> -1 62 | test_05: 63 | const edges = [ 64 | ['c', 'n'], 65 | ['c', 'e'], 66 | ['c', 's'], 67 | ['c', 'w'], 68 | ['w', 'e'], 69 | ]; 70 | 71 | shortestPath(edges, 'w', 'e'); // -> 1 72 | test_06: 73 | const edges = [ 74 | ['c', 'n'], 75 | ['c', 'e'], 76 | ['c', 's'], 77 | ['c', 'w'], 78 | ['w', 'e'], 79 | ]; 80 | 81 | shortestPath(edges, 'n', 'e'); // -> 2 82 | test_07: 83 | const edges = [ 84 | ['m', 'n'], 85 | ['n', 'o'], 86 | ['o', 'p'], 87 | ['p', 'q'], 88 | ['t', 'o'], 89 | ['r', 'q'], 90 | ['r', 's'] 91 | ]; 92 | 93 | shortestPath(edges, 'm', 's'); // -> 6 94 | */ 95 | 96 | // breadth first; 97 | const shortestPath = (edges, nodeA, nodeB) => { 98 | const graph = buildGraph(edges); 99 | const visited = new Set([nodeA]); 100 | const queue = [[nodeA, 0]]; 101 | 102 | while (queue.length > 0) { 103 | const [node, distance] = queue.shift(); 104 | 105 | if (node === nodeB) return distance; 106 | 107 | for (let neighbor of graph[node]) { 108 | if (!visited.has(neighbor)) { 109 | visited.add(neighbor); 110 | queue.push([neighbor, distance + 1]); 111 | } 112 | } 113 | } 114 | 115 | return -1; 116 | }; 117 | 118 | const buildGraph = (edges) => { 119 | const graph = {}; 120 | 121 | for (let edge of edges) { 122 | const [a, b] = edge; 123 | if (!(a in graph)) graph[a] = []; 124 | if (!(b in graph)) graph[b] = []; 125 | 126 | graph[a].push(b); 127 | graph[b].push(a); 128 | } 129 | 130 | return graph; 131 | }; -------------------------------------------------------------------------------- /JAVA solutions/recursion/RecursionLearning.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class RecursionLearning { 4 | public static void main(String[] args) { 5 | // printNumebr(1); // prints 1 to 5 6 | // printEven(1); 7 | // printNumebr(1, 10); 8 | // int[] arr = {1, 2, 3, 4, 5}; 9 | // printArray(arr, 0); 10 | 11 | // System.out.println(sum(1, 5)); 12 | // int[] arr = {1, 2, 3, 4, 5, 6}; 13 | 14 | // System.out.println(binarySearch(arr, 5, 0, arr.length - 1)); 15 | 16 | // printReversed(10, 1); 17 | // System.out.println(prod(3)); 18 | // System.out.println(sumOfDifgits(123)); 19 | 20 | System.out.println(prodOfDgits(23)); 21 | 22 | } 23 | 24 | static int binarySearch(int[] arr, int target, int start, int end) { 25 | if (start > end) return -1; 26 | 27 | int mid = start + (end - start) / 2; 28 | 29 | if (arr[mid] == target) return mid; 30 | 31 | if (arr[mid] < target) { 32 | return binarySearch(arr, target, mid + 1, end); 33 | } 34 | return binarySearch(arr, target, start, mid - 1); 35 | } 36 | 37 | static void printNumebr(int start, int end) { 38 | if (start > end) { 39 | return; 40 | } 41 | System.out.print(start + " "); 42 | printNumebr(start + 1, end); 43 | } 44 | 45 | static void printReversed(int end, int start) { 46 | if (end < start) { 47 | return; 48 | } 49 | System.out.print(end + " "); 50 | printReversed(end - 1, start); 51 | } 52 | 53 | static void printEven(int n) { 54 | if (n > 10) { 55 | return; 56 | } 57 | if (n % 2 == 0) System.out.println(n); 58 | 59 | printEven(n + 1); 60 | } 61 | 62 | static void printArray(int[] arr, int n) { 63 | if (n == arr.length) return; 64 | 65 | System.out.println(arr[n]); 66 | printArray(arr, n + 1); 67 | } 68 | 69 | static int sum(int start, int end) { 70 | if (start == end) { 71 | return start; 72 | } 73 | return start + sum(start + 1, end); 74 | } 75 | 76 | static int prod(int n) { 77 | if (n == 1) { 78 | return n; 79 | } 80 | 81 | return n * prod(n - 1); 82 | } 83 | 84 | static int sumOfDifgits(int n) { 85 | if (n == 0) { 86 | return 0; 87 | } 88 | 89 | return sumOfDifgits(n / 10) + n % 10; 90 | } 91 | 92 | static int prodOfDgits(int n) { 93 | if (n % 10 == n) { 94 | return n; 95 | } 96 | 97 | return (n % 10) * prodOfDgits(n / 10); 98 | } 99 | 100 | static boolean isArraySorted(int[] arr, int index) { 101 | if (index == arr.length - 1) return true; 102 | 103 | return arr[index] < arr[index + 1] && isArraySorted(arr, index + 1); 104 | } 105 | 106 | static boolean linearSearch(int[] arr, int target, int index) { 107 | if (index == arr.length) return false; 108 | 109 | return arr[index] == target || linearSearch(arr, target, index + 1); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /Data structures/trees/depth_first_value/depth_first_values.js: -------------------------------------------------------------------------------- 1 | // Write a function, depthFirstValues, that takes in the root of a binary tree. 2 | // The function should return an array containing all values of the tree in depth - first order. 3 | 4 | // Hey.This is our first binary tree problem, 5 | // so you should be liberal with watching the Approach and Walkthrough.Be productive, not stubborn. 6 | 7 | /* test case */ 8 | 9 | /* 10 | const a = new Node('a'); 11 | const b = new Node('b'); 12 | const c = new Node('c'); 13 | const d = new Node('d'); 14 | const e = new Node('e'); 15 | const f = new Node('f'); 16 | 17 | a.left = b; 18 | a.right = c; 19 | b.left = d; 20 | b.right = e; 21 | c.right = f; 22 | 23 | a 24 | / \ 25 | b c 26 | / \ \ 27 | d e f 28 | 29 | depthFirstValues(a); 30 | -> ['a', 'b', 'd', 'e', 'c', 'f'] 31 | 32 | *******TEST CASE ********** 33 | 34 | const a = new Node('a'); 35 | const b = new Node('b'); 36 | const c = new Node('c'); 37 | const d = new Node('d'); 38 | const e = new Node('e'); 39 | const f = new Node('f'); 40 | const g = new Node('g'); 41 | 42 | a.left = b; 43 | a.right = c; 44 | b.left = d; 45 | b.right = e; 46 | c.right = f; 47 | e.left = g; 48 | 49 | a 50 | / \ 51 | b c 52 | / \ \ 53 | d e f 54 | / 55 | g 56 | 57 | depthFirstValues(a); 58 | -> ['a', 'b', 'd', 'e', 'g', 'c', 'f'] 59 | 60 | *******TEST CASE ********** 61 | 62 | const a = new Node('a'); 63 | const b = new Node('b'); 64 | const c = new Node('c'); 65 | const d = new Node('d'); 66 | const e = new Node('e'); 67 | 68 | a.right = b; 69 | b.left = c; 70 | c.right = d; 71 | d.right = e; 72 | 73 | a 74 | \ 75 | b 76 | / 77 | c 78 | \ 79 | d 80 | \ 81 | e 82 | 83 | depthFirstValues(a); 84 | -> ['a', 'b', 'c', 'd', 'e'] 85 | */ 86 | 87 | class Node { 88 | constructor (val) { 89 | this.val = (val === undefined ? 0 : val); 90 | this.left = (left === undefined ? null : left); 91 | this.right = (right === undefined ? null : right); 92 | } 93 | } 94 | 95 | /*! iterative way 96 | 97 | n = number of nodes; 98 | Time: O(n); 99 | Space: O(n) 100 | */ 101 | const depthFirstValuesI = (root) => { 102 | if (root === null) 103 | return []; 104 | 105 | const values = []; 106 | const stack = [root]; 107 | 108 | while (stack.length > 0) { // while stack is Empty 109 | const currentNode = stack.pop(); 110 | values.push(currentNode.val); 111 | 112 | if (currentNode.right !== null) 113 | stack.push(currentNode.right); 114 | 115 | if (currentNode.left !== null) 116 | stack.push(currentNode.left); 117 | } 118 | 119 | return values; 120 | }; 121 | 122 | 123 | /*! Recursive way 124 | 125 | * n = number of nodes; 126 | * Time: O(n); 127 | * Space: O(n) 128 | */ 129 | const depthFirstValues = (root) => { 130 | if (root === null) 131 | return []; 132 | 133 | const leftValues = depthFirstValues(root.left); 134 | const rightValues = depthFirstValues(root.right); 135 | return [root.val, ...leftValues, ...rightValues]; 136 | }; -------------------------------------------------------------------------------- /Data structures/trees/tree_min_value/tree_min_value.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function, treeMinValue, 3 | that takes in the root of a binary tree that contains number values. 4 | The function should return the minimum value within the tree. 5 | 6 | You may assume that the input tree is non - empty.; 7 | 8 | 9 | test_00: 10 | 11 | const a = new Node(3); 12 | const b = new Node(11); 13 | const c = new Node(4); 14 | const d = new Node(4); 15 | const e = new Node(-2); 16 | const f = new Node(1); 17 | 18 | a.left = b; 19 | a.right = c; 20 | b.left = d; 21 | b.right = e; 22 | c.right = f; 23 | 24 | 3 25 | / \ 26 | 11 4 27 | / \ \ 28 | 4 -2 1 29 | 30 | treeMinValue(a); // -> -2 31 | 32 | test_01: 33 | 34 | const a = new Node(5); 35 | const b = new Node(11); 36 | const c = new Node(3); 37 | const d = new Node(4); 38 | const e = new Node(14); 39 | const f = new Node(12); 40 | 41 | a.left = b; 42 | a.right = c; 43 | b.left = d; 44 | b.right = e; 45 | c.right = f; 46 | 47 | 5 48 | / \ 49 | 11 3 50 | / \ \ 51 | 4 14 12 52 | 53 | treeMinValue(a); // -> 3 54 | 55 | test_02: 56 | 57 | const a = new Node(-1); 58 | const b = new Node(-6); 59 | const c = new Node(-5); 60 | const d = new Node(-3); 61 | const e = new Node(-4); 62 | const f = new Node(-13); 63 | const g = new Node(-2); 64 | const h = new Node(-2); 65 | 66 | a.left = b; 67 | a.right = c; 68 | b.left = d; 69 | b.right = e; 70 | c.right = f; 71 | e.left = g; 72 | f.right = h; 73 | 74 | -1 75 | / \ 76 | -6 -5 77 | / \ \ 78 | -3 -4 -13 79 | / \ 80 | -2 -2 81 | 82 | treeMinValue(a); // -> -13 83 | 84 | test_03: 85 | 86 | const a = new Node(42); 87 | 88 | 42 89 | 90 | treeMinValue(a); // -> 42 91 | */ 92 | 93 | 94 | // depth first (recursive) 95 | const treeMinValueDr = (root) => { 96 | if (root === null) return Infinity; 97 | const smallestLeftValue = treeMinValueDr(root.left); 98 | const smallestRightValue = treeMinValueDr(root.right); 99 | return Math.min(root.val, smallestLeftValue, smallestRightValue); 100 | }; 101 | 102 | // depth first (iterative) 103 | const treeMinValueDi = (root) => { 104 | const stack = [root]; 105 | 106 | let smallest = Infinity; 107 | while (stack.length) { 108 | const current = stack.pop(); 109 | if (current.val < smallest) smallest = current.val; 110 | 111 | if (current.left !== null) stack.push(current.left); 112 | if (current.right !== null) stack.push(current.right); 113 | } 114 | return smallest; 115 | }; 116 | 117 | //breadth first (iterative) 118 | /* 119 | Note: this solution should really be considered O(n^2) runtime 120 | because the JavaScript shift() methods runs in O(n). 121 | JavaScript does not have a native queue data structure that is maximally efficient. 122 | */ 123 | const treeMinValue = (root) => { 124 | const queue = [root]; 125 | 126 | let smallest = Infinity; 127 | while (queue.length) { 128 | const current = queue.shift(); 129 | if (current.val < smallest) smallest = current.val; 130 | 131 | if (current.left !== null) queue.push(current.left); 132 | if (current.right !== null) queue.push(current.right); 133 | } 134 | return smallest; 135 | }; -------------------------------------------------------------------------------- /algorithms/searching/graph-theory/Dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define pb push_back 4 | #define eps 1e-9 5 | #define ff first 6 | #define ss second 7 | #define pi acos(-1) 8 | #define inf 1e18 9 | #define mset(a,x) memset(a,(x),sizeof(a)) 10 | #define all(x) x.begin(),x.end() 11 | #define allr(x) x.rbegin(),x.rend() 12 | #define Fast_Read ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); 13 | #define Precision(x) cout.setf(ios::fixed); cout.precision(x); 14 | 15 | using namespace std; 16 | typedef long double ld; 17 | typedef long long ll; 18 | typedef pair pii; 19 | inline int nxt(){int aaa;scanf("%d",&aaa);return aaa;} 20 | inline ll lxt(){ll aaa;scanf("%lld",&aaa);return aaa;} 21 | inline double dxt(){double aaa;scanf("%lf",&aaa);return aaa;} 22 | #ifdef ARnAb 23 | #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__) 24 | template < typename Arg1 > 25 | void __f(const char* name, Arg1&& arg1){ 26 | cerr << name << " is " << arg1 << std::endl; 27 | } 28 | template < typename Arg1, typename... Args> 29 | void __f(const char* names, Arg1&& arg1, Args&&... args){ 30 | const char* comma = strchr(names+1, ','); 31 | cerr.write(names, comma - names) << " is " << arg1 <<" "; 32 | __f(comma+1, args...); 33 | } 34 | #else 35 | #define debug(...) 36 | #endif 37 | ///******************************************START****************************************** 38 | int cs=0; 39 | int node,edge; 40 | vector< vector< pair > > adj; 41 | vectordis; 42 | vectorpar; 43 | void djkstra(int sp){ 44 | priority_queue< pair > pq; 45 | pq.push({0,sp}); 46 | dis[sp]=0; 47 | while(!pq.empty()) 48 | { 49 | auto top=pq.top(); 50 | pq.pop(); 51 | int u=top.ss; 52 | for(int i=0;i>node>>edge; 67 | adj.resize(node+1); 68 | dis.assign(node+1, inf); 69 | par.assign(node+1, -1); 70 | for(int i=0;i>u>>v>>x; 74 | adj[u].pb({v,x}); 75 | adj[v].pb({u,x}); 76 | } 77 | djkstra(1); 78 | int x=node; 79 | if(dis[x]==inf) 80 | { 81 | cout<<-1<dq; 85 | dq.push_front(x); 86 | while(par[x]!=-1) 87 | { 88 | int xx=par[x]; 89 | dq.push_front(xx); 90 | x=xx; 91 | } 92 | while(!dq.empty()) 93 | { 94 | int p=dq.front(); 95 | dq.pop_front(); 96 | cout<>tc; 110 | while(tc--) 111 | solve(); 112 | return 0; 113 | } 114 | --------------------------------------------------------------------------------