├── Kattis Online Judge ├── ReadMe.md └── LCA on Trees │ └── Tourists │ └── ReadMe.md ├── Images ├── ReadMe.md ├── Icon.png ├── Sample.gif ├── median.png ├── Leetcode Logo.png ├── Codeforces Logo.png └── GeeksforGeeks Logo.png ├── _config.yml ├── Crash Course II (DS & Algorithms) ├── ReadMe.md ├── Outline │ ├── ReadMe.md │ └── Pointers and Structures │ │ └── ReadMe.md ├── Lecture Notes │ └── ReadMe.md ├── Practice Problems │ └── ReadMe.md ├── Programming Assignments │ └── ReadMe.md └── Syllabus │ └── ReadMe.md ├── Interview Preparation ├── Coding Questions │ └── .Rhistory ├── Probability │ └── ReadMe.md ├── ReadMe.md └── Algorithms and Data Structures │ └── ReadMe.md ├── Templates ├── Dijkstra's Algorithm │ ├── ReadMe.md │ └── Adjacency List │ │ └── ReadMe.md ├── Strongly Connected Components │ ├── ReadMd.md │ └── Double DFS Approach │ │ └── ReadMe.md ├── Travelling Cardinal Directions │ ├── ReadMe.md │ └── Co-ordinate Approach.cpp ├── ReadMe.md ├── Lowest Common Ancestor │ └── ReadMe.md ├── Printing a Matrix │ ├── ReadMe.md │ └── The Fancy Approach.cpp ├── Comparators │ ├── The Fundamentals (Conceptual).cpp │ ├── The Good.cpp │ ├── The Worst (and Wrong).cpp │ └── The Best.cpp ├── Matrix Partial Sum │ └── Readme.md ├── Prime Factorization │ └── Prime Factorization Template.cpp └── Scan and Print a Vector │ └── Scanning And Printing a Vector (Debugging).cpp ├── UVa Online Judge ├── Disjoint Set Union │ └── ReadMe.md ├── Graph Traversal │ └── As long as I learn (12376) │ │ └── ReadMe.md ├── Fenwick Tree │ ├── Potentiometers (12086) │ │ └── ReadMe.md │ └── Interval Product (12532) │ │ └── ReadMe.md ├── Binary Search the Answer │ └── Monkey and Oiled Bamboo (12032) │ │ ├── ReadMe.md │ │ ├── Simple Binary Search.cpp │ │ └── Clean Implementation (Safe).cpp ├── Priority Queue │ └── Add All (10954) │ │ └── Min Heap (Greedy).cpp ├── Map │ └── Hardwood Species (10226) │ │ └── STL_Map.cpp ├── Binary Search │ └── Where is the Marble (10474) │ │ └── Lower Bound.cpp └── 2D Range Sum │ └── Maximum Sum (108) │ └── O(n^4).cpp ├── Codeforces Contests ├── CF Edu Round 72 │ └── Images │ │ ├── ReadMe.md │ │ └── Rating.PNG ├── CF Round 582 │ ├── Images │ │ ├── 1.png │ │ ├── 2.png │ │ ├── 3.png │ │ ├── 4.png │ │ └── 5.png │ ├── Rating.PNG │ └── ReadMe.md ├── CF Round 581 │ ├── D) Kirk and a Binary String │ │ ├── ReadMe.md │ │ └── Remove Valid Parenthesis.cpp │ └── ReadMe.md └── ReadMe.md ├── LeetCode Contests ├── LeetCode Contest #130 │ ├── ReadMe.md │ ├── #1019 Next Greater Element │ │ ├── ReadMe.md │ │ └── Stack Based Approach.cpp │ ├── #1018 Binary Prefix Divisible by 5 │ │ └── Optimized Approach.cpp │ └── #1020 Number of Enclaves │ │ └── Number of Enclaves.cpp ├── LeetCode Contest #131 │ ├── ReadMe.md │ ├── #1023 CamelCase Matching │ │ └── ReadMe.md │ └── #1022 Sum of root to leaf Binary Numbers │ │ ├── ReadMe.md │ │ ├── No Data Structure Approach.cpp │ │ └── Vector Based Enumeration.cpp ├── LeetCode BiWeekly Contest #8 │ ├── ReadMe.md │ ├── #1180 Substrings with one Distinct │ │ ├── DP Solution.cpp │ │ └── ReadMe.md │ └── #1181 Before After Puzzle │ │ ├── ReadMe.md │ │ └── String Stream.cpp ├── LeetCode Contest #153 │ ├── #1185 Day of Week │ │ └── ReadMe.md │ ├── #1184 Distance Between Bus Stops │ │ ├── ReadMe.md │ │ └── Contest Submission (Dirty).cpp │ ├── #1186 Maximum Subarray with 1 Deletion │ │ └── ReadMe.md │ ├── #1187 Make Array Strictly Increasing │ │ └── ReadMe.md │ └── ReadMe.md ├── LeetCode BiWeekly Contest #9 │ ├── #1199 Minimum Time to Build Blocks │ │ └── ReadMe.md │ ├── ReadMe.md │ ├── #1196 Apples in Basket │ │ ├── Good Library Functions.cpp │ │ └── ReadMe.md │ ├── #1197 Minimum Knight Moves │ │ ├── ReadMe.md │ │ └── Simple BFS.cpp │ └── #1198 Smallest Common Element │ │ ├── ReadMe.md │ │ └── Library.cpp ├── LeetCode Contest #157 │ ├── #1219 Path with Maximum Gold │ │ └── ReadMe.md │ ├── #1217 Play with Chips │ │ ├── Simple.cpp │ │ └── ReadMe.md │ ├── ReadMe.md │ ├── #1218 Longest AP Sequence │ │ ├── DP with HashMap.cpp │ │ └── ReadMe.md │ └── #1220 Count Vowel Permutation │ │ ├── Graph DP.cpp │ │ └── ReadMe.md ├── LeetCode BiWeekly Contest #17 │ ├── #5146 Distinct Echo Substrings │ │ └── ReadMe.md │ ├── ReadMe.md │ ├── #5143 Decompress Run Length │ │ └── Naive.cpp │ ├── #5145 Even GrandParents Sum │ │ └── Inorder Traversal (Clean).cpp │ └── #5144 Matrix Block Sum │ │ └── Range Sum DP.cpp ├── LeetCode Contest #152 │ ├── #1176 Diet Plan Performance │ │ ├── ReadMe.md │ │ └── Sliding Window.cpp │ ├── #1175 Prime Arrangements │ │ ├── ReadMe.md │ │ └── Sieve.cpp │ ├── #1177 Can Make Palindrome Substring │ │ ├── ReadMe.md │ │ └── Prefix Sum.cpp │ └── ReadMe.md ├── LeetCode Contest #138 │ ├── #1054 Distant Barcodes │ │ ├── ReadMe.md │ │ └── Max Heap Approach.cpp │ ├── #1051 Height Checker │ │ ├── ReadMe.md │ │ └── Sorting Based Approach.cpp │ └── ReadMe.md ├── LeetCode BiWeekly Contest #10 │ ├── #1213 Intersection of 3 Sorted Array │ │ ├── ReadMe.md │ │ └── HashMap.cpp │ ├── #1216 Valid Palindrome │ │ ├── ReadMe.md │ │ ├── LCS Approach.cpp │ │ └── Edit Distance Approach.cpp │ ├── #1214 Two Sum BST │ │ ├── HashMap Approach.cpp │ │ ├── O(1) Space.cpp │ │ └── ReadMe.md │ ├── #1215 Stepping Numbers │ │ ├── ReadMe.md │ │ └── Post Order Traversal.cpp │ └── ReadMe.md ├── LeetCode Contest #127 │ ├── #1006 Clumsy Factorial │ │ └── Explanation and Link.md │ ├── #1007 BST From Preorder │ │ ├── Explanation and Link.md │ │ └── BST From Preorder O(n^2).cpp │ ├── #1005 Maximize Sum Of Array After K Negations │ │ ├── ReadMe.md │ │ └── Maximize sum after K negations.cpp │ ├── LC #127 Contest Review.md │ └── #1008 Minimum Domino Rotations For Equal Row │ │ └── Explanation and Link.md ├── Readme.md ├── LeetCode Contest #126 │ ├── #1004 Max Consecutive Ones III │ │ └── Alternate Solutions.md │ ├── #1003 Check if Word is Valid After Substitution │ │ ├── JavaScript_BruteForce.js │ │ ├── Walid Word Checking_BruteForce.cpp │ │ ├── JavaScript_Optimized.js │ │ └── Concise and Optimized.cpp │ ├── LC #126 Contest Review.md │ └── #1002 Find Common Charcters │ │ └── Explantion and Link.md ├── LeetCode Contest #128 │ ├── #1012 Complement of a Base 10 Integer │ │ ├── JavaScript (Complement of a Number).js │ │ └── Complement of a number.cpp │ ├── ReadMe.md │ └── #1013 Pairs with Sum divisible by 60 │ │ ├── JavaScript Implementation.js │ │ └── Pairs with Sum divisible by 60.cpp ├── LeetCode Contest #162 │ ├── ReadMe.md │ ├── #1253 Reconstruct Binary Matrix │ │ ├── ReadMe.md │ │ └── Greedy.cpp │ ├── #1252 Cells with Odd Values │ │ └── Simple.cpp │ ├── #1254 Number of Closed Islands │ │ ├── Optimized DFS.cpp │ │ └── Modified DFS.cpp │ └── #1255 Maximum Score Words │ │ ├── ReadMe.md │ │ └── Backtracking.cpp ├── LeetCode Contest #129 │ ├── #1022 Smallest Integer with only 1's Divisible by K │ │ ├── JavaScript Implementation.js │ │ └── C++ Implementation.cpp │ ├── #1021 Best SightSeeing Pair │ │ └── Dynamic Programming O(1) space.cpp │ ├── #1023 Binary string with substring from 1 to N │ │ ├── C++ [Bruteforce But works].cpp │ │ └── ReadMe.md │ ├── #1020 Partition array into 3 parts │ │ └── Prefix Sum Method.cpp │ └── ReadMe.md └── LeetCode Contest #135 │ └── ReadMe.md ├── .gitattributes ├── GeekForGeeks ├── Binary Tree to DLL │ ├── ReadMe.md │ └── Modified InOrder.cpp ├── Tower Of Hanoi │ ├── ReadMe.md │ └── Recursive Approach.cpp ├── ReadMe.md └── Smallest Window with all characters of other string │ └── Readme.md ├── docs ├── _build │ ├── html │ │ ├── _static │ │ │ ├── custom.css │ │ │ ├── up.png │ │ │ ├── down.png │ │ │ ├── file.png │ │ │ ├── minus.png │ │ │ ├── plus.png │ │ │ ├── comment.png │ │ │ ├── ajax-loader.gif │ │ │ ├── up-pressed.png │ │ │ ├── comment-close.png │ │ │ ├── down-pressed.png │ │ │ ├── comment-bright.png │ │ │ ├── fonts │ │ │ │ ├── Lato-Bold.ttf │ │ │ │ ├── Inconsolata.ttf │ │ │ │ ├── Lato-Regular.ttf │ │ │ │ ├── Lato │ │ │ │ │ ├── lato-bold.eot │ │ │ │ │ ├── lato-bold.ttf │ │ │ │ │ ├── lato-bold.woff │ │ │ │ │ ├── lato-bold.woff2 │ │ │ │ │ ├── lato-italic.eot │ │ │ │ │ ├── lato-italic.ttf │ │ │ │ │ ├── lato-italic.woff │ │ │ │ │ ├── lato-regular.eot │ │ │ │ │ ├── lato-regular.ttf │ │ │ │ │ ├── lato-bolditalic.eot │ │ │ │ │ ├── lato-bolditalic.ttf │ │ │ │ │ ├── lato-italic.woff2 │ │ │ │ │ ├── lato-regular.woff │ │ │ │ │ ├── lato-regular.woff2 │ │ │ │ │ ├── lato-bolditalic.woff │ │ │ │ │ └── lato-bolditalic.woff2 │ │ │ │ ├── RobotoSlab-Bold.ttf │ │ │ │ ├── Inconsolata-Bold.ttf │ │ │ │ ├── Inconsolata-Regular.ttf │ │ │ │ ├── RobotoSlab-Regular.ttf │ │ │ │ ├── fontawesome-webfont.eot │ │ │ │ ├── fontawesome-webfont.ttf │ │ │ │ ├── fontawesome-webfont.woff │ │ │ │ ├── fontawesome-webfont.woff2 │ │ │ │ └── RobotoSlab │ │ │ │ │ ├── roboto-slab-v7-bold.eot │ │ │ │ │ ├── roboto-slab-v7-bold.ttf │ │ │ │ │ ├── roboto-slab-v7-bold.woff │ │ │ │ │ ├── roboto-slab-v7-bold.woff2 │ │ │ │ │ ├── roboto-slab-v7-regular.eot │ │ │ │ │ ├── roboto-slab-v7-regular.ttf │ │ │ │ │ ├── roboto-slab-v7-regular.woff │ │ │ │ │ └── roboto-slab-v7-regular.woff2 │ │ │ └── documentation_options.js │ │ ├── objects.inv │ │ └── .buildinfo │ └── doctrees │ │ ├── index.doctree │ │ └── environment.pickle ├── Makefile └── make.bat ├── LeetCode Non-Contest Solutions ├── #198 House Robber │ └── ReadMe.md ├── #232 Queue using 2 stacks │ └── ReadMe.md ├── #103 Zig Zag Tree Traversal │ └── ReadMe.md ├── #344 Reverse string Inplace │ ├── ReadMe.md │ └── 2 Pointer Approach.cpp ├── #796 Are 2 Strings Rotations │ ├── ReadMe.md │ └── Concatenation Approach.cpp ├── #116 Populating Next Pointers │ └── ReadMe.md ├── #42 Trapping Rain Water │ ├── ReadMe.md │ └── DP Approach.cpp ├── #106 Tree from In-order and Post-order │ └── ReadMe.md ├── #5 Longest Palindromic Substring │ └── ReadMe.md ├── #83 Removes Duplicates from List (Retain Single Copy) │ ├── ReadMe.md │ ├── Recursive Approach.cpp │ ├── Failed Approach.cpp │ └── Iterative Approach.cpp ├── #155 Stack to Implement getMin │ ├── ReadMe.md │ └── Auxillary Stack.cpp ├── #445 Add 2 numbers (Linked List) │ └── ReadMe.md ├── ReadMe.md ├── #72 Edit Distance │ └── Readme.md ├── #61 Cyclic Right Shift for Linked Lists │ ├── ReadMe.md │ └── Circle Formation.cpp ├── #32 Longest Valid Parentheses │ └── ReadMe.md ├── #721 Accounts Merge │ └── ReadMe.md ├── #141 Loop Detection in Linked List │ ├── ReadMe.md │ ├── Reversal Approach.cpp │ └── Walker & Runner Approach.cpp ├── #189 Rotate Array │ └── Triple Reversal Approach.cpp ├── #152 Maximum Product Subarray │ ├── Min_Max Optimized (Works).cpp │ └── Min_Max Approach (Fails).cpp ├── #151 Reverse a String Keeping The Words Intact │ ├── Explanation And Link.md │ └── Reverse a String Keeping The Words Same.cpp ├── #45 Jump Game II │ ├── Compact and Optimized (Final Version).cpp │ ├── Optimized BFS.cpp │ └── Bruteforce BFS (TLE).cpp ├── #206 Reverse a Linked List │ ├── Iterative Reverse JavaScript.js │ ├── Iterative Reverse.cpp │ ├── Recursive Reverse JavaScript.js │ └── Recursive Reverse.cpp ├── #160 Intersection of 2 Linked Lists │ └── Hashing Based Approach.cpp ├── #543 Diameter of Binary Tree │ └── Post Order Approach.cpp ├── #24 Pairwise swap in a Linked List │ ├── JavaScript Implementation.js │ ├── Explanation and Link.md │ └── Recursive Solution.cpp ├── #893 Bitwise OR of Subarrays │ └── Optimized DP.cpp ├── #127 Word Ladder │ └── ReadMe.md ├── #312 Burst Balloons │ └── Recursive Memo.cpp ├── #134 Circular Tour of Petrol Pumps │ ├── Queue [O(n) Space].cpp │ ├── Queue [O(1) Space].cpp │ └── Concatenation Approach [Clean].cpp ├── #84 Largest Rectangle Under the Skyline │ └── Single Traversal and 1 Stack.cpp └── #138 Cloning a Linked List with Random Pointers │ └── First Draft (Uncommented).cpp ├── Pseudocode ├── Stack │ └── Stock Span │ │ └── Stock Span.pdf ├── Graphs │ ├── Word Ladder │ │ └── Word_Ladder.pdf │ ├── Topological Sort │ │ ├── Images │ │ │ ├── KahnAlgoStep1.png │ │ │ ├── KahnAlgoStep2.png │ │ │ ├── KahnAlgoStep3.png │ │ │ ├── KahnAlgoStep4.png │ │ │ ├── KahnAlgoStep5.png │ │ │ └── KahnAlgoStep6.png │ │ └── Topological Sorting.pdf │ └── Minimum Jumps to Reach the End of Array │ │ └── Min_Jumps.pdf ├── Dynamic Programming │ ├── Edit Distance │ │ └── E_Dist.pdf │ ├── Maximum Sum Subarray │ │ ├── Kadane.pdf │ │ └── SourceCode.tex │ ├── Longest Common Subsequence │ │ └── LCS.pdf │ ├── Trapping Rainwater │ │ └── Trap_Water.pdf │ ├── Longest Increasing Subsequence │ │ └── LIS.pdf │ ├── Buying and Selling Stocks │ │ └── One Transaction │ │ │ └── BSS 1 (DP).pdf │ └── Wildcard Pattern Matching │ │ └── WildCard_Pattern_Matching.pdf ├── Heaps │ ├── Merge K Sorted Vectors │ │ └── Merge_K_Sorted.pdf │ ├── Minimum Cost to Connect Ropes │ │ ├── Min_Cost_Ropes.pdf │ │ └── SourceCode.tex │ └── Median in a Stream of Integers │ │ └── Median in Stream.pdf ├── Trees │ ├── Zig Zag Tree Traversal │ │ └── Zig Zag Traversal.pdf │ ├── Vertical Order Traversal │ │ └── Vertical Order Traversal.pdf │ ├── Connect Nodes at the Same Level │ │ └── Connect Nodes at Level.pdf │ └── Level Order Traversal │ │ ├── Single Line │ │ └── Level Order Traversal.pdf │ │ └── Line By Line │ │ ├── Two Queues │ │ └── Level_Order_Line_1.pdf │ │ ├── Queue and Marker │ │ └── Level_Order_Line_2.pdf │ │ └── One Queueu and No Marker │ │ └── Level_Order_Line_3.pdf ├── Linked Lists │ ├── Reverse a Linked List │ │ └── Recursive and Iterative.pdf │ ├── Clone a List with Random Pointers │ │ └── Clone_List_Random.pdf │ └── Remove Duplicates from Sorted List │ │ ├── Delete All Copies │ │ └── Remove_Duplicates_All.pdf │ │ └── Retain Single Copy │ │ └── Remove_Duplicates_Some.pdf ├── Queue │ └── First Non Repeating in Stream │ │ └── First Non Repeating in Stream.pdf └── Sorting │ └── Selection Sort │ └── SourceCode.tex ├── Crash Course (DS & Algorithms) ├── Lecture Notes │ ├── Heaps.pdf │ ├── Dynamic Programming.pdf │ ├── Last Lecture (Trees, Graphs, List).pdf │ ├── Lecture_1 (Recursion, Time Complexity).pdf │ └── ReadMe.md ├── Practice Problems │ ├── PS1_Recursion.pdf │ ├── PS4 (STL, Maps).pdf │ ├── PS2 (Divide and Conquer, Sorting).pdf │ └── ReadMe.md ├── ReadMe.md └── Programming Assignments │ ├── Programming_Assignment_1.pdf │ ├── Programming_Assignment_2.pdf │ ├── Programming_Assignment_3 (STL).pdf │ ├── Programming_Assignment_4 (DP).pdf │ ├── Programming_Assignment_5 (String Manipulation).pdf │ └── ReadMe.md ├── SPOJ Online Judge ├── Sets │ └── Colorful Arrays (CLFLARR) │ │ ├── ReadMe.md │ │ └── Reverse Query Processing.cpp └── Trees │ └── Minimum Vertex Cover (PT07X) │ └── ReadMe.md ├── Codechef ├── Dynamic Programming │ └── Squared Subsequences (SQRDSUB) │ │ ├── Editorial.pdf │ │ └── DP_Approach.cpp └── Fenwick Tree │ └── Gravel (Spread) │ └── ReadMe.md ├── HackerRank ├── Dynamic Programming │ └── Red John is Back │ │ ├── ReadMe.md │ │ └── Simple DP and Sieve.cpp └── String Algorithms │ └── LCS │ └── Common Child │ └── Simple LCS.cpp ├── .github └── config.yml └── E-Olymp Online Judge └── DP on Trees └── House Robber (Tree) (973) └── ReadMe.md /Kattis Online Judge/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Images/ReadMe.md: -------------------------------------------------------------------------------- 1 | Nothing to see here. 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Interview Preparation/Coding Questions/.Rhistory: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Templates/Dijkstra's Algorithm/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /UVa Online Judge/Disjoint Set Union/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Codeforces Contests/CF Edu Round 72/Images/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/Outline/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #130/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #131/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Templates/Strongly Connected Components/ReadMd.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Templates/Travelling Cardinal Directions/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/Lecture Notes/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #8/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/Practice Problems/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * linguist-vendored 2 | *.tex linguist-vendored=false 3 | -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/Programming Assignments/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /GeekForGeeks/Binary Tree to DLL/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description. 2 | -------------------------------------------------------------------------------- /Templates/Strongly Connected Components/Double DFS Approach/ReadMe.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /GeekForGeeks/Tower Of Hanoi/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description and add the code 2 | -------------------------------------------------------------------------------- /docs/_build/html/_static/custom.css: -------------------------------------------------------------------------------- 1 | /* This file intentionally left blank. */ 2 | -------------------------------------------------------------------------------- /GeekForGeeks/ReadMe.md: -------------------------------------------------------------------------------- 1 | This folder contains the codes submitted on GeekForGeeks. 2 | -------------------------------------------------------------------------------- /Interview Preparation/Probability/ReadMe.md: -------------------------------------------------------------------------------- 1 | * - [ ] Expected number of Inversions 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#198 House Robber/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the explanation. 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/#1185 Day of Week/ReadMe.md: -------------------------------------------------------------------------------- 1 | Solve the question 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#232 Queue using 2 stacks/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the explanation 2 | -------------------------------------------------------------------------------- /Templates/ReadMe.md: -------------------------------------------------------------------------------- 1 | This directory contains the templates for competitive programming. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#103 Zig Zag Tree Traversal/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#344 Reverse string Inplace/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#796 Are 2 Strings Rotations/ReadMe.md: -------------------------------------------------------------------------------- 1 | Explain the approach. 2 | -------------------------------------------------------------------------------- /Images/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/Icon.png -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #131/#1023 CamelCase Matching/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#116 Populating Next Pointers/ReadMe.md: -------------------------------------------------------------------------------- 1 | Explain all the approaches. 2 | -------------------------------------------------------------------------------- /Images/Sample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/Sample.gif -------------------------------------------------------------------------------- /Images/median.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/median.png -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/#1184 Distance Between Bus Stops/ReadMe.md: -------------------------------------------------------------------------------- 1 | Optimize the approach 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/#1186 Maximum Subarray with 1 Deletion/ReadMe.md: -------------------------------------------------------------------------------- 1 | Clean the code. 2 | -------------------------------------------------------------------------------- /Interview Preparation/ReadMe.md: -------------------------------------------------------------------------------- 1 | This folder contains the necessary resources to prepare for an interview. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#42 Trapping Rain Water/ReadMe.md: -------------------------------------------------------------------------------- 1 | Clean the code and update the explanation 2 | -------------------------------------------------------------------------------- /UVa Online Judge/Graph Traversal/As long as I learn (12376)/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Review 2 | What a boring question! 3 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #131/#1022 Sum of root to leaf Binary Numbers/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#106 Tree from In-order and Post-order/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the explanation and links. 2 | -------------------------------------------------------------------------------- /Images/Leetcode Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/Leetcode Logo.png -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#5 Longest Palindromic Substring/ReadMe.md: -------------------------------------------------------------------------------- 1 | Clean the code and provide the documentation. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#83 Removes Duplicates from List (Retain Single Copy)/ReadMe.md: -------------------------------------------------------------------------------- 1 | Update the description 2 | -------------------------------------------------------------------------------- /GeekForGeeks/Smallest Window with all characters of other string/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | Update the description and clean the code 3 | -------------------------------------------------------------------------------- /Images/Codeforces Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/Codeforces Logo.png -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#155 Stack to Implement getMin/ReadMe.md: -------------------------------------------------------------------------------- 1 | Explain the algorithm and link 2 unique solutions. 2 | -------------------------------------------------------------------------------- /Images/GeeksforGeeks Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Images/GeeksforGeeks Logo.png -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1199 Minimum Time to Build Blocks/ReadMe.md: -------------------------------------------------------------------------------- 1 | Do it using **Huffman Algorithm** 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/#1219 Path with Maximum Gold/ReadMe.md: -------------------------------------------------------------------------------- 1 | # To Do 2 | Solve this problem. It's a simple DFs. 3 | -------------------------------------------------------------------------------- /docs/_build/html/objects.inv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/objects.inv -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#445 Add 2 numbers (Linked List)/ReadMe.md: -------------------------------------------------------------------------------- 1 | Explain a bit about sentinels and the algorithm in general. 2 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/ReadMe.md: -------------------------------------------------------------------------------- 1 | This directory contains the solutions of all the questions that I solve during my free time. 2 | -------------------------------------------------------------------------------- /docs/_build/html/_static/up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/up.png -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/#1187 Make Array Strictly Increasing/ReadMe.md: -------------------------------------------------------------------------------- 1 | Good question on DP. You should definitely try it. 2 | -------------------------------------------------------------------------------- /docs/_build/doctrees/index.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/doctrees/index.doctree -------------------------------------------------------------------------------- /docs/_build/html/_static/down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/down.png -------------------------------------------------------------------------------- /docs/_build/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/file.png -------------------------------------------------------------------------------- /docs/_build/html/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/minus.png -------------------------------------------------------------------------------- /docs/_build/html/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/plus.png -------------------------------------------------------------------------------- /docs/_build/html/_static/comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/comment.png -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #17/#5146 Distinct Echo Substrings/ReadMe.md: -------------------------------------------------------------------------------- 1 | Solve this question to know more about **Rolling Hashes** 2 | -------------------------------------------------------------------------------- /docs/_build/doctrees/environment.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/doctrees/environment.pickle -------------------------------------------------------------------------------- /docs/_build/html/_static/ajax-loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/ajax-loader.gif -------------------------------------------------------------------------------- /docs/_build/html/_static/up-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/up-pressed.png -------------------------------------------------------------------------------- /Pseudocode/Stack/Stock Span/Stock Span.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Stack/Stock Span/Stock Span.pdf -------------------------------------------------------------------------------- /docs/_build/html/_static/comment-close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/comment-close.png -------------------------------------------------------------------------------- /docs/_build/html/_static/down-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/down-pressed.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Images/1.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Images/2.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Images/3.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Images/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Images/4.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Images/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Images/5.png -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/Rating.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Round 582/Rating.PNG -------------------------------------------------------------------------------- /Pseudocode/Graphs/Word Ladder/Word_Ladder.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Word Ladder/Word_Ladder.pdf -------------------------------------------------------------------------------- /docs/_build/html/_static/comment-bright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/comment-bright.png -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato-Bold.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Inconsolata.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Inconsolata.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato-Regular.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bold.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bold.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bold.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab-Bold.ttf -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #152/#1176 Diet Plan Performance/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Simple usage of sliding window. Take care of the first and last windwo updation. 3 | -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Inconsolata-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Inconsolata-Bold.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bold.woff2 -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-italic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-italic.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-italic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-italic.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-italic.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-regular.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-regular.ttf -------------------------------------------------------------------------------- /Codeforces Contests/CF Edu Round 72/Images/Rating.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codeforces Contests/CF Edu Round 72/Images/Rating.PNG -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Lecture Notes/Heaps.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Lecture Notes/Heaps.pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Edit Distance/E_Dist.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Edit Distance/E_Dist.pdf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Inconsolata-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Inconsolata-Regular.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bolditalic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bolditalic.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bolditalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bolditalic.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-italic.woff2 -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-regular.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-regular.woff2 -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab-Regular.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #138/#1054 Distant Barcodes/ReadMe.md: -------------------------------------------------------------------------------- 1 | This is just a variation of **Rearrange characters in a string such that no equal characters are adjacent** 2 | -------------------------------------------------------------------------------- /SPOJ Online Judge/Sets/Colorful Arrays (CLFLARR)/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Intuition 2 | If you loved `Knight Tournament`, you are gonna love this too. 3 | 4 | ### Extra Tags 5 | Query Processing 6 | -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bolditalic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bolditalic.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/Lato/lato-bolditalic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/Lato/lato-bolditalic.woff2 -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep1.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep2.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep3.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep4.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep5.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Images/KahnAlgoStep6.png -------------------------------------------------------------------------------- /Pseudocode/Graphs/Topological Sort/Topological Sorting.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Topological Sort/Topological Sorting.pdf -------------------------------------------------------------------------------- /Pseudocode/Heaps/Merge K Sorted Vectors/Merge_K_Sorted.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Heaps/Merge K Sorted Vectors/Merge_K_Sorted.pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Maximum Sum Subarray/Kadane.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Maximum Sum Subarray/Kadane.pdf -------------------------------------------------------------------------------- /Pseudocode/Trees/Zig Zag Tree Traversal/Zig Zag Traversal.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Zig Zag Tree Traversal/Zig Zag Traversal.pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Longest Common Subsequence/LCS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Longest Common Subsequence/LCS.pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Trapping Rainwater/Trap_Water.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Trapping Rainwater/Trap_Water.pdf -------------------------------------------------------------------------------- /Pseudocode/Heaps/Minimum Cost to Connect Ropes/Min_Cost_Ropes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Heaps/Minimum Cost to Connect Ropes/Min_Cost_Ropes.pdf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Practice Problems/PS1_Recursion.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Practice Problems/PS1_Recursion.pdf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2 -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Lecture Notes/Dynamic Programming.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Lecture Notes/Dynamic Programming.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Practice Problems/PS4 (STL, Maps).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Practice Problems/PS4 (STL, Maps).pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Longest Increasing Subsequence/LIS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Longest Increasing Subsequence/LIS.pdf -------------------------------------------------------------------------------- /Pseudocode/Heaps/Median in a Stream of Integers/Median in Stream.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Heaps/Median in a Stream of Integers/Median in Stream.pdf -------------------------------------------------------------------------------- /Pseudocode/Trees/Vertical Order Traversal/Vertical Order Traversal.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Vertical Order Traversal/Vertical Order Traversal.pdf -------------------------------------------------------------------------------- /UVa Online Judge/Fenwick Tree/Potentiometers (12086)/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## Review 2 | * The most basic question on Fenwick Tree. 3 | * Time Taken : 12 Minutes for coding, 8 Minutes for Debugging 4 | * Penalty : None 5 | -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff -------------------------------------------------------------------------------- /docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/docs/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2 -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #130/#1019 Next Greater Element/ReadMe.md: -------------------------------------------------------------------------------- 1 | The code should be self explanatory. 2 | 3 | Here's another [link](https://www.geeksforgeeks.org/next-greater-element/) for reference. 4 | -------------------------------------------------------------------------------- /Pseudocode/Graphs/Minimum Jumps to Reach the End of Array/Min_Jumps.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Graphs/Minimum Jumps to Reach the End of Array/Min_Jumps.pdf -------------------------------------------------------------------------------- /Codechef/Dynamic Programming/Squared Subsequences (SQRDSUB)/Editorial.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Codechef/Dynamic Programming/Squared Subsequences (SQRDSUB)/Editorial.pdf -------------------------------------------------------------------------------- /Pseudocode/Linked Lists/Reverse a Linked List/Recursive and Iterative.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Linked Lists/Reverse a Linked List/Recursive and Iterative.pdf -------------------------------------------------------------------------------- /Pseudocode/Trees/Connect Nodes at the Same Level/Connect Nodes at Level.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Connect Nodes at the Same Level/Connect Nodes at Level.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/ReadMe.md: -------------------------------------------------------------------------------- 1 | This directory contains the *Lecture Notes*, *Programming Assignments* and *Practice Problems* of the **Data Structures and Algorithms** crash course that I took during the year 2019. 2 | -------------------------------------------------------------------------------- /Pseudocode/Trees/Level Order Traversal/Single Line/Level Order Traversal.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Level Order Traversal/Single Line/Level Order Traversal.pdf -------------------------------------------------------------------------------- /Pseudocode/Linked Lists/Clone a List with Random Pointers/Clone_List_Random.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Linked Lists/Clone a List with Random Pointers/Clone_List_Random.pdf -------------------------------------------------------------------------------- /Pseudocode/Queue/First Non Repeating in Stream/First Non Repeating in Stream.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Queue/First Non Repeating in Stream/First Non Repeating in Stream.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Lecture Notes/Last Lecture (Trees, Graphs, List).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Lecture Notes/Last Lecture (Trees, Graphs, List).pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_1.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_2.pdf -------------------------------------------------------------------------------- /Pseudocode/Trees/Level Order Traversal/Line By Line/Two Queues/Level_Order_Line_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Level Order Traversal/Line By Line/Two Queues/Level_Order_Line_1.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Lecture Notes/Lecture_1 (Recursion, Time Complexity).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Lecture Notes/Lecture_1 (Recursion, Time Complexity).pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Practice Problems/PS2 (Divide and Conquer, Sorting).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Practice Problems/PS2 (Divide and Conquer, Sorting).pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Buying and Selling Stocks/One Transaction/BSS 1 (DP).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Buying and Selling Stocks/One Transaction/BSS 1 (DP).pdf -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Wildcard Pattern Matching/WildCard_Pattern_Matching.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Dynamic Programming/Wildcard Pattern Matching/WildCard_Pattern_Matching.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_3 (STL).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_3 (STL).pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_4 (DP).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_4 (DP).pdf -------------------------------------------------------------------------------- /Interview Preparation/Algorithms and Data Structures/ReadMe.md: -------------------------------------------------------------------------------- 1 | This is the list of famous algorithms and Data Structures which I need to implement before sitting for interviews. 2 | 3 | ### Sorting 4 | * [ ] **Quick Sort** 5 | * [ ] **Merge Sort** 6 | -------------------------------------------------------------------------------- /Pseudocode/Trees/Level Order Traversal/Line By Line/Queue and Marker/Level_Order_Line_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Level Order Traversal/Line By Line/Queue and Marker/Level_Order_Line_2.pdf -------------------------------------------------------------------------------- /Kattis Online Judge/LCA on Trees/Tourists/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Review 2 | * Good question to get started with LCA on trees. 3 | * It has a good technique to answer path queries between 2 nodes. 4 | * It has a clean approach to iterate all the mutliple of a number. 5 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#72 Edit Distance/Readme.md: -------------------------------------------------------------------------------- 1 | [Blog](https://leetcode.com/problems/edit-distance/discuss/234043/C%2B%2B-Well-Commented-Solution-With-Explanation-DP) 2 | Update the description (with a working example). [Borrow an image from CLRS]. 3 | -------------------------------------------------------------------------------- /Pseudocode/Trees/Level Order Traversal/Line By Line/One Queueu and No Marker/Level_Order_Line_3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Trees/Level Order Traversal/Line By Line/One Queueu and No Marker/Level_Order_Line_3.pdf -------------------------------------------------------------------------------- /docs/_build/html/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 0a43d3252200fab10293636877f1b0fe 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1213 Intersection of 3 Sorted Array/ReadMe.md: -------------------------------------------------------------------------------- 1 | There exists a simple **O(n)** solution with a single pass (using Merge Sort Technique). I was trying that but gave up and used maps instead. Not a solution that I'm proud of. 2 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #138/#1051 Height Checker/ReadMe.md: -------------------------------------------------------------------------------- 1 | Such an easy question, Yet I was unable to solve it during the contest. 2 | I think it also has an O(n) solution. It's the same as **Minimum Length Subarray, Sorting which sorts the entire array**. 3 | -------------------------------------------------------------------------------- /Pseudocode/Linked Lists/Remove Duplicates from Sorted List/Delete All Copies/Remove_Duplicates_All.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Linked Lists/Remove Duplicates from Sorted List/Delete All Copies/Remove_Duplicates_All.pdf -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 581/D) Kirk and a Binary String/ReadMe.md: -------------------------------------------------------------------------------- 1 | [Problem Link](https://codeforces.com/contest/1204/problem/D2) 2 | [Editorial](https://codeforces.com/blog/entry/69244) 3 | [Submission Link](https://codeforces.com/contest/1204/submission/59446128) 4 | -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_5 (String Manipulation).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Crash Course (DS & Algorithms)/Programming Assignments/Programming_Assignment_5 (String Manipulation).pdf -------------------------------------------------------------------------------- /Pseudocode/Linked Lists/Remove Duplicates from Sorted List/Retain Single Copy/Remove_Duplicates_Some.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Just-A-Visitor/Algorithmic-Pseudocode/HEAD/Pseudocode/Linked Lists/Remove Duplicates from Sorted List/Retain Single Copy/Remove_Duplicates_Some.pdf -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Practice Problems/ReadMe.md: -------------------------------------------------------------------------------- 1 | 1) Practice Problem Set 1 on **Recursion** has been uploaded. 2 | 3 | 2) Practice Problem Set 2 on **Divide and Conquer** and **Sorting** has been uploaded. 4 | 5 | 3) Practice Problem Set 4 on **STL, Maps** has been uploaded. 6 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/ReadMe.md: -------------------------------------------------------------------------------- 1 | I solved 2 questions (First and the third). I need to upsolve the remaining questions 2 | 3 | ## To Do 4 | - [ ] **Day of the Week** 5 | - [ ] **Make array strictly increasing** 6 | - [ ] **Clean the code of the remaining 2 questions** 7 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1006 Clumsy Factorial/Explanation and Link.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/clumsy-factorial/discuss/252279/You-never-think-of-this-amazing-O(1)-solution 2 | 3 | 4 | 5 | https://leetcode.com/problems/clumsy-factorial/discuss/252247/C%2B%2BJava-Brute-Force 6 | -------------------------------------------------------------------------------- /SPOJ Online Judge/Trees/Minimum Vertex Cover (PT07X)/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### To Do 2 | * Explain the algorithm in detail. 3 | * Update the error journal (`parent == child`) 4 | 5 | 6 | ### Review 7 | * Time Taken --> 15 Minutes for Coding. 5 Minutes for Debugging (`Parent == Child`). 8 | * AC in first attempt. 9 | -------------------------------------------------------------------------------- /LeetCode Contests/Readme.md: -------------------------------------------------------------------------------- 1 | **Don't comment out bad code. Rewrite it.** 2 | 3 | # Contest Calendar 4 | * - [x] **LC Round 153** (8th September, 2019) 5 | * - [x] **Participation** 6 | * - [ ] **Upsolving** 7 | 8 | 9 | 10 | This directory contains the questions of all the contests in separate folders. 11 | -------------------------------------------------------------------------------- /UVa Online Judge/Binary Search the Answer/Monkey and Oiled Bamboo (12032)/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Review 2 | * Great question to get acquainted with the concept 3 | * Solved it in the first attempt 4 | * Insert a sentinel at the front to get rid of corner cases 5 | * Stick to the current template of Binary Search (Symmetric and less risky) 6 | -------------------------------------------------------------------------------- /Templates/Dijkstra's Algorithm/Adjacency List/ReadMe.md: -------------------------------------------------------------------------------- 1 | The code is more or less self explanatory after you've gone through the ReadMe of **Matrix and Maze**. 2 | 3 | A new function used is **vector :: assign**. It fills the values and resizes if needed! 4 | 5 | # Algorithm 6 | * Just the implementation of the pseudocode in **CLRS**. 7 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1004 Max Consecutive Ones III/Alternate Solutions.md: -------------------------------------------------------------------------------- 1 | Link 1 2 | 3 | https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window 4 | 5 | Link 2 6 | 7 | https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247559/C%2B%2BJava-5-lines-sliding-window 8 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #128/#1012 Complement of a Base 10 Integer/JavaScript (Complement of a Number).js: -------------------------------------------------------------------------------- 1 | var bitwiseComplement = function(num) 2 | { 3 | var all_bits_set = Math.pow(2,0); 4 | for(let i=1; all_bits_set& chips); 5 | }; 6 | 7 | int Solution :: minCostToMoveChips(vector& chips) 8 | { 9 | int odd = 0, even = 0; 10 | for(auto ele : chips) 11 | { 12 | if(ele % 2 != 0) 13 | odd++; 14 | else 15 | even++; 16 | } 17 | 18 | return min(odd, even); 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#61 Cyclic Right Shift for Linked Lists/ReadMe.md: -------------------------------------------------------------------------------- 1 | You should've gone for the head! 2 | Probably not in this case. Aim for the new tail. 3 | 4 | 5 | 6 | # Explain the non trivial parts 7 | 8 | 9 | # Credits 10 | This amazing idea was borrowed from [LeetCode's Discuss Post](https://leetcode.com/problems/rotate-list/discuss/22735/My-clean-C%2B%2B-code-quite-standard-(find-tail-and-reconnect-the-list)) 11 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1003 Check if Word is Valid After Substitution/JavaScript_BruteForce.js: -------------------------------------------------------------------------------- 1 | var isValid = function (str) 2 | { 3 | var pattern = "abc"; 4 | 5 | var position = str.indexOf(pattern); 6 | 7 | while(position != -1) 8 | { 9 | // Remember to overwrite the string 10 | str = str.replace(pattern, ""); 11 | position = str.indexOf(pattern); 12 | } 13 | 14 | return str.length==0; 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #130/#1018 Binary Prefix Divisible by 5/Optimized Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector prefixesDivBy5(vector& a); 5 | }; 6 | 7 | vector Solution :: prefixesDivBy5(vector& a) 8 | { 9 | vector answer; 10 | int num=0; 11 | for(int i=0; i 12 minutes for coding, 8 minutes for debugging 6 | * Penalty ==> None 7 | 8 | ## To Do 9 | * Clean up the code. 10 | * Write an extended descriptioin 11 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1196 Apples in Basket/Good Library Functions.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxNumberOfApples(vector& arr); 5 | }; 6 | 7 | int Solution :: maxNumberOfApples(vector& a) 8 | { 9 | sort(a.begin(), a.end()); 10 | 11 | for(int i = 1; i < a.size(); i++) 12 | a[i] += a[i-1]; 13 | 14 | auto itr = lower_bound(a.begin(), a.end(), 5000); 15 | return distance(a.begin(), itr); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#32 Longest Valid Parentheses/ReadMe.md: -------------------------------------------------------------------------------- 1 | The DP solution is so implementation-heavy. Document it properly. 2 | 3 | [Here's](https://leetcode.com/problems/longest-valid-parentheses/discuss/14140/Constant-space-O(n)-time-with-forward-and-backward-pass) a solution using 2 traversals and O(1) space. 4 | 5 | Read the [Comments](https://leetcode.com/problems/longest-valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query=) section to get a better understanding. 6 | -------------------------------------------------------------------------------- /Templates/Printing a Matrix/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## Review 2 | It's just a fancy way to avoid braces while printing a matrix. Use it only if you are comfortable with it. It might look cryptic at first, but once you understand the concept, it's very easy. 3 | 4 | ## Why does it Work? 5 | `" \n"` is a `char*`. Let's call it `str`. So, `str[0]` gives us ` `, while `str[1]` gives us `\n`. Now, `str[false]` gives us a space while `str[true]` gives us a new line. Hence, we get the appropriate spacing after each row. 6 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #8/#1180 Substrings with one Distinct/DP Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countLetters(string str); 5 | }; 6 | 7 | int Solution :: countLetters(string str) 8 | { 9 | int n = str.length(); 10 | vector good(n,1); 11 | 12 | for(int i = n-2; i >= 0; i--) 13 | if(str[i] == str[i+1]) 14 | good[i] = good[i+1] + 1; 15 | 16 | return accumulate(good.begin(), good.end(), 0); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#721 Accounts Merge/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Review 2 | * Passed all the test cases in the first submission. However, I think the solution is a bit inefficient as I'm creating the DSU using maps (and not arrays). There are a couple of great (and short) solutions on Discuss. I need to go through them. 3 | * This is an excellent question to practice Graphs and DSUs 4 | 5 | ### To Do 6 | * Make the code more concise and efficient 7 | * Explain your approach 8 | * Attempt it via Graph (DFS) 9 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #138/#1051 Height Checker/Sorting Based Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int heightChecker(vector& heights); 5 | }; 6 | 7 | int Solution :: heightChecker(vector& heights) 8 | { 9 | vector copy = heights; 10 | sort(heights.begin(), heights.end()); 11 | 12 | int count = 0; 13 | for(int i=0; i decompressRLElist(vector& nums); 5 | }; 6 | 7 | vector Solution :: decompressRLElist(vector& a) 8 | { 9 | vector res; 10 | 11 | int n = a.size(); 12 | int ind = 1; 13 | while(ind < n) 14 | { 15 | int element = a[ind]; 16 | int copies = a[ind - 1]; 17 | 18 | while(copies--) 19 | res.push_back(element); 20 | 21 | ind += 2; 22 | } 23 | 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#141 Loop Detection in Linked List/ReadMe.md: -------------------------------------------------------------------------------- 1 | Explain the proof. [**Very Important**] 2 | 3 | 4 | # Reversal Approach 5 | 6 | Keep reversing the list iteratively (using the famous technique). If there is a loop, you'll eventually come back to **head**. If not, you'll hit a null pointer. 7 | 8 | ### Credits 9 | 10 | This approach was told to me by a friend, Ankur Gautam. This is an amazing solution with an out of box thinking approach. Surprisingly, it's not famous. (Well, it does destroy the list, so that's a drawback). 11 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Review 2 | **Rank** : 1258/6650 3 | 4 | **Submission Time** 5 | 6 | Q1) 4 minutes 7 | Q2) 37 minutes 8 | Q3) ---- 9 | Q4) 26 minutes 10 | 11 | This is the fastest time in which I have solved the 4th question. I solved 3 questions (except the second last one) in under 37 minutes. The second last one was also easy (Plain dfs implementation on matrix). But, I was feeling too sleepy and lazy! 12 | 13 | 14 | # To Do 15 | Solve the third question (#1219 -- Maximum Gold in a Path). It's a simple DFS. 16 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1197 Minimum Knight Moves/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | The moves are symmetric. Hence, we can just assume the problem to be in the first quadrant. Consequently, a simple BFS would give us the required result. We maintain the `visited` state in the `count` matrix itself. We initialize it to -1, meaning it has not been visited. If it is visited, we can just store the minimum number of steps taken to reach that cell. 3 | 4 | 5 | [Blog](https://leetcode.com/problems/minimum-knight-moves/discuss/387004/Everything-is-in-First-Quadrant) 6 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/#1217 Play with Chips/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | There's no cost to move numbers by a difference of 2. Hence, we can move all even numbers to 0 and all odd numbers to 1 without any cost. Now, finally, we need to bring all numbers to zero or 1. Hence, we find out whether moving the odd numbers or the even numbers would incur a greater cost. We return the minimum of the two 3 | 4 | # Blog 5 | [Link](https://leetcode.com/problems/play-with-chips/discuss/398178/Detailed-Explanation-O(n)-or-O(1)-Everything-is-in-0-or-1) 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #8/#1181 Before After Puzzle/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Consider all `nC2` pairs. For each pair, extract the individual strings in a vector. If the last element of one vector is equal to the first element of the second vector, then merge the 2 vectors and store it in a set. Finally, return the elements from the set. Of course, it can be done without streaming the string but this is another way to look at the problem. 3 | 4 | 5 | [Blog](https://leetcode.com/problems/before-and-after-puzzle/discuss/376910/A-Novel-Method-using-StringStream-C%2B%2B-Explained) 6 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/#1021 Best SightSeeing Pair/Dynamic Programming O(1) space.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxScoreSightseeingPair(vector& a); 5 | }; 6 | 7 | int Solution :: maxScoreSightseeingPair(vector& a) 8 | { 9 | int n = a.size(); 10 | int maxOverallGain = INT_MIN; 11 | int maxEndRight = a[n-1] - (n-1); 12 | for(int i=n-2; i>=0; i--) 13 | { 14 | maxEndRight = max(maxEndRight, a[i+1] - (i+1)); 15 | maxOverallGain = max(maxOverallGain, a[i] + i + maxEndRight); 16 | } 17 | return maxOverallGain; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/#1022 Smallest Integer with only 1's Divisible by K/C++ Implementation.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int smallestRepunitDivByK(int k); 5 | }; 6 | 7 | int Solution :: smallestRepunitDivByK(int k) 8 | { 9 | if(k%2==0 || k%5==0) return -1; 10 | int prevRem=1, newRem, sum=0; 11 | int maxLength = 100000; 12 | for(int power=0; power 2 | using namespace std; 3 | 4 | /* Technique to travel the four cardinal directions */ 5 | void travelCardinalDirections(vector> &mat, int row, int col) 6 | { 7 | // Defining directions with [row][col] as origin 8 | int dx[] = {-1, 0, 1, 0}; 9 | int dy[] = {0, 1, 0, -1}; 10 | 11 | for(int i=0; i<4; i++) 12 | { 13 | int x = row + dx[i]; 14 | int y = col + dx[i]; 15 | 16 | // Access mat[x][y] 17 | } 18 | } 19 | int main() 20 | { 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Templates/Comparators/The Fundamentals (Conceptual).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Edge 5 | { 6 | public: 7 | int u, v, weight; 8 | 9 | public: 10 | Edge(int u, int v, int weight) 11 | { 12 | this->u = u, this->v = v; 13 | this->weight = weight; 14 | } 15 | 16 | bool operator < (const Edge& big) const 17 | { 18 | if(weight == big.weight) 19 | { 20 | if(u == big.u) 21 | return v < big.v; 22 | 23 | return u < big.u; 24 | } 25 | 26 | return weight < big.weight; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | cout<<"GfG!"; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 581/ReadMe.md: -------------------------------------------------------------------------------- 1 | # To Do 2 | * - [ ] Implementation / Understanding of **A** 3 | * - [ ] Implementation / Understanding of **B** 4 | * - [ ] Proof of Correctness and Implementation of **Floyd Warshall** 5 | * - [ ] Editorial of Problem **C**(Based on Floyd Warshall) 6 | * - [ ] Proof of Correctness of **D** (Based on Valid Parentheses) 7 | * - [ ] DP approach for **D** 8 | * - [ ] Implementation / Understanding of **E** 9 | 10 | I forgot to register for the contest. If I would have registered, I could have only solved C, which would later prove to be wrong (by myself). 11 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1198 Smallest Common Element/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | First of all, remove the duplicate elements from each row. This can be easily done via the `erase` and `unique` function. Now, we build a hashmap to maintain the frequency of each element. Finally, we traverse the first row fo the matrix in a sorted order and return the first value which has frequency equal to the number of rows in the matrix. If there is no such element present, we return -1. 3 | 4 | 5 | [Blog](https://leetcode.com/problems/find-smallest-common-element-in-all-rows/discuss/386997/A-Concise-Implementation-C%2B%2B) 6 | -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Programming Assignments/ReadMe.md: -------------------------------------------------------------------------------- 1 | **24th September, 2019** : Instructions for submission of programming assignments has been uploaded. 2 | 3 | **25th September, 2019** : Programmming assignment 2 (along with hints) has been uploaded. 4 | 5 | **29th September, 2019** : Programmming assignment 3 on STL (along with hints) has been uploaded. 6 | 7 | **3rd October, 2019** : Programmming assignment 4 on DP has been uploaded. 8 | 9 | **7th October, 2019** : Programming assignment 5 on String Manipulation has been uploaded. All the problems have less than 10-15 lines of code if you do it properly. 10 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#189 Rotate Array/Triple Reversal Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void rotate(vector& v, int k); 5 | }; 6 | 7 | /* Rotates the array to the right by K */ 8 | void Solution :: rotate(vector& v, int k) 9 | { 10 | // Extract size and normalize the shift 11 | int n = v.size(); 12 | k = k%n; 13 | 14 | // Reverse the entire array 15 | reverse(v.begin(), v.end()); 16 | 17 | // Reverse first k elements 18 | reverse(v.begin(), v.begin() + k); 19 | 20 | // Reverse the last (n-k) elements 21 | reverse(v.begin()+k, v.end()); 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #17/#5145 Even GrandParents Sum/Inorder Traversal (Clean).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int sumEvenGrandparent(TreeNode* root, bool parentsEven, bool grandParentsEven); 5 | }; 6 | 7 | int Solution :: sumEvenGrandparent(TreeNode* root, bool parentsEven = false, bool grandParentsEven = false) 8 | { 9 | if(!root) 10 | return 0; 11 | 12 | int sum = 0; 13 | if(grandParentsEven) 14 | sum += root->val; 15 | 16 | sum += sumEvenGrandparent(root->left, root->val%2 == 0, parentsEven); 17 | sum += sumEvenGrandparent(root->right, root->val%2 == 0, parentsEven); 18 | 19 | return sum; 20 | } 21 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = . 8 | BUILDDIR = _build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #135/ReadMe.md: -------------------------------------------------------------------------------- 1 | I have mixed feelings about this contest. It's been a while since I gave my last contest. 2 | Here are the statistics 3 | 4 | * **Questions Solved** ==> 2 out of 4 [Q1, Q2] 5 | * **Submission Time** ===> Q1) 31 Minutes, Q2) 18 Minutes 6 | * **Rank** ===> 858/3636 7 | 8 | The contest was indeed a tough one. Even **Votrubac** solved only the first 2 questions (which was quite shocking, as he gets every question in each contest, with a clean code). 9 | 10 | I haven't upsolved the remaining questions. **I'm too lazy**. My solutions for the first 2 questions weren't upto the mark, so I avoided posting on **Discuss**. 11 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1003 Check if Word is Valid After Substitution/Walid Word Checking_BruteForce.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool isValid(string str); 9 | }; 10 | 11 | bool Solution :: isValid(string str) 12 | { 13 | string pattern = "abc"; 14 | 15 | auto position = str.find(pattern); 16 | 17 | while(position != string::npos) 18 | { 19 | str.erase(position, pattern.length()); 20 | position = str.find(pattern); 21 | } 22 | 23 | return str.empty(); 24 | } 25 | int main() 26 | { 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Templates/Printing a Matrix/The Fancy Approach.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printMatrix(vector> &mat) 5 | { 6 | int R = mat.size(); 7 | int C = mat[0].size(); 8 | 9 | for(int i = 0; i < R; i++) 10 | for(int j = 0; j < C; j++) 11 | cout << mat[i][j] << " \n"[j == C - 1]; 12 | } 13 | 14 | void scanMatrix(vector> &mat) 15 | { 16 | for(auto &row_vec : mat) 17 | for(auto &ele : row_vec) 18 | cin >> ele; 19 | } 20 | int main() 21 | { 22 | int n; 23 | cin >> n; 24 | 25 | vector> mat(n, vector(n,0)); 26 | 27 | scanMatrix(mat); 28 | printMatrix(mat); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #128/ReadMe.md: -------------------------------------------------------------------------------- 1 | **LC#128 Contest Review** 2 | 3 | **Questions Solved** ---- 2/4 4 | 5 | **Penalties** ------ 2 times on question 1 6 | 7 | **Submission Time** ------- Q1) 8 minutes, 10 minutes, 12 minutes 8 | 9 | Q2) 21 minutes 10 | 11 | **Rank** ------ 1621 / 5164 12 | 13 | 14 | **Comments** 15 | 16 | * Accidentally saw the hints for Q3 (which uses binary search on answer). Didn't feel motivated to code it at that time as the implementation wasn't neat. I hope to solve it later in a neat way. 17 | 18 | * After the contest, I saw the hints for Q4 (which was very easy). I'll try it later today, 19 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1198 Smallest Common Element/Library.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int smallestCommonElement(vector>& mat); 5 | }; 6 | 7 | int Solution :: smallestCommonElement(vector>& mat) 8 | { 9 | for(auto &v : mat) 10 | v.erase(unique(v.begin(), v.end()), v.end()); 11 | 12 | map count; 13 | 14 | for(auto &row_vec : mat) 15 | for(auto &ele : row_vec) 16 | count[ele]++; 17 | 18 | int rowCount = mat.size(); 19 | 20 | for(auto &ele : mat[0]) 21 | if(count[ele] == rowCount) 22 | return ele; 23 | 24 | return -1; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#796 Are 2 Strings Rotations/Concatenation Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool rotateString(string text, string pattern) 5 | { 6 | // Rotating strings does not change their length 7 | if(text.length()!=pattern.length()) return false; 8 | 9 | // Concatenate the first string to itself to get the rid of circular searching 10 | string concatenatedString = text + text; 11 | 12 | // If it is a rotation, then it must occur as a substring of the concatenated string 13 | if(concatenatedString.find(pattern) != string::npos) return true; 14 | else return false; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1003 Check if Word is Valid After Substitution/JavaScript_Optimized.js: -------------------------------------------------------------------------------- 1 | var isValid = function(str) 2 | { 3 | var stack = []; 4 | var n; 5 | 6 | // Traverse the string and keep deleting 'abc' in O(1) 7 | for(let i=0; i=2 && stack[n-1]=='b' && stack[n-2]=='a') 16 | stack.pop(), stack.pop(); 17 | } 18 | 19 | return stack.length==0; 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1007 BST From Preorder/Explanation and Link.md: -------------------------------------------------------------------------------- 1 | **Alternate Solutions** 2 | 3 | https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252232/JavaC%2B%2BPython-O(N)-Solution 4 | 5 | 6 | https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252273/C%2B%2B-6-lines 7 | 8 | https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252754/Java-Stack-Iterative-Solution 9 | 10 | 11 | https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversa/ 12 | 13 | 14 | [GeekForGeeks Stack Explanation](https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/) 15 | -------------------------------------------------------------------------------- /HackerRank/Dynamic Programming/Red John is Back/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Review 2 | * The approach is simple. The first 4 cases would be the base case. Now, suppose `n > 4`. Let us observe the first block that we insert. If we decide to insert it vertically, we are interested in the number of ways of inserting the remaining blocks to the right of it according to the rules of the game. 3 | * On the other hand, if we decide to place it horizontally, we would have to supply 3 more blocks to fill the gap. With the remaining `n-4` blocks, we are interested in the number of ways of arranging them. 4 | * The total ways would be the sum of them. 5 | * After that, it is just standard Sieve Implementation. (Implement Sieve properly, don't run the outer loop from `1`). 6 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1213 Intersection of 3 Sorted Array/HashMap.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3); 5 | }; 6 | 7 | vector Solution :: arraysIntersection(vector& a, vector& b, vector& c) 8 | { 9 | map count; 10 | 11 | for(auto ele : a) 12 | count[ele]++; 13 | 14 | for(auto ele : b) 15 | count[ele]++; 16 | 17 | for(auto ele : c) 18 | count[ele]++; 19 | 20 | vector result; 21 | for(auto ele : count) 22 | if(ele.second == 3) 23 | result.push_back(ele.first); 24 | 25 | return result; 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1253 Reconstruct Binary Matrix/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | * First, intialize both the rows as `0`. Now, fill the indices where the vertical column sum is `2` (as they don't have a choice). So, now we only need to make choices for the columns with sum `1`. Find out the current sum of the first row. Compare it with the required amount. If the difference becomes negative, it means that there is no solution. Else, greedily fill the required `1s` in the top row and the remaining `1s` in the bottom row. Finally, check if the sum of the bottom row equals `lower` 3 | 4 | 5 | # Blog 6 | [Link](https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/425170/Detailed-Explanation-using-Greedy-Approach) 7 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1216 Valid Palindrome/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Find the longest common subsequence of the string and its reverse. Now, `n - lcs_length` is the smallest number of characters that needs to be deleted from the string to make it a palindrome. Hence, we just check whether this value is less than or equal to `k` or not. 3 | 4 | # To Do 5 | It can also be done using **Edit Distance**. (Why is `edit_distance <= 2*k` and not `k`?) 6 | 7 | # Review 8 | Excellent question to see the application of standard problems. It's like a new paradigm for **Palindromes** 9 | 10 | # Blog 11 | [Link](https://leetcode.com/problems/valid-palindrome-iii/discuss/397602/Detailed-Explanation-using-Longest-Common-Subsequence) 12 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1252 Cells with Odd Values/Simple.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int oddCells(int n, int m, vector>& indices); 5 | }; 6 | 7 | int Solution :: oddCells(int row, int col, vector>& indices) 8 | { 9 | vector> mat(row, vector(col,0)); 10 | for(auto vec : indices) 11 | { 12 | int r = vec.front(); 13 | int c = vec.back(); 14 | 15 | int i = r; 16 | for(int j = 0; j < col; j++) 17 | mat[i][j] += 1; 18 | 19 | int j = c; 20 | for(int i = 0; i < row; i++) 21 | mat[i][j] += 1; 22 | } 23 | 24 | int count = 0; 25 | for(int i = 0; i < row; i++) 26 | for(int j = 0; j < col; j++) 27 | if(mat[i][j] & 1) 28 | count++; 29 | 30 | return count; 31 | } 32 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#152 Maximum Product Subarray/Min_Max Optimized (Works).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProduct(vector& a); 5 | }; 6 | 7 | int Solution :: maxProduct(vector& a) 8 | { 9 | int n = a.size(); 10 | 11 | int max_ending_here = a[0]; 12 | int min_ending_here = a[0]; 13 | int max_so_far = a[0]; 14 | 15 | for(int i=1; i& arr, int difference); 5 | }; 6 | 7 | int Solution :: longestSubsequence(vector& a, int diff) 8 | { 9 | int n = a.size(); 10 | vector dp(n); 11 | 12 | unordered_map max_dp_value; 13 | dp[n-1] = 1; 14 | max_dp_value[a[n-1]] = 1; 15 | 16 | for(int i = n-2; i >= 0; i--) 17 | { 18 | int old_value = max_dp_value[a[i]]; 19 | 20 | int new_value = 1 + max_dp_value[a[i] + diff]; 21 | 22 | dp[i] = max(old_value, new_value); 23 | max_dp_value[a[i]] = dp[i]; 24 | } 25 | 26 | return *max_element(dp.begin(), dp.end()); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#83 Removes Duplicates from List (Retain Single Copy)/Recursive Approach.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | ListNode* deleteDuplicates(ListNode* head); 6 | }; 7 | 8 | /* Removes duplicates (while storing a single copy) */ 9 | ListNode* Solution :: deleteDuplicates(ListNode* head) 10 | { 11 | // Empty List / Single Element, Nothing to delete 12 | if(!head or !head->next) return head; 13 | 14 | /* Recursively delete duplicates in the remaining list */ 15 | 16 | // Remember to connect the returned value 17 | head->next = deleteDuplicates(head->next); 18 | 19 | // If values match, return the cleaned version, else original 20 | if(head->val == head->next->val) 21 | return head->next; 22 | else 23 | return head; 24 | } 25 | -------------------------------------------------------------------------------- /Crash Course II (DS & Algorithms)/Syllabus/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Data Structures 2 | * - [ ] Stack 3 | * - [ ] Queue 4 | * - [ ] Heaps/Priority Queue 5 | * - [ ] Linked List 6 | * - [ ] Binary Tree 7 | * - [ ] Disjoint Set Union 8 | * - [ ] Hashing 9 | 10 | ### Paradigms 11 | * - [ ] Recursion 12 | * - [ ] Divide and Conquer 13 | * - [ ] Sorting 14 | * - [ ] Dynamic Programming 15 | 16 | 17 | ### STL 18 | * - [ ] Vectors 19 | * - [ ] Iterators 20 | * - [ ] Comparators 21 | * - [ ] Strings 22 | * - [ ] Map/HashMap 23 | * - [ ] Sets/Multi Set 24 | 25 | ### Graph Theory 26 | * - [ ] DFS 27 | * - [ ] BFS 28 | * - [ ] Connected Components 29 | * - [ ] Cycle Detection 30 | * - [ ] Topological Sort (Kahn's) 31 | * - [ ] MST (Kruskal) 32 | 33 | ### Miscellaneous 34 | * - [ ] Time Complexity 35 | * - [ ] Introduction to OOPs 36 | -------------------------------------------------------------------------------- /Crash Course (DS & Algorithms)/Lecture Notes/ReadMe.md: -------------------------------------------------------------------------------- 1 | **24th September, 2019** : Lecture 1 (Recursion, Time Complexity) has been uploaded. 2 | 3 | **28th September, 2019** : Lecture 3 (STL / C++) has been uploaded. It's almost impossible to read them on your smartphones as they are in markdown format. Use a desktop / laptop instead. Feel free to experiment with the example codes with the given links. Use Google Chrome for better formatting. 4 | 5 | 6 | **5th October, 2019** : Notes on **Custom Comparators** has been uploaded. (Along with 2 Practice Problems) 7 | 8 | **7th October, 2019** : Short Notes on **Dynamic Programming** has been uploaded. 9 | 10 | **8th October, 2019** : Short Notes on **Heaps** has been uploaded. 11 | 12 | **11th October, 2019** : The Last Lecture on **Graphs, Trees, Linked List** has been uploaded. 13 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1214 Two Sum BST/HashMap Approach.cpp: -------------------------------------------------------------------------------- 1 | void populateMap(TreeNode* root, map &count) 2 | { 3 | if(!root) 4 | return; 5 | 6 | count[root->val]++; 7 | populateMap(root->left, count); 8 | populateMap(root->right, count); 9 | } 10 | 11 | class Solution 12 | { 13 | public: 14 | bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target); 15 | }; 16 | 17 | 18 | 19 | bool Solution :: twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) 20 | { 21 | map count1, count2; 22 | populateMap(root1, count1); 23 | populateMap(root2, count2); 24 | 25 | for(auto ele : count1) 26 | if(ele.first == target or count2[target - ele.first] != 0) 27 | return true; 28 | 29 | return false; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #152/#1176 Diet Plan Performance/Sliding Window.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int dietPlanPerformance(vector& calories, int k, int lower, int upper); 5 | }; 6 | 7 | int Solution :: dietPlanPerformance(vector& a, int k, int lower, int upper) 8 | { 9 | int n = a.size(); 10 | int res = 0; 11 | int sum = 0; 12 | 13 | for(int i = 0; i < k; i++) 14 | sum += a[i]; 15 | 16 | if(sum < lower) 17 | res--; 18 | if(sum > upper) 19 | res++; 20 | 21 | for(int i = k; i < n; i++) 22 | { 23 | sum -= a[i-k]; 24 | sum += a[i]; 25 | 26 | if(sum < lower) 27 | res--; 28 | if(sum > upper) 29 | res++; 30 | } 31 | 32 | 33 | return res; 34 | } 35 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #152/#1175 Prime Arrangements/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | * First, count all the primes from 1 to **n** using **Sieve**. Remember to terminate the outer loop at **sqrt(n)**. 3 | * Next , iterate over each positon and get the count of prime positions, call it `k`. 4 | * So, for the `k` prime numbers, we have limited choice, we need to arrange them in `k` prime spots. 5 | * For the `n-k` non prime numbers, we also have limited choice. We need to arrange them in `n-k` non prime spots. 6 | * Both the events are indepent, so the total ways would be product of them. 7 | * Number of ways to arrange `k` objects in `k` boxes is `k!`. 8 | * Use the property that `(a*b) %m = ( (a%m) * (b%m) ) % m`. 9 | 10 | 11 | 12 | [Blog Link](https://leetcode.com/problems/prime-arrangements/discuss/371968/Detailed-Explanation-using-Sieve) 13 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1196 Apples in Basket/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | The idea is very simple. Keep taking the elements in a greedily manner, that is, take the lightest elements first. This requires sorting the array. After that, I converted it into a **Prefix_Sum** array, and hence each entry would indicate the accumulated sum of the elements to the left. We just need to find the point where it reaches the maximum weight (or stays below it). Of course, a simple approach using `count` and `sum` suffices, I used iterator manipulation and library functions, specifically `auto`, `lower_bound` and `distance`. They can be quite handy at times. 3 | 4 | # Complexity 5 | **O(n log (n) )** 6 | 7 | 8 | 9 | [Blog](https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/discuss/386991/Same-Idea-Different-Implementation-C%2B%2B) 10 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1005 Maximize Sum Of Array After K Negations/ReadMe.md: -------------------------------------------------------------------------------- 1 | **Intuition** 2 | 3 | **Claim** We need to negate the minimum element in the array at each step 4 | 5 | **Proof** Observe that negating a positive element make us lose twice the contribution. 6 | So if the minimum element is positive,we would lose the least possible contribution by negating it. 7 | Also, observe that negating a negative element results in twice the contribution gain in magnitude. 8 | So the larger the magnitude of the negative element, the larger the gain. 9 | 10 | 11 | [Blog](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252317/detailed-explanation-using-min-heap-without-any-messy-indices) 12 | 13 | [Alternate Solution](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252254/C%2B%2BPython-Sort) 14 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#141 Loop Detection in Linked List/Reversal Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool hasCycle(ListNode *head); 5 | }; 6 | 7 | /* Detects cycle in a linked list */ 8 | bool Solution :: hasCycle(ListNode *head) 9 | { 10 | // Declare the auxillary pointers 11 | ListNode* current = head; 12 | ListNode* previous = nullptr; 13 | ListNode* temp = nullptr; 14 | 15 | // Perform the exact same steps a s reversal 16 | while(current) 17 | { 18 | // The usual stuff 19 | temp = current->next; 20 | current->next = previous; 21 | previous = current; 22 | current = temp; 23 | 24 | // Check if you encounter head again 25 | if(current==head) return true; 26 | 27 | } 28 | 29 | // The list was successfully reversed. No Cycle 30 | return false; 31 | } 32 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1003 Check if Word is Valid After Substitution/Concise and Optimized.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string str); 5 | }; 6 | 7 | /* Return true if the word is valid */ 8 | bool Solution :: isValid(string str) 9 | { 10 | vector specialStack; 11 | int n; 12 | 13 | // Traverse the string and keep deleting 'abc' in O(1) 14 | for(auto ele : str) 15 | { 16 | n = specialStack.size(); 17 | 18 | // If the character is 'c', pop the matching 'b' and 'a' from the stack, if they exist 19 | if(ele!= 'c' || n==0) specialStack.push_back(ele); 20 | else 21 | if(n>=2 && specialStack[n-1]=='b' && specialStack[n-2]=='a') 22 | specialStack.pop_back(), specialStack.pop_back(); 23 | } 24 | 25 | return specialStack.size()==0; 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/#1023 Binary string with substring from 1 to N/C++ [Bruteforce But works].cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool queryString(string S, int N); 5 | }; 6 | 7 | bool Solution :: queryString(string str, int N) 8 | { 9 | for(int i=1; i<=N; i++) 10 | { 11 | int number = i; 12 | string str_num = ""; 13 | 14 | // Convert the number to string 15 | while(number!=0) 16 | { 17 | str_num += number%2 + '0'; 18 | number = number/2; 19 | } 20 | 21 | // Reverse the string to get the correct representation 22 | reverse(str_num.begin(), str_num.end()); 23 | 24 | // Check if the number is present or not 25 | if(str.find(str_num)==string::npos) 26 | return false; 27 | } 28 | 29 | return true; 30 | } 31 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#151 Reverse a String Keeping The Words Intact/Explanation And Link.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | Approach 4 | 5 | * Create a new stream called newStream which behaves as if the characters of the current string are present in the standard 6 | input or cin 7 | * Start extracting each string from the streaming string 8 | * Keep pushing the words onto the stack. This ensures a LIFO order and the last word to enter would be popped first. 9 | * Keep doing the process till the stream becomes empty. 10 | * Extract words from the stack and append it to answer 11 | * Remember to append space if it is not the last word. 12 | 13 | Problem 14 | 15 | https://leetcode.com/problems/reverse-words-in-a-string/ 16 | 17 | Blog 18 | 19 | https://leetcode.com/problems/reverse-words-in-a-string/discuss/248752/C%2B%2B-Detailed-Explanation-stringstream-Memory-InEfficient 20 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #126/#1002 Find Common Charcters/Explantion and Link.md: -------------------------------------------------------------------------------- 1 | Approach 2 | 3 | * Create a vector freq that maps each character of the alphabet to its frequency in any given string. 4 | * Create a vector minMatching that stores the count of characters which occur in all the strings so far 5 | * Traverse the list of strings and for each string, update (overwrite) the freq vector and accordingly update the minMatching vector. 6 | * At the end, traverse the minMatching vector and append each character as a single string in the answer vector. 7 | 8 | Miscellaneous 9 | 10 | * The minMatching vector has been initialised with INT_MAX instead of 0 to handle the updation of first string. After that, all the non-appearing charcters would be set to zero. 11 | 12 | Link 13 | 14 | https://leetcode.com/problems/find-common-characters/discuss/247798/detailed-explanation-c-on 15 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#141 Loop Detection in Linked List/Walker & Runner Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool hasCycle(ListNode *head); 5 | }; 6 | 7 | /* Detects cycle in a linked list */ 8 | bool Solution :: hasCycle(ListNode *head) 9 | { 10 | // Start both the pointers at the head 11 | ListNode* walker = head; 12 | ListNode* runner = head; 13 | 14 | // Keep moving as long as both exist 15 | while(walker and runner) 16 | { 17 | // Take one/two step depending on the person 18 | walker = walker->next; 19 | runner = runner->next ? runner->next->next : nullptr; 20 | 21 | // The nullity check is imortant [Consider a single element] 22 | if(walker and runner and walker==runner) return true; 23 | } 24 | 25 | // If it has reached here, it means one pointer was null 26 | return false; 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#45 Jump Game II/Compact and Optimized (Final Version).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int jump(vector& nums); 5 | }; 6 | 7 | int Solution :: jump(vector& a) 8 | { 9 | int n = a.size(); 10 | 11 | // This also functions as the visited array 12 | vector level(n,-1); 13 | 14 | // Queue contains the indexes 15 | queue bfs; 16 | bfs.push(0); 17 | level[0] = 0; 18 | int min_un_reach = 1; 19 | 20 | /* min_un_reach denotes the minimum element which is not yet reached */ 21 | 22 | // Perform the bfs 23 | while(!bfs.empty()) 24 | { 25 | int ind = bfs.front(); 26 | bfs.pop(); 27 | 28 | 29 | while(min_un_reach < n and min_un_reach <= ind + a[ind]) 30 | { 31 | bfs.push(min_un_reach); 32 | level[min_un_reach] = level[ind] + 1; 33 | min_un_reach++; 34 | } 35 | } 36 | 37 | return level.back(); 38 | } 39 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #128/#1013 Pairs with Sum divisible by 60/JavaScript Implementation.js: -------------------------------------------------------------------------------- 1 | /* Returns the number of pairs whose sum is divisible by 60 */ 2 | var numPairsDivisibleBy60 = function(time) 3 | { 4 | // The reference for modular arithmetic 5 | const ref=60; 6 | 7 | // Initilize the map 8 | var count = []; 9 | for(let i=0; i 2 | using namespace std; 3 | 4 | /* Note : Be very careful with comparators if you are going to use equality method 5 | * If there are 2 small arguments, you can just skip 'auto' and compare directly 6 | * The comparator can never look like lhs <= rhs. Why is that? Think Carefully. 7 | */ 8 | 9 | /* It's missing one thing. You always have to provide arguments during instantiation */ 10 | 11 | class Edge 12 | { 13 | public: 14 | int u, v, weight; 15 | 16 | public: 17 | Edge(int u, int v, int weight) 18 | { 19 | this->u = u, this->v = v; 20 | this->weight = weight; 21 | } 22 | 23 | bool operator < (const Edge& big) const 24 | { 25 | auto lhs = tie(weight, u, v); 26 | auto rhs = tie(big.weight, big.u, big.v); 27 | 28 | return lhs < rhs; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | cout<<"GfG!"; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #128/#1013 Pairs with Sum divisible by 60/Pairs with Sum divisible by 60.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numPairsDivisibleBy60(vector& time); 5 | }; 6 | 7 | /* Returns the number of pairs whose sum is divisible by 60 */ 8 | int Solution :: numPairsDivisibleBy60(vector& a) 9 | { 10 | // The reference for modular arithmetic 11 | int ref=60; 12 | 13 | // Populate the map in modular arithemtic 14 | unordered_map count; 15 | for(auto ele : a) 16 | count[ele%ref]++; 17 | 18 | // Traverse from 1 to 29 and update answer 19 | int answer=0; 20 | for(int i=1; i prime(n + 1, true); 10 | prime[0] = false; 11 | prime[1] = false; 12 | 13 | for(int i = 2; i <= sqrt(n); i++) 14 | { 15 | if(prime[i]) 16 | for(int factor = 2; factor*i <= n; factor++) 17 | prime[factor*i] = false; 18 | } 19 | 20 | int primeIndices = 0; 21 | for(int i = 1; i <= n; i++) 22 | if(prime[i]) 23 | primeIndices++; 24 | 25 | int mod = 1e9 + 7, res = 1; 26 | 27 | for(int i = 1; i <= primeIndices; i++) 28 | res = (1LL*res*i) % mod; 29 | for(int i = 1; i<= (n-primeIndices); i++) 30 | res = (1LL*res*i) % mod; 31 | 32 | return res; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /UVa Online Judge/Priority Queue/Add All (10954)/Min Heap (Greedy).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void solve(int size) 5 | { 6 | vector vec(size); 7 | for(auto &ele : vec) 8 | cin >> ele; 9 | 10 | priority_queue, greater> minHeap; 11 | for(auto ele : vec) 12 | minHeap.push(ele); 13 | 14 | int totalCost = 0; 15 | int currentCost; 16 | while(minHeap.size() > 1) 17 | { 18 | int min_ele = minHeap.top(); 19 | minHeap.pop(); 20 | 21 | int second_min_ele = minHeap.top(); 22 | minHeap.pop(); 23 | 24 | currentCost = min_ele + second_min_ele; 25 | totalCost += currentCost; 26 | 27 | minHeap.push(currentCost); 28 | } 29 | 30 | cout << totalCost << endl; 31 | } 32 | 33 | int main() 34 | { 35 | int size; 36 | cin >> size; 37 | 38 | while(size != 0) 39 | { 40 | solve(size); 41 | cin >> size; 42 | } 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/#1020 Partition array into 3 parts/Prefix Sum Method.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool canThreePartsEqualSum(vector& A); 5 | }; 6 | 7 | bool Solution :: canThreePartsEqualSum(vector& a) 8 | { 9 | int sum = accumulate(a.begin(), a.end(), 0); 10 | 11 | if(sum%3!=0) return false; 12 | 13 | int subSum = sum/3; 14 | 15 | bool firstFound=false, secondFound = false, thirdFound = false; 16 | 17 | int prefixSum=0; 18 | for(auto ele : a) 19 | { 20 | prefixSum += ele; 21 | if(!firstFound && prefixSum==subSum) firstFound = true; 22 | else if(firstFound && !secondFound && prefixSum==subSum*2) secondFound = true; 23 | else if(firstFound && secondFound && prefixSum==subSum*3) thirdFound = true; 24 | } 25 | 26 | return (firstFound && secondFound && thirdFound); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#206 Reverse a Linked List/Iterative Reverse JavaScript.js: -------------------------------------------------------------------------------- 1 | /* Reverses the linked list iteratively */ 2 | var reverseList = function(head) 3 | { 4 | // Pointers to keep track of 3 consecutive nodes 5 | var previous = null; 6 | var current = head; 7 | var temp; 8 | 9 | // Traverse the list and keep reversing the elements as you encounter them 10 | while(current) 11 | { 12 | // Store the location of the next element 13 | temp = current.next; 14 | 15 | // Link the current element to the previous one 16 | current.next = previous; 17 | 18 | // Update the previous to current 19 | previous = current; 20 | 21 | // Update current to the original next element 22 | current = temp; 23 | } 24 | 25 | // Remember to return previous as current would be null 26 | return previous; 27 | }; 28 | -------------------------------------------------------------------------------- /Templates/Comparators/The Worst (and Wrong).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Edge 5 | { 6 | public: 7 | int u, v, weight; 8 | 9 | public: 10 | Edge(int u, int v, int weight) 11 | { 12 | this->u = u, this->v = v; 13 | this->weight = weight; 14 | } 15 | 16 | bool operator < (const Edge& big) const 17 | { 18 | return weight < big.weight; 19 | } 20 | }; 21 | 22 | /* Why is this comparator wrong? 23 | * Hint : It would work correctly for Kruskal but not for Dijkstra. Why? 24 | * Suppose you have one element in a set (2,3 weight = k) 25 | * Now, you try to find an element (6, 7, weight = k) 26 | * Do you think you'll get the correct answer. Experiment with it. 27 | * But how does it work correctly for Kruskal? 28 | * Why does it fail for Dijkstra. I mean, what do I care about vertex ordering by its index? 29 | */ 30 | 31 | int main() 32 | { 33 | cout<<"GfG!"; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #8/#1180 Substrings with one Distinct/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Call a substring good if it only contains a single distinct character. Now, define a dp state, where `dp[i]` represents the number of good substrings starting at `i`. 3 | Now, if `str[i] == str[i+1]` , it means that `str[i]` can be appended to each good substring formed by the index `i+1`. Moreover, it can also create a single substring consisting of just `str[i]`. 4 | 5 | Hence, the final DP relation is `dp[i] = (str[i] == str[i+1]) ? dp[i+1] + 1 : 1`. 6 | 7 | # Reducing the space Complexity 8 | Notice that to compute `dp[i]`, we only need the information of `i+1`. Hence, we can use a single counter, without having to create a vector. Hence, the space complexity would be O(1). 9 | 10 | 11 | 12 | [Blog](https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/discuss/376879/A-Novel-Method-with-DP-O(n)-or-O(1)-With-Explanation) 13 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1215 Stepping Numbers/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | The idea is to create all the valid numbers in advance. Start out with a single number. There can be at most 2 possibility for the number containing one extra digit at the end. 3 | 4 | * If the last number is not 9, then the next end digit can be `current_end_digit + 1`. We call this the left child. 5 | * If the last number is not 0, then the next end digit can be `current_end_digit - 1`. We call this the right child. 6 | 7 | We keep on creating the tree in a post order traversal and terminate the recursion as soon as we see a number bigger than the limit. In the meanwhile, we keep storing the created numbers in a set. Finally, we traverse the set in a sorted order and extract the numbers within the given range into a vector. 8 | 9 | 10 | # Blog 11 | [Link](https://leetcode.com/problems/stepping-numbers/discuss/397610/Detailed-Explanation-using-Post-Order-Traversal) 12 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #131/#1022 Sum of root to leaf Binary Numbers/No Data Structure Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int sum=0; 4 | public: 5 | int sumRootToLeaf(TreeNode* root, int oldNumber); 6 | }; 7 | 8 | /* Returns the sum of all paths from root to leaf */ 9 | int Solution :: sumRootToLeaf(TreeNode* root, int oldNumber=0) 10 | { 11 | // If the tree doesn't exist, the number formed is 0 12 | if(!root) return 0; 13 | 14 | int newNumber = oldNumber*2 + root->val; 15 | 16 | // If it is a leaf node, we have enumerated a path 17 | if(!root->left and !root->right) 18 | { 19 | sum += newNumber; 20 | return sum; 21 | } 22 | 23 | // If it is not a leaf node, enumerate paths in both directions 24 | sumRootToLeaf(root->left, newNumber); 25 | sumRootToLeaf(root->right, newNumber); 26 | 27 | // Return the sum of all numbers in both the halfs 28 | return sum; 29 | } 30 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1215 Stepping Numbers/Post Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | set collect; 4 | int limit; 5 | public: 6 | void BuildTree(long root); 7 | vector countSteppingNumbers(int low, int high); 8 | }; 9 | 10 | void Solution :: BuildTree(long root) 11 | { 12 | if(root > limit) 13 | return; 14 | collect.insert(root); 15 | 16 | int lastVal = root%10; 17 | 18 | if(lastVal != 9) 19 | BuildTree(root*10 + (lastVal + 1)); 20 | 21 | if(lastVal != 0) 22 | BuildTree(root*10 + (lastVal - 1)); 23 | } 24 | 25 | vector Solution :: countSteppingNumbers(int low, int high) 26 | { 27 | limit = high; 28 | for(int i = 0; i <= 9; i++) 29 | BuildTree(i); 30 | 31 | vector result; 32 | for(auto ele : collect) 33 | if(low <= ele and ele <= high) 34 | result.push_back(ele); 35 | 36 | return result; 37 | } 38 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #153/#1184 Distance Between Bus Stops/Contest Submission (Dirty).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int distanceBetweenBusStops(vector& distance, int start, int destination); 5 | }; 6 | 7 | int Solution :: distanceBetweenBusStops(vector& dist, int start, int destination) 8 | { 9 | int n = dist.size(); 10 | int current = start; 11 | int forward = 0; 12 | while(true) 13 | { 14 | forward += dist[current]; 15 | current = (current + 1)%n; 16 | if(current == destination) 17 | break; 18 | 19 | 20 | } 21 | 22 | int backward = 0; 23 | current = start; 24 | 25 | while(true) 26 | { 27 | current = (current) ? current - 1 : n-1; 28 | backward += dist[current]; 29 | 30 | if(current == destination) 31 | break; 32 | 33 | 34 | } 35 | 36 | return min(forward, backward); 37 | } 38 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/#1220 Count Vowel Permutation/Graph DP.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countVowelPermutation(int n); 5 | }; 6 | 7 | int Solution :: countVowelPermutation(int n) 8 | { 9 | vector> dp(n+1, vector(5, 0)); 10 | 11 | int MOD = 1e9 + 7; 12 | 13 | /* dp[i][j] denotes the number of valid strings of length n */ 14 | 15 | for(int i = 0; i < 5; i++) 16 | dp[1][i] = 1; 17 | 18 | for(int i = 1; i < n; i++) 19 | { 20 | dp[i+1][0] = (dp[i][1] + dp[i][2] + dp[i][4]) %MOD; 21 | 22 | dp[i+1][1] = (dp[i][0] + dp[i][2]) % MOD; 23 | 24 | dp[i+1][2] = (dp[i][1] + dp[i][3]) % MOD; 25 | 26 | dp[i+1][3] = dp[i][2]; 27 | 28 | dp[i+1][4] = (dp[i][2] + dp[i][3]) % MOD; 29 | } 30 | 31 | int res = 0; 32 | for(int i = 0; i < 5; i++) 33 | res = (res + dp[n][i]) % MOD; 34 | 35 | return res; 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#45 Jump Game II/Optimized BFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int jump(vector& nums); 5 | }; 6 | 7 | int Solution :: jump(vector& a) 8 | { 9 | int n = a.size(); 10 | 11 | // This also functions as the visited array 12 | vector level(n,-1); 13 | 14 | // Queue contains the indexes 15 | queue bfs; 16 | bfs.push(0); 17 | level[0] = 0; 18 | int maxReach = 0; 19 | 20 | /* maxReach denotes the maximum element reached */ 21 | 22 | // Perform the bfs 23 | while(!bfs.empty()) 24 | { 25 | int ind = bfs.front(); 26 | bfs.pop(); 27 | 28 | // Check if you can reach the next element 29 | while(maxReach + 1 < n and maxReach + 1 <= ind + a[ind]) 30 | { 31 | maxReach++; 32 | level[maxReach] = level[ind] + 1; 33 | bfs.push(maxReach); 34 | } 35 | } 36 | 37 | return level.back(); 38 | } 39 | -------------------------------------------------------------------------------- /.github/config.yml: -------------------------------------------------------------------------------- 1 | # Configuration for welcome - https://github.com/behaviorbot/welcome 2 | 3 | # Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome 4 | 5 | # Comment to be posted to on first time issues 6 | newIssueWelcomeComment: > 7 | Thanks for opening your first issue here! Be sure to follow the issue template! 8 | 9 | # Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome 10 | 11 | # Comment to be posted to on PRs from first time contributors in your repository 12 | newPRWelcomeComment: > 13 | Thanks for opening this pull request! Please check out our contributing guidelines. 14 | 15 | # Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge 16 | 17 | # Comment to be posted to on pull requests merged by a first time user 18 | firstPRMergeComment: > 19 | Congrats on merging your first pull request! We here at behaviorbot are proud of you! 20 | 21 | # It is recommended to include as many gifs and emojis as possible! 22 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#83 Removes Duplicates from List (Retain Single Copy)/Failed Approach.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | ListNode* deleteDuplicates(ListNode* head); 6 | }; 7 | 8 | /* Removes duplicates (while storing a single copy) */ 9 | ListNode* Solution :: deleteDuplicates(ListNode* head) 10 | { 11 | // Empty List / Single Element, Nothing to delete 12 | if(!head or !head->next) return head; 13 | 14 | // Recursively delete duplicates in the remaining list 15 | ListNode* nextDistinct = deleteDuplicates(head->next); 16 | 17 | // If values match, return the cleaned version, else original 18 | if(head->val == nextDistinct->val) 19 | return nextDistinct; 20 | else 21 | return head; 22 | } 23 | 24 | 25 | 26 | /* This approach is wrong. No pointers are modified (only the copies are returned). 27 | Consider [2,3,3]. The output is [2,3,3] instead of [2,3]. 28 | This happens because you are never changing the next field of any pointer 29 | */ 30 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#160 Intersection of 2 Linked Lists/Hashing Based Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* getIntersectionNode(ListNode *headA, ListNode *headB); 5 | }; 6 | 7 | /* Returns the intersection point of 2 linked lists */ 8 | ListNode* Solution :: getIntersectionNode(ListNode *headA, ListNode *headB) 9 | { 10 | // Create the map to store the address of the first list 11 | unordered_map address; 12 | 13 | // Populate the first list in the map 14 | while(headA) 15 | { 16 | address[headA] = 1; 17 | headA = headA->next; 18 | } 19 | 20 | // Traverse the second list and find the first repeating address 21 | while(headB) 22 | { 23 | // If the node is hashed, it is the start of the intersection 24 | if(address.find(headB)!=address.end()) 25 | return headB; 26 | headB = headB->next; 27 | } 28 | 29 | // If it reaches here, it means no intersection 30 | return nullptr; 31 | } 32 | -------------------------------------------------------------------------------- /UVa Online Judge/Map/Hardwood Species (10226)/STL_Map.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void calculateFraction(vector &collection) 5 | { 6 | map freq; 7 | for(auto str : collection) 8 | freq[str]++; 9 | 10 | int totalCount = 0; 11 | for(auto ele : freq) 12 | totalCount += ele.second; 13 | 14 | cout << std :: setprecision(4) << std :: fixed; 15 | for(auto ele : freq) 16 | { 17 | // Promotion 18 | double fraction = (100.0 * ele.second) /totalCount; 19 | 20 | cout << ele.first << " "; 21 | cout << fraction << endl; 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | int testCases; 28 | cin >> testCases; 29 | 30 | cin.ignore(2); 31 | for(int i = 0; i < testCases; i++) 32 | { 33 | string str; 34 | vector collection; 35 | 36 | while(getline(cin, str) and str.length () != 0) 37 | collection.push_back(str); 38 | 39 | if(i != 0) 40 | cout << endl; 41 | 42 | calculateFraction(collection); 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#83 Removes Duplicates from List (Retain Single Copy)/Iterative Approach.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | ListNode* deleteDuplicates(ListNode* head); 6 | }; 7 | 8 | /* Removes duplicates (while storing a single copy) */ 9 | ListNode* Solution :: deleteDuplicates(ListNode* head) 10 | { 11 | // Make a backup to return it later 12 | ListNode* backupHead = head; 13 | 14 | // Traverse to the first distinct element 15 | while(head) 16 | { 17 | // Start from the next node 18 | ListNode* nextDistinct = head->next; 19 | 20 | // Keep going forward if you see repeated values 21 | while(nextDistinct and nextDistinct->val == head->val) 22 | nextDistinct = nextDistinct->next; 23 | 24 | // Connect it so that all dupliactes vanish 25 | head->next = nextDistinct; 26 | 27 | // Move to the next node 28 | head = head->next; 29 | } 30 | 31 | // Return the original Head 32 | return backupHead; 33 | } 34 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/ReadMe.md: -------------------------------------------------------------------------------- 1 | This is the first time I solved all the 4 questions in a contest 2 | 3 | **Rank** -- 353/3583 4 | 5 | **Submission Time** 6 | Q1) 10 Minutes 7 | Q2) 18 Minutes 8 | Q3) 42 Minutes 9 | Q4) 1 hour 6 minutes 10 | 11 | **Penalty** 12 | 1 Penalty on question 3 as I didn't even see the output of the sample cases. 13 | 14 | **Review** 15 | All the questions were amazing (especially the last one) 16 | 17 | 18 | Upon further analysis, I didn't realize that in the second question, the 2 trees were BST. I solved it assuming normal trees (by converting to hash map). Although the complexity remains linear, it's not such a good solution. 19 | 20 | Similarly for the first question, I kept doing some mistake in the implementation and ended up using maps. The intended solution was O(n). I didn't really use the fact that the arrays were sorted. This was also not upto the spirit of the question. 21 | 22 | But, to compensate, I did do the remaining 2 solutions in an elegant manner. 23 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#543 Diameter of Binary Tree/Post Order Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int diameter = 0; 4 | public: 5 | int diameterOfBinaryTree(TreeNode* root); 6 | int height(TreeNode* root); 7 | }; 8 | 9 | /* Returns the height of the tree */ 10 | int Solution :: height(TreeNode* root) 11 | { 12 | // If the tree is empty, diameter is 0 13 | if(!root) return 0; 14 | 15 | // Recursively calculate the height of left and right subtree 16 | int leftHeight = height(root->left); 17 | int rightHeight = height(root->right); 18 | 19 | // Update the longest path 20 | diameter = max(diameter, leftHeight + rightHeight); 21 | 22 | // Return the height of the tree 23 | return max(leftHeight,rightHeight) + 1; 24 | } 25 | 26 | /* Returns the diameter of the binary tree */ 27 | int Solution :: diameterOfBinaryTree(TreeNode* root) 28 | { 29 | // Calculate the height and update the diameter 30 | height(root); 31 | 32 | // Return the updated diameter 33 | return diameter; 34 | } 35 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#206 Reverse a Linked List/Iterative Reverse.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* reverseList(ListNode* head); 5 | }; 6 | 7 | /* Reverses the linked list iteratively */ 8 | ListNode* Solution :: reverseList(ListNode* head) 9 | { 10 | // Pointers to keep track of 3 consecutive nodes 11 | ListNode* previous = nullptr; 12 | ListNode* current = head; 13 | ListNode* temp; 14 | 15 | // Traverse the list and keep reversing the elements as you encounter them 16 | while(current) 17 | { 18 | // Store the location of the next element 19 | temp = current->next; 20 | 21 | // Link the current element to the previous one 22 | current->next = previous; 23 | 24 | // Update the previous to current 25 | previous = current; 26 | 27 | // Update current to the original next element 28 | current = temp; 29 | } 30 | 31 | // Remember to return previous as current would be null 32 | return previous; 33 | } 34 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#24 Pairwise swap in a Linked List/JavaScript Implementation.js: -------------------------------------------------------------------------------- 1 | /* Converting it into an iterative version is easy.*/ 2 | /* Enclose the swapping procedure in a while loop */ 3 | 4 | /* Swaps the nodes pairwise */ 5 | var swapPairs = function(head) 6 | { 7 | // If less than 2 elements exist, No need to do anything 8 | if(!head || !(head.next)) return head; 9 | 10 | // Swap 2 nodes manually and let recursion do the rest 11 | var firstNode = head; 12 | var secondNode = head.next; 13 | 14 | // Connect first node to third node 15 | firstNode.next = secondNode.next; 16 | 17 | // Connect second node to the first node 18 | secondNode.next = firstNode; 19 | 20 | // Update head 21 | head = secondNode; 22 | 23 | // Recursively swap the remainging nodes. 24 | // There are atleast 2 nodes, hence no null pointer exception happen 25 | head.next.next = swapPairs(head.next.next); 26 | 27 | // Return the updated head to be overwritten 28 | return head; 29 | } 30 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1216 Valid Palindrome/LCS Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValidPalindrome(string str, int k); 5 | }; 6 | 7 | int compute_lcs(string str1, string str2) 8 | { 9 | int m = str1.length(); 10 | int n = str2.length(); 11 | 12 | int row = m + 1; 13 | int col = n + 1; 14 | 15 | vector> lcs(row, vector(col,0)); 16 | 17 | for(int i = 1; i < row; i++) 18 | { 19 | for(int j = 1; j < col; j++) 20 | { 21 | if(str1[i-1] == str2[j-1]) 22 | lcs[i][j] = 1 + lcs[i-1][j-1]; 23 | else 24 | lcs[i][j] = max({lcs[i-1][j], lcs[i][j-1], lcs[i-1][j-1]}); 25 | } 26 | } 27 | 28 | return lcs[m][n]; 29 | } 30 | 31 | 32 | bool Solution :: isValidPalindrome(string str1, int k) 33 | { 34 | string str2 = str1; 35 | reverse(str2.begin(), str2.end()); 36 | 37 | int remain = str1.length() - compute_lcs(str1, str2); 38 | 39 | return remain <= k; 40 | } 41 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#152 Maximum Product Subarray/Min_Max Approach (Fails).cpp: -------------------------------------------------------------------------------- 1 | /* This solution assumes that atleast 1 posiitve element is present */ 2 | /* Fails on LeetCode */ 3 | class Solution 4 | { 5 | public: 6 | int maxProduct(vector& a); 7 | }; 8 | 9 | int Solution :: maxProduct(vector& a) 10 | { 11 | int max_ending_here = 1; 12 | int min_ending_here = 1; 13 | 14 | int max_so_far = INT_MIN; 15 | 16 | for(int i=0; i0) 19 | { 20 | max_ending_here *= a[i]; 21 | min_ending_here = min(min_ending_here*a[i], 1); 22 | } 23 | 24 | if(a[i]==0) 25 | { 26 | max_ending_here = 1; 27 | min_ending_here = 1; 28 | } 29 | 30 | if(a[i]<0) 31 | { 32 | int temp = max_ending_here; 33 | max_ending_here = max(min_ending_here*a[i], 1); 34 | min_ending_here = temp*a[i]; 35 | } 36 | 37 | max_so_far = max(max_so_far, max_ending_here); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#24 Pairwise swap in a Linked List/Explanation and Link.md: -------------------------------------------------------------------------------- 1 | **Link** 2 | [Recursion](https://leetcode.com/problems/swap-nodes-in-pairs/discuss/259625/Detailed-Explanation-with-Pictures-C%2B%2BJavaScript) 3 | 4 | [An iterative solution using sentinels](https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11046/My-simple-JAVA-solution-for-share) 5 | 6 | **Intuition** 7 | * The idea is simple. Just swap 2 nodes manually and let recursion do the rest. 8 | 9 | **Algorithm** 10 | 1) Extract the first and the second node of the list. 11 | ![image](https://assets.leetcode.com/users/just__a__visitor/image_1553184089.png) 12 | 2) Connect the first node to the third node 13 | ![image](https://assets.leetcode.com/users/just__a__visitor/image_1553184135.png) 14 | 3) Connect the second node to the first node 15 | ![image](https://assets.leetcode.com/users/just__a__visitor/image_1553184175.png) 16 | 4) Update the head and update the third node (via the recursion blackbox) 17 | ![image](https://assets.leetcode.com/users/just__a__visitor/image_1553184228.png) 18 | 19 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/#1218 Longest AP Sequence/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Let us define `dp[i]` as the longest arithmetic subsequence which starts at `i`. 3 | 4 | If the subsequence starts at `i`, then it means that to fill the `i-th` entry we do not need to look on the left. Hence, this gives us a hint that we should start filling the `dp` matrix from the right. 5 | 6 | Suppose, at any stage we are at the `i-th` element. By definition, this is the first term of our subsequence. Hence, we need to find whether the second term `a[i] + diff` exists in the right half or not. This suggests us to keep a hash map to store the running `dp` values. If it exists, we also need to find what is the maximum dp value associated with it. 7 | 8 | So, after checking the maximum dp value from hashmap, we can update the maximum dp value in the hashmap. Hence, `dp[i] = 1 + max_dp_value[next_term]` , where `next_term = a[i] + diff`. 9 | 10 | 11 | # Blog 12 | [Link](https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/398201/Detailed-Explanation-using-DP-O(n)) 13 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#206 Reverse a Linked List/Recursive Reverse JavaScript.js: -------------------------------------------------------------------------------- 1 | /* Reverses the linked list recursively */ 2 | var reverseList = function(head) 3 | { 4 | // If the list is empty or has one element, nothing to reverse 5 | if(!head || !(head.next)) return head; 6 | 7 | /* Dealing the one element case as base case is necessary */ 8 | 9 | // Reverse the list except the first element 10 | reversedHead = reverseList(head.next); 11 | 12 | /* Observe that reversedHead would be the last element in the original list */ 13 | /* The tricky part is that you still have access to the last element in the reversed list */ 14 | /* This makes it O(n) instead of O(n^2) */ 15 | 16 | newLastElement = head.next; 17 | 18 | // If the last element exists, connect it to the first element 19 | if(newLastElement) newLastElement.next = head; 20 | 21 | // Block the unnecessary access of the previous head 22 | head.next = null; 23 | 24 | // Remember to return the new head 25 | return reversedHead; 26 | }; 27 | -------------------------------------------------------------------------------- /UVa Online Judge/Binary Search/Where is the Marble (10474)/Lower Bound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void solve(vector &vec, vector &queries) 5 | { 6 | sort(vec.begin(), vec.end()); 7 | 8 | for(int query : queries) 9 | { 10 | auto itr = lower_bound(vec.begin(), vec.end(), query); 11 | 12 | int index = itr - vec.begin(); 13 | 14 | // ++index to accomodate 1 based indexing 15 | if(index < vec.size() and vec[index] == query) 16 | cout << query << " found at " << ++index << endl; 17 | else 18 | cout << query << " not found" << endl; 19 | } 20 | } 21 | 22 | void scanVector(vector &vec) 23 | { 24 | for(auto &ele : vec) 25 | cin >> ele; 26 | } 27 | 28 | int main() 29 | { 30 | int n, q; 31 | cin >> n >> q; 32 | 33 | int tc_number = 1; 34 | 35 | while(n > 0 and q > 0) 36 | { 37 | vector vec(n), queries(q); 38 | 39 | scanVector(vec); 40 | scanVector(queries); 41 | 42 | cout << "CASE# " << tc_number++ << ":" << endl; 43 | solve(vec, queries); 44 | 45 | cin >> n >> q; 46 | } 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1254 Number of Closed Islands/Optimized DFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int row, col; 5 | bool terminal = false; 6 | void dfs(vector> &grid, int row, int col); 7 | int closedIsland(vector>& grid); 8 | }; 9 | 10 | void Solution :: dfs(vector> &grid, int i, int j) 11 | { 12 | if(i < 0 or j < 0 or i >= row or j >= col) 13 | { 14 | terminal = true; 15 | return; 16 | } 17 | 18 | if(grid[i][j] == 1) 19 | return; 20 | 21 | // Visit this cell 22 | grid[i][j] = 1; 23 | 24 | dfs(grid, i, j + 1); dfs(grid, i, j - 1); 25 | dfs(grid, i + 1, j); dfs(grid, i - 1, j); 26 | } 27 | 28 | int Solution :: closedIsland(vector>& grid) 29 | { 30 | row = grid.size(); 31 | col = grid[0].size(); 32 | 33 | int count = 0; 34 | for(int i = 0; i < row; i++) 35 | { 36 | for(int j = 0; j < col; j++) 37 | { 38 | if(grid[i][j] == 0) 39 | { 40 | terminal = false; 41 | dfs(grid, i, j); 42 | 43 | if(!terminal) 44 | count++; 45 | } 46 | } 47 | } 48 | 49 | return count; 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/ReadMe.md: -------------------------------------------------------------------------------- 1 | **LC#129 Contest Review** 2 | 3 | **Thoughts** 4 | 5 | * I've been under-performing for the past few contests. I need to be more focused during the contests (Last contest, I lost motivation just after half an hour). 6 | * **Is tomorrow's contest going to be the one where I solve all the questions during the contest duration**? Well, that's not in my control. However, I can ensure that I solve all the questions by myself latest by 11AM. 7 | 8 | --- 9 | **Schedule** 10 | * 8-9:30 -> Contest 11 | * 9:30-10 -> Breakfast 12 | * 10-11 -> Implement the unsolved questions 13 | * 11-12 -> Write blogs, read Top contestant's code, read **Discuss** articles. 14 | 15 | **Strategy** 16 | * I've decided to experiment a bit with my strategy during tomorrow's contest. In the first 5 minutes, I won't implement anything. Instead I'll devote the time to read each of the 4 questions. 17 | 18 | --- 19 | 20 | 21 | The contest was pre-poned by 1 hour and I was not aware of that. Eventually I didn't solve any of the question during contest duration. 22 | I upsolved all the questions afterwards. 23 | -------------------------------------------------------------------------------- /GeekForGeeks/Tower Of Hanoi/Recursive Approach.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | int moveCount = 0; 8 | int desiredCount = 0; 9 | void tower_of_hanoi(int n, int source, int aux, int target); 10 | }; 11 | 12 | void Solution :: tower_of_hanoi(int n, int source, int aux, int target) 13 | { 14 | if(n == 1) 15 | { 16 | moveCount ++; 17 | if(moveCount == desiredCount) 18 | cout << source << " " << target << endl; 19 | 20 | return; 21 | } 22 | 23 | tower_of_hanoi(n-1, source, target, aux); 24 | 25 | moveCount++; 26 | if(moveCount == desiredCount) 27 | cout << source << " " << target << endl; 28 | 29 | tower_of_hanoi(n-1, aux, source, target); 30 | } 31 | 32 | int main() 33 | { 34 | int t; 35 | cin >> t; 36 | 37 | for(int i = 0; i < t; i++) 38 | { 39 | Solution s; 40 | int n, desiredCount; 41 | cin >> n >> desiredCount; 42 | 43 | s.desiredCount = desiredCount; 44 | s.tower_of_hanoi(n, 1, 2, 3); 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1253 Reconstruct Binary Matrix/Greedy.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> reconstructMatrix(int upper, int lower, vector& colsum); 5 | }; 6 | 7 | vector> Solution :: reconstructMatrix(int upper, int lower, vector& colsum) 8 | { 9 | int n = colsum.size(); 10 | vector> mat(2, vector (n, 0)); 11 | 12 | for(int i = 0; i < n; i++) 13 | if(colsum[i] == 2) 14 | mat[0][i] = 1, mat[1][i] = 1; 15 | 16 | auto& first_row = mat[0]; 17 | int current_upper_sum = accumulate(first_row.begin(), first_row.end(), 0); 18 | 19 | int diff = upper - current_upper_sum; 20 | 21 | if(diff < 0) 22 | return vector>(); 23 | 24 | for(int i = 0; i < n; i++) 25 | { 26 | if(colsum[i] == 1) 27 | { 28 | if(diff > 0) 29 | mat[0][i] = 1, diff--; 30 | else 31 | mat[1][i] = 1; 32 | } 33 | } 34 | 35 | auto& second_row = mat[1]; 36 | int current_lower_sum = accumulate(second_row.begin(), second_row.end(), 0); 37 | 38 | if(current_lower_sum != lower) 39 | return vector> (); 40 | 41 | return mat; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #130/#1020 Number of Enclaves/Number of Enclaves.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int ROW, COL; 4 | public: 5 | int numEnclaves(vector>& a); 6 | void dfs(vector>& a, int i, int j); 7 | }; 8 | 9 | void Solution :: dfs(vector>& a, int i, int j) 10 | { 11 | if(i<0 || i>=ROW || j<0 || j>=COL) return; 12 | if(a[i][j]==0 || a[i][j]==-1) return; 13 | 14 | a[i][j] = -1; 15 | 16 | dfs(a,i-1,j); dfs(a,i+1,j); 17 | dfs(a,i,j-1); dfs(a,i,j+1); 18 | } 19 | 20 | int Solution :: numEnclaves(vector>& a) 21 | { 22 | ROW = a.size(); 23 | COL = a[0].size(); 24 | 25 | vector rowBorders = {0,ROW-1}; 26 | vector colBorders = {0,COL-1}; 27 | 28 | for(int i : rowBorders) 29 | for(int j=0; jval == key) 14 | return true; 15 | 16 | if(root->val > key) 17 | return binary_search(root->left, key); 18 | else 19 | return binary_search(root->right, key); 20 | } 21 | 22 | 23 | bool Solution :: twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) 24 | { 25 | if(!root1 || !root2) 26 | return false; 27 | 28 | if(root1->val == target) 29 | return true; 30 | 31 | // Check if this is the answer 32 | if(binary_search(root2, target - root1->val)) 33 | return true; 34 | 35 | // Check in the left subtree 36 | if(twoSumBSTs(root1->left, root2, target)) 37 | return true; 38 | 39 | // Check in the right subtree 40 | if(twoSumBSTs(root1->right, root2, target)) 41 | return true; 42 | 43 | return false; 44 | } 45 | -------------------------------------------------------------------------------- /Templates/Prime Factorization/Prime Factorization Template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Function to obtain all prime factors of a number, along with its multiplicity */ 5 | /* Time Complexity is O( sqrt(n) ) */ 6 | vector> primeFactorization(long num) 7 | { 8 | vector> res; 9 | 10 | for(int factor = 2; factor*factor <= num; factor++) 11 | { 12 | int multiplicity = 0; 13 | 14 | while(num % factor == 0) 15 | { 16 | num /= factor; 17 | multiplicity++; 18 | } 19 | 20 | if(multiplicity != 0) 21 | res.push_back(make_pair(factor, multiplicity)); 22 | } 23 | 24 | if(num != 1) 25 | res.push_back(make_pair(num , 1)); 26 | 27 | return res; 28 | } 29 | 30 | void testPrimeFactorization() 31 | { 32 | for(int num = 2; num <= 50; num++) 33 | { 34 | vector> factors; 35 | factors = primeFactorization(num); 36 | 37 | cout << "The prime factors of " << num << " are "; 38 | 39 | for(auto ele : factors) 40 | cout << ele.first << " "; 41 | 42 | cout << endl; 43 | } 44 | } 45 | 46 | int main() 47 | { 48 | testPrimeFactorization(); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1254 Number of Closed Islands/Modified DFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int row, col; 5 | bool terminal = false; 6 | void dfs(vector> &grid, int row, int col); 7 | int closedIsland(vector>& grid); 8 | }; 9 | 10 | void Solution :: dfs(vector> &grid, int i, int j) 11 | { 12 | if(i < 0 or j < 0 or i >= row or j >= col) 13 | return; 14 | 15 | if(grid[i][j] == 1 or grid[i][j] == 2) 16 | return; 17 | 18 | if(i == 0 or j == 0 or i == row - 1 or j == col -1) 19 | terminal = true; 20 | 21 | // Visit this cell 22 | grid[i][j] = 2; 23 | 24 | dfs(grid, i, j + 1); dfs(grid, i, j - 1); 25 | dfs(grid, i + 1, j); dfs(grid, i - 1, j); 26 | } 27 | 28 | int Solution :: closedIsland(vector>& grid) 29 | { 30 | row = grid.size(); 31 | col = grid[0].size(); 32 | 33 | int count = 0; 34 | for(int i = 0; i < row; i++) 35 | { 36 | for(int j = 0; j < col; j++) 37 | { 38 | if(grid[i][j] == 0) 39 | { 40 | terminal = false; 41 | dfs(grid, i, j); 42 | 43 | if(!terminal) 44 | count++; 45 | } 46 | } 47 | } 48 | 49 | return count; 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#344 Reverse string Inplace/2 Pointer Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void reverseString(vector& str); 5 | }; 6 | 7 | void Solution :: reverseString(vector& str) 8 | { 9 | int len = str.size(); 10 | 11 | // If the string is of length less than two, it is already in place 12 | if(len<2) return; 13 | 14 | // Use the two pointer approach. Start Swapping element from the front and back 15 | int left = 0; 16 | int right = len-1; 17 | 18 | // Temporary buffer to store the element to be swapped 19 | char buffer; 20 | 21 | // While left does not cross rght, keep swapping 22 | while(left> dp(n + 1); 15 | for(auto &row_vec : dp) 16 | row_vec.resize(n + 1); 17 | 18 | int row = n+1; 19 | int col = n+1; 20 | 21 | for(int i = 0; i < n; i++) 22 | dp[i][0] = i; 23 | 24 | for(int j = 0; j < n; j++) 25 | dp[0][j] = j; 26 | 27 | for(int i = 1; i < row; i++) 28 | { 29 | for(int j = 1; j < col; j++) 30 | { 31 | if((str1[i-1] == str2[j-1])) 32 | { 33 | dp[i][j] = dp[i-1][j-1]; 34 | } 35 | else 36 | { 37 | dp[i][j] = 1 + min(dp[i-1][j],dp[i][j-1]); 38 | } 39 | } 40 | } 41 | 42 | int min_steps = dp[n][n]; 43 | /* Why 2 * k ? */ 44 | return min_steps <= 2*k; 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1005 Maximize Sum Of Array After K Negations/Maximize sum after K negations.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int largestSumAfterKNegations(vector& a, int k); 5 | }; 6 | 7 | /* Returns the maximum sum possible after k negations */ 8 | int Solution :: largestSumAfterKNegations(vector& a, int k) 9 | { 10 | // Calculate the initial sum of the array 11 | int sum = accumulate(a.begin(), a.end(), 0); 12 | 13 | // Create a min heap 14 | priority_queue, greater> minHeap; 15 | 16 | // Push all the elements onto the min heap 17 | for(auto element : a) 18 | minHeap.push(element); 19 | 20 | // Repeat the operation k times 21 | for(int i=0; i& a); 5 | }; 6 | 7 | /* collection[i] is the set of all distinct bitwise 'or' 8 | * of all the subarrays ending at i. 9 | * Clearly, collection[i] = a[i] union (a[i] | collection[i-1]) 10 | */ 11 | 12 | /* We can also reduce the space complexity using 'curr' & 'prev' set */ 13 | 14 | /* Don't mix up '|' and 'or'*/ 15 | int Solution :: subarrayBitwiseORs(vector& a) 16 | { 17 | // Too strict time limit. Use Hashing 18 | vector> collection(a.size()); 19 | int n = a.size(); 20 | 21 | // Initially, each collection contains one element 22 | for(int i = 0; i < n; i++) 23 | collection[i].insert(a[i]); 24 | 25 | // Simple DP. Size of each collection[i] < 32 26 | for(int i = 1; i < n; i++) 27 | for(auto ele : collection[i-1]) 28 | collection[i].insert(a[i] | ele); 29 | 30 | unordered_set final_collection; 31 | 32 | // Use reference whenever possible 33 | for(auto& set : collection) 34 | for(auto ele : set) 35 | final_collection.insert(ele); 36 | 37 | return final_collection.size(); 38 | } 39 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#24 Pairwise swap in a Linked List/Recursive Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* swapPairs(ListNode* head); 5 | }; 6 | 7 | /* Converting it into an iterative version is easy.*/ 8 | /* Enclose the swapping procedure in a while loop */ 9 | 10 | /* Swaps the nodes pairwise */ 11 | ListNode* Solution :: swapPairs(ListNode* head) 12 | { 13 | // If less than 2 elements exist, No need to do anything 14 | if(!head || !(head->next)) return head; 15 | 16 | // Swap 2 nodes manually and let recursion do the rest 17 | ListNode* firstNode = head; 18 | ListNode* secondNode = head->next; 19 | 20 | // Connect first node to third node 21 | firstNode->next = secondNode->next; 22 | 23 | // Connect second node to the first node 24 | secondNode->next = firstNode; 25 | 26 | // Update head 27 | head = secondNode; 28 | 29 | // Recursively swap the remainging nodes. 30 | // There are atleast 2 nodes, hence no null pointer exception happen 31 | head->next->next = swapPairs(head->next->next); 32 | 33 | // Return the updated head to be overwritten 34 | return head; 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #130/#1019 Next Greater Element/Stack Based Approach.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | vector nextLargerNodes(ListNode* head); 6 | }; 7 | 8 | /* Returns the next greater element in the linked list */ 9 | vector Solution :: nextLargerNodes(ListNode* head) 10 | { 11 | // Create a vector and copy the list 12 | vector a; 13 | while(head) 14 | { 15 | a.push_back(head->val); 16 | head = head->next; 17 | } 18 | 19 | // Create the vector to store the answer; 20 | int n = a.size(); 21 | vector answer(n); 22 | 23 | // Create the monotonic stack 24 | stack myStack; 25 | for(int i=n-1; i>=0; i--) 26 | { 27 | // Pop all smaller/equal elements from the stack 28 | while(!myStack.empty() && a[i]>=myStack.top()) 29 | myStack.pop(); 30 | 31 | // The remaining element is the next greater element 32 | answer[i] = myStack.empty()? 0 : myStack.top(); 33 | 34 | // Push this element onto the stack 35 | myStack.push(a[i]); 36 | } 37 | 38 | // Return the answer 39 | return answer; 40 | } 41 | -------------------------------------------------------------------------------- /Templates/Scan and Print a Vector/Scanning And Printing a Vector (Debugging).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* To use the template just copy the 2 functions and use it */ 6 | 7 | /* Prints the contents of a vector containing any data type in the cout stream*/ 8 | template 9 | void printVector(vector &myVector) 10 | { 11 | cout << endl << "Printing the contents of the vector" << endl; 12 | 13 | for(auto ele : myVector) 14 | cout << ele << " "; 15 | 16 | cout << endl << "The vector has been printed" << endl; 17 | } 18 | 19 | /* Scans the contents of a vector of any data type*/ 20 | /* Assumes that the vector has been resized */ 21 | template 22 | void scanVector(vector &myVector) 23 | { 24 | for(auto &ele : myVector) 25 | cin >> ele; 26 | } 27 | 28 | 29 | int main() 30 | { 31 | vector myVec; 32 | 33 | int size; 34 | cin >> size; 35 | 36 | myVec.resize(size); 37 | 38 | scanVector(myVec); 39 | printVector(myVec); 40 | return 0; 41 | } 42 | 43 | 44 | /* Test Case 45 | 5 46 | 1 2 3 4 5 47 | */ 48 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#127 Word Ladder/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Review 2 | * An excellent question to refresh the basics of **BFS** and **STL** containers. 3 | * **Time Taken** : 15 minutes (including brain storming and coding) 4 | * **Penalty** : None 5 | * **What's New?** 6 | * Found a clean way for searching in an unordered_map/set. 7 | * Adopted a new way to populate STL Containers with the help of existing containers. 8 | * A Novel approach to change a single charcter of a string using range based for loops. 9 | 10 | # Approach 11 | * Store all the dictionary words in a hashmap called `dictionary` to facilitate quick searching. 12 | * Make another hashmap `visited` which contains all the string which are visited. 13 | * The queue would store the string and its level. (i,e a pair). 14 | * Whenever you pop a string during bfs, iterate over each of the characters and try to replace them with all the alphabets (while keeping the remaining letters same. If the new string is present in the dictionary and is not visited, visit it. 15 | 16 | # To Do 17 | * Perform BFS with marker to avoid pushing a pair into the queue. 18 | * Apply an alternate technique of modifying the dictionary instead of a `visited` hashmap. 19 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#206 Reverse a Linked List/Recursive Reverse.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* reverseList(ListNode* head); 5 | }; 6 | 7 | /* Reverses the linked list recursively */ 8 | ListNode* Solution :: reverseList(ListNode* head) 9 | { 10 | // If the list is empty or has one element, nothing to reverse 11 | if(!head || !(head->next)) return head; 12 | 13 | /* Dealing the one element case as base case is necessary */ 14 | 15 | // Reverse the list except the first element 16 | ListNode* reversedHead = reverseList(head->next); 17 | 18 | /* Observe that reversedHead would be the last element in the original list */ 19 | /* The tricky part is that you still have access to the last element in the reversed list */ 20 | /* This makes it O(n) instead of O(n^2) */ 21 | 22 | ListNode* newLastElement = head->next; 23 | 24 | // If the last element exists, connect it to the first element 25 | if(newLastElement) newLastElement->next = head; 26 | 27 | // Block the unnecessary access of the previous head 28 | head->next = nullptr; 29 | 30 | // Remember to return the new head 31 | return reversedHead; 32 | } 33 | -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 581/D) Kirk and a Binary String/Remove Valid Parenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void solve(string str) 5 | { 6 | // String to store the final answer 7 | string result = str; 8 | 9 | // This is an indicial stack 10 | stack myStack; 11 | 12 | // Remove all valid brackets 13 | for(int i = 0; i < str.length(); i++) 14 | { 15 | // Opening bracket, Push it onto stack 16 | if(str[i] == '1') 17 | { 18 | myStack.push(i); 19 | } 20 | 21 | // Closing bracket 22 | else 23 | { 24 | // Pop a matching pair if exists 25 | if(!myStack.empty()) 26 | myStack.pop(); 27 | } 28 | } 29 | 30 | // The remaining brakcets haven't been paired 31 | // We can convert all opening to closing now 32 | while(!myStack.empty()) 33 | { 34 | result[myStack.top()] = '0'; 35 | myStack.pop(); 36 | } 37 | 38 | // Print the result 39 | cout << result << endl; 40 | } 41 | 42 | int main() 43 | { 44 | string str; 45 | cin >> str; 46 | 47 | solve(str); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #157/#1220 Count Vowel Permutation/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | Let us visualize this as a graph problem. From the above rules, we can create a directed graph where an edge between characters `first` and `second` imply that it is permissible to write `second` immediately after first. Hence, the question converts to, **Given a directed graph, how many paths of length `n` are there?** 3 | 4 | ![image](https://assets.leetcode.com/users/just__a__visitor/image_1570334589.png) 5 | 6 | Now, Let us say that `dp[n][char]` denotes the number of directed paths of length `n` which end at a particular vertex `char`. Then, we know that the last vertex in our path was `char`. However, let's focus on the last second vertex. It could have been any of the vertex which has a direct edge to `char`. Hence, if we can find the number of paths of length `n-1` ending at these vertices, then we can append `char` at the end of every path and we would have exhausted all possibilites. 7 | 8 | Hence, `dp[n+1][x] = sum of all dp[n][y]` such that there is a directed edge from `y` to `x`. 9 | 10 | # Blog 11 | [Link](https://leetcode.com/problems/count-vowels-permutation/discuss/398222/Detailed-Explanation-using-Graphs-With-Pictures-O(n)) 12 | 13 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#312 Burst Balloons/Recursive Memo.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | vector< vector > memo; 4 | 5 | public: 6 | int collect(vector &a, int low, int high); 7 | int maxCoins(vector &a); 8 | }; 9 | 10 | /* Max Coins that you can collect in the range (low, high) (Both exclusive) */ 11 | int Solution :: collect(vector &a, int low, int high) 12 | { 13 | int len = high - low + 1; 14 | 15 | if(len <= 2) 16 | return 0; 17 | 18 | if(memo[low][high] != -1) 19 | return memo[low][high]; 20 | 21 | int max_profit = 0; 22 | for(int k = low + 1; k < high; k++) 23 | { 24 | int collect_left = collect(a, low, k); 25 | int collect_right = collect(a, k, high); 26 | int collect_now = a[low]*a[k]*a[high]; 27 | 28 | int profit_now = collect_left + collect_right + collect_now; 29 | 30 | max_profit = max(max_profit, profit_now); 31 | } 32 | 33 | memo[low][high] = max_profit; 34 | return max_profit; 35 | } 36 | 37 | int Solution :: maxCoins(vector &a) 38 | { 39 | int sentinel = 1; 40 | 41 | // Create 2 boundaries 42 | a.push_back(sentinel); 43 | a.insert(a.begin(), sentinel); 44 | 45 | int n = a.size(); 46 | memo.resize(n, vector (n, -1)); 47 | 48 | return collect(a, 0, n - 1); 49 | } 50 | 51 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #9/#1197 Minimum Knight Moves/Simple BFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minKnightMoves(int tx, int ty); 5 | }; 6 | 7 | int Solution :: minKnightMoves(int tx, int ty) 8 | { 9 | tx = abs(tx), ty = abs(ty); 10 | int n = 400; 11 | vector> mat(n, vector(n,-1)); 12 | 13 | int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; 14 | int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1}; 15 | 16 | int row = 0, col = 0, x, y; 17 | 18 | queue> q; 19 | 20 | mat[row][col] = 0; 21 | q.push(make_pair(row,col)); 22 | 23 | while(!q.empty()) 24 | { 25 | if(mat[tx][ty] != -1) 26 | return mat[tx][ty]; 27 | 28 | row = q.front().first; 29 | col = q.front().second; 30 | q.pop(); 31 | 32 | for(int i = 0; i < 8; i++) 33 | { 34 | int x = row + dx[i]; 35 | int y = col + dy[i]; 36 | 37 | if(x >= 0 and y >= 0 and x < n and y < n and mat[x][y] == -1) 38 | { 39 | mat[x][y] = 1 + mat[row][col]; 40 | q.push(make_pair(x,y)); 41 | } 42 | } 43 | } 44 | 45 | 46 | return mat[tx][ty]; 47 | } 48 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#134 Circular Tour of Petrol Pumps/Queue [O(n) Space].cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int canCompleteCircuit(vector& gas, vector& cost); 5 | }; 6 | 7 | int Solution :: canCompleteCircuit(vector& gas, vector& cost) 8 | { 9 | int n = gas.size(); 10 | queue myQueue; 11 | 12 | int current = 0, fuel = 0, firstSeen = 0; 13 | 14 | while(true) 15 | { 16 | // This indicates that the last decision was incorrect 17 | if(fuel<0) 18 | { 19 | // Clear everything for fresh iterations 20 | fuel = 0; 21 | while(!myQueue.empty()) 22 | myQueue.pop(); 23 | } 24 | 25 | // Record how many time you encounter the first pump 26 | if(current==0) firstSeen++; 27 | 28 | // This is the third pass. Terminate! 29 | if(firstSeen>2) return -1; 30 | 31 | // Tour completed 32 | if(myQueue.size()==n) 33 | return myQueue.front(); 34 | 35 | // Enqueue the pump blindly 36 | fuel += gas[current]; 37 | fuel -= cost[current]; 38 | myQueue.push(current); 39 | 40 | // Go to the next pump 41 | current = (current + 1)%n; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /E-Olymp Online Judge/DP on Trees/House Robber (Tree) (973)/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Review 2 | * Clearly the **Hello World** of DP on Trees. Make sure to understand **House Robber on a 1D array** first. 3 | * Initially, I forgot the `parent` parameter which led to **TLE** (Infinite Loop). 4 | * The second one was a serious bug and I was able to debug it only because the sample cases where nice and tricky. When we decide to leave the `i-th` vertex, we shouldn't necessarily take all the `children`. (Why?). Because it might devoid us of taking the grand children. However, we do want to take the profit from the subtree of all the children. Hence, I declared a new array `dp_subtree` which gives the maximum coins that can be robbed from the `i-th` subtree (regardless of whether we take it or not). 5 | * Naturallly, `dp_subtree[i] = max(dp_include[i], dp_exclude[i])`. So, when we decide to leave the `i-th` vertex, we can just accumulate the profit of all the subtrees rooted at the children via this array. 6 | * Of course, we could have done this without creating an array. However, I wanted to keep things self-explanatory for the first time. 7 | * Looking on the bright side, I did clear all the test cases on the first submission. 8 | 9 | 10 | ### Credits 11 | * [Codeforces Blog](https://codeforces.com/blog/entry/20935) 12 | -------------------------------------------------------------------------------- /Templates/Comparators/The Best.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Note : Be very careful with comparators if you are going to use equality method 5 | * If there are 2 small arguments, you can just skip 'auto' and compare directly 6 | * The comparator can never look like lhs <= rhs. Why is that? Think Carefully. 7 | */ 8 | 9 | /* It also includes the default constructor to create fixed size arrays 10 | * You can skip the default constructor if you are aren't creating fixed size vector 11 | * Instead, use `push_back` 12 | */ 13 | 14 | class Edge 15 | { 16 | public: 17 | int u, v, weight; 18 | 19 | public: 20 | 21 | Edge() : u(), v(), weight() {}; 22 | 23 | Edge(int u, int v, int weight) 24 | { 25 | this->u = u, this->v = v; 26 | this->weight = weight; 27 | } 28 | 29 | bool operator < (const Edge& big) const 30 | { 31 | auto lhs = tie(weight, u, v); 32 | auto rhs = tie(big.weight, big.u, big.v); 33 | 34 | return lhs < rhs; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | int n; 41 | cin >> n; 42 | 43 | vector vec(n); 44 | 45 | for(auto &ele : vec) 46 | cin >> ele.u >> ele.v >> ele.weight; 47 | 48 | for(auto &ele : vec) 49 | cout << ele.u << " " << ele.v << " " << ele.weight << "\n"; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Codeforces Contests/CF Round 582/ReadMe.md: -------------------------------------------------------------------------------- 1 | ### Strategy Before the Contest 2 | I have decided to experiment a little. I would start the contest from the 4th question onwards. 3 | * 45 minutes for the 4th problem 4 | * 45 minutes for the 5th problem. 5 | * If I do both (or just 5th) before the alloted time, I would move onto the 6th question. 6 | * If not, I will start solving the first 3 questions in the last 30 minutes. 7 | 8 | This is a divison 3 round. The last 3 questons would be easily solvable. I have to struggle till the last minute. 9 | 10 | ## Aftermath 11 | This contest was a disaster. The questions were mostlly observation based and implementation heavy (unless you know the correct shorter way). I solved the first question in the last 10 minutes (which was perfectly valid) and later submitted another solution handling the case when `n == 1`. Sadlly the first solution was correct, the second was not. Silly me! 12 | 13 | The only question worth upsolving is the last question (which uses **DSU**). 14 | 15 | 16 | **I am not giving Divison 3 Contests again**. 17 | 18 | 19 | # To Do 20 | * - [ ] Learn **Union Find** and imlement the last question. 21 | 22 | 23 | # Rating 24 | ![Rating](https://github.com/Just-A-Visitor/Coding/blob/master/Codeforces%20Contests/CF%20Round%20582/Rating.PNG) 25 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#61 Cyclic Right Shift for Linked Lists/Circle Formation.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* rotateRight(ListNode* head, int k); 5 | }; 6 | 7 | /* Rotates a linked list to the right by k places */ 8 | ListNode* Solution :: rotateRight(ListNode* head, int k) 9 | { 10 | // Handle the base case 11 | if(!head) return head; 12 | 13 | /* Find out the length along with the tail */ 14 | 15 | // Length has to be intialized as 1 instead of 0 16 | int length = 1; 17 | 18 | // Traverse the list and find the tail 19 | ListNode* tail = head; 20 | while(tail->next) 21 | { 22 | tail = tail->next; 23 | length++; 24 | } 25 | 26 | // Normalize the shift 27 | k = k%length; 28 | 29 | // Handle the corner case 30 | if(k==0) return head; 31 | 32 | // Form a circle 33 | tail->next = head; 34 | 35 | /* We are sure that the tail is not null and k>0*/ 36 | 37 | // Go to the new tail node 38 | for(int i=0; i<(length-k); i++) 39 | tail = tail->next; 40 | 41 | // Store the location of the new head 42 | ListNode* newHead = tail->next; 43 | 44 | // Cut the list here 45 | tail->next = nullptr; 46 | 47 | // Return the new head 48 | return newHead; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#151 Reverse a String Keeping The Words Intact/Reverse a String Keeping The Words Same.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | string reverseWords(string str); 9 | }; 10 | 11 | /* Reverses the string but keeps the words same */ 12 | string Solution :: reverseWords(string str) 13 | { 14 | // Create a new stringstream 15 | stringstream newStream(str); 16 | 17 | // Variables to store the results 18 | string finalAnswer, word; 19 | stack myStack; 20 | 21 | // As long as the stream contains words, extract it and push it onto the stack 22 | while(newStream >> word) 23 | myStack.push(word); 24 | 25 | // Clear the stack and the string would be reversed 26 | while(!myStack.empty()) 27 | { 28 | // Append the new word 29 | finalAnswer += myStack.top(); 30 | myStack.pop(); 31 | 32 | // If it is not the last iteration, append space 33 | if(!myStack.empty()) finalAnswer += " "; 34 | } 35 | 36 | // Return the reversed string 37 | return finalAnswer; 38 | } 39 | 40 | /* The question demands that extra spaces be removed, it takes care of that */ 41 | 42 | 43 | int main() 44 | { 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#84 Largest Rectangle Under the Skyline/Single Traversal and 1 Stack.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int largestRectangleArea(vector& a); 5 | }; 6 | 7 | /* Computes the largest rectangle under the Skyline */ 8 | int Solution :: largestRectangleArea(vector& a) 9 | { 10 | // Push the sentinel. It ensures that all elements are popped 11 | a.push_back(0); 12 | 13 | // Declare the stack to hold indices 14 | stack myStack; 15 | int maxArea = 0; 16 | 17 | // Push each element on the stack 18 | for(int i=0; i& gas, vector& cost); 5 | }; 6 | 7 | int Solution :: canCompleteCircuit(vector& gas, vector& cost) 8 | { 9 | int n = gas.size(); 10 | int size = 0, start = -1; 11 | 12 | int current = 0, fuel = 0, firstSeen = 0; 13 | 14 | while(true) 15 | { 16 | // This indicates that the last decision was incorrect 17 | if(fuel<0) 18 | { 19 | // Clear everything for fresh iterations 20 | fuel = 0; 21 | start = -1, size =0 ; 22 | } 23 | 24 | // Record how many time you encounter the first pump 25 | if(current==0) firstSeen++; 26 | 27 | // This is the third pass. Terminate! 28 | if(firstSeen>2) return -1; 29 | 30 | // Tour completed 31 | if(size==n) 32 | return start; 33 | 34 | // Enqueue the pump blindly 35 | fuel += gas[current]; 36 | fuel -= cost[current]; 37 | size++; 38 | 39 | // Update the first element if needed 40 | if(start==-1) 41 | start = current; 42 | 43 | // Go to the next pump 44 | current = (current + 1)%n; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /SPOJ Online Judge/Sets/Colorful Arrays (CLFLARR)/Reverse Query Processing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Query 5 | { 6 | public: 7 | int l, r, color; 8 | Query(int l, int r, int color) 9 | { 10 | this->l = l; 11 | this->r = r; 12 | this->color = color; 13 | } 14 | }; 15 | 16 | void colorful_arrays(int n, vector &queryVec) 17 | { 18 | // One based Indexing 19 | vector finalColor(n + 1); 20 | 21 | set uncolored; 22 | for(int i = 1; i <= n; i++) 23 | uncolored.insert(i); 24 | 25 | // Process the queries in reverse order 26 | reverse(queryVec.begin(), queryVec.end()); 27 | 28 | for(auto ele : queryVec) 29 | { 30 | auto itr = uncolored.lower_bound(ele.l); 31 | 32 | while(itr != uncolored.end() and *itr <= ele.r) 33 | { 34 | finalColor[*itr] = ele.color; 35 | itr = uncolored.erase(itr); 36 | } 37 | 38 | } 39 | 40 | for(int i = 1; i <= n; i++) 41 | cout << finalColor[i] << endl; 42 | 43 | } 44 | 45 | int main() 46 | { 47 | int n, queryLength; 48 | cin >> n >> queryLength; 49 | 50 | vector queryVec; 51 | 52 | for(int i = 0; i < queryLength; i++) 53 | { 54 | int l, r, color; 55 | cin >> l >> r >> color; 56 | queryVec.push_back(Query(l, r, color)); 57 | } 58 | 59 | colorful_arrays(n, queryVec); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /UVa Online Judge/Binary Search the Answer/Monkey and Oiled Bamboo (12032)/Simple Binary Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Assumes that the sentinel is appended at the front */ 5 | bool possible(vector &a, int max_jump_length) 6 | { 7 | int n = a.size(); 8 | 9 | for(int i = 1; i < n; i++) 10 | { 11 | if(max_jump_length <= 0) 12 | return false; 13 | 14 | int jump = a[i] - a[i-1]; 15 | 16 | if(jump > max_jump_length) 17 | return false; 18 | 19 | if(jump == max_jump_length) 20 | max_jump_length--; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | int solve(vector &a) 27 | { 28 | int low = 1; 29 | int high = 1e7; 30 | 31 | while(low < high) 32 | { 33 | int mid = (low + high)/2; 34 | 35 | if(possible(a, mid)) 36 | high = mid; 37 | else 38 | low = mid + 1; 39 | } 40 | 41 | assert(possible(a, low)); 42 | 43 | return low; 44 | } 45 | 46 | int main() 47 | { 48 | int test; 49 | cin >> test; 50 | 51 | for(int i = 1; i <= test; i++) 52 | { 53 | int n; 54 | cin >> n; 55 | 56 | vector a(n); 57 | for(auto &ele : a) 58 | cin >> ele; 59 | 60 | int sentinel = 0; 61 | 62 | // Technique to insert an element at the front 63 | a.insert(a.begin(), sentinel); 64 | 65 | cout << "Case " << i << ": " << solve(a) << endl; 66 | 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /GeekForGeeks/Binary Tree to DLL/Modified InOrder.cpp: -------------------------------------------------------------------------------- 1 | /* Driver function for modified inorder tree conversion */ 2 | void convert(Node* root, Node **prev_ref) 3 | { 4 | // Empty tree, Nothing to convert 5 | if(!root) return; 6 | 7 | // Recursively flatten the left subtree 8 | // Record the inorder predeccessor of root 9 | convert(root->left, prev_ref); 10 | 11 | // Connect the last seen node to root 12 | if((*prev_ref)) 13 | { 14 | (*prev_ref)->right = root; 15 | root->left = (*prev_ref); 16 | } 17 | 18 | /* The if condition is for checking that the head of the list is set */ 19 | 20 | // Update the last seen node 21 | *prev_ref = root; 22 | 23 | // Recursively flatten the right subtree 24 | convert(root->right, prev_ref); 25 | } 26 | 27 | 28 | 29 | /* Converts the binary tree to doubly linked list inplace*/ 30 | void BToDLL(Node *root, Node **head_ref) 31 | { 32 | // Previous records the last visited node 33 | Node* previous = nullptr; 34 | 35 | // Pass the address of previous to reflect changes 36 | convert(root, &previous); 37 | 38 | /* Previous points to the tail. Obtain the head */ 39 | while(previous && previous->left) 40 | previous = previous->left; 41 | 42 | // Update the head of the list 43 | (*head_ref) = previous; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #162/#1255 Maximum Score Words/ReadMe.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | * Since the number of words is quite less (14), we can just generate all the subsets. Let's call a subset valid if all the words in that subset can be formed by using the given letters. It is clear that we need to maximize the score of valid subsets. To do this, we generate all subsets, and check if it is valid. If it is, we find its score and update the global maxima. 3 | 4 | * To generate the subsets, we create a function call `generate_subset(words, n)` which generate all the subsets of the vector `words`. To quickly recap, we have 2 choices for the last element, either to take it or to leave it. We store this choice in an array called `taken` where `taken[i]` represent that the `i-th` element was taken in our journey. We then recurse for the remaining elements. 5 | 6 | * When `n` becomes zero, it means we cannot make any more choices. So now, we traverse our `taken` array to find out the elements in this subset. Then we count the frequency of each letter in this subset. If the frequency of each letter is under the provided limit, it means it is a valid subet. Hence, we find the score of this subset and update the maxima. 7 | 8 | 9 | # Blog 10 | [Link](https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/425104/Detailed-Explanation-using-Recursion) 11 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#134 Circular Tour of Petrol Pumps/Concatenation Approach [Clean].cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int canCompleteCircuit(vector& gas, vector& cost); 5 | }; 6 | 7 | int Solution :: canCompleteCircuit(vector& gas, vector& cost) 8 | { 9 | int original_size = gas.size(); 10 | for(int i = 0; i < original_size; i++) 11 | { 12 | gas.push_back(gas[i]); 13 | cost.push_back(cost[i]); 14 | } 15 | 16 | int new_size = original_size + original_size; 17 | 18 | queue myQueue; 19 | 20 | int current = 0, fuel = 0; 21 | 22 | while(current < new_size) 23 | { 24 | // This indicates that the last decision was incorrect 25 | if(fuel<0) 26 | { 27 | // Clear everything for fresh iterations 28 | fuel = 0; 29 | while(!myQueue.empty()) 30 | myQueue.pop(); 31 | } 32 | 33 | // Tour completed 34 | if(myQueue.size() == original_size) 35 | return myQueue.front(); 36 | 37 | // Enqueue the pump blindly 38 | fuel += gas[current]; 39 | fuel -= cost[current]; 40 | myQueue.push(current); 41 | 42 | // Go to the next pump 43 | current++; 44 | } 45 | 46 | return -1; 47 | } 48 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1007 BST From Preorder/BST From Preorder O(n^2).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | TreeNode* construct(vector& preorder, int low, int high); 5 | 6 | TreeNode* bstFromPreorder(vector& preorder) 7 | { 8 | return construct(preorder, 0, preorder.size()-1); 9 | } 10 | }; 11 | 12 | /* Constructs the binary search tree whose preorder is a[low,...,high] */ 13 | TreeNode* Solution :: construct(vector& preorder, int low, int high) 14 | { 15 | // If low and high cross, or if they are out of bound, the tree does not exist 16 | if(low<0 || high<0) return nullptr; 17 | if(low>high) return nullptr; 18 | 19 | // The first element of the traversal is the root 20 | TreeNode* root = new TreeNode(preorder[low]); 21 | 22 | // greaterIndex stores the index of the first element greater than root's val 23 | int greaterIndex = high+1; 24 | for(int i=low+1; i<=high; i++) 25 | { 26 | if(preorder[i]>root->val) 27 | { 28 | greaterIndex=i; 29 | break; 30 | } 31 | } 32 | 33 | // Construct the left and right subtree recursively 34 | root->left = construct(preorder, low+1, greaterIndex-1); 35 | root->right = construct(preorder, greaterIndex, high); 36 | 37 | // Return the filled tree 38 | return root; 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/LC #127 Contest Review.md: -------------------------------------------------------------------------------- 1 | **Questions Solved** ---- 3 (Q-1, Q-3, Q-4) 2 | 3 | **Penalties** --- **1** (on Q-1) 4 | ----**2** (on Q-4) 5 | 6 | *Submission Time* ---- 7 | 8 | Q1) **16 minutes, 18 minutes** 9 | 10 | Q4) **49 minutes, 53 minutes** 11 | 12 | Q3) **1 hour 29 minutes 36 seconds** (This was such a close call!) 13 | 14 | 15 | **Rank** ---- 1868/4071 16 | 17 | 18 | **Remarks** ----- I have mixed feelings about this contest. I managed to solve 3 out of 4 questions yet I'm not satisfied with my performance. 19 | I ended up doing a lot of incorrect submissions. My accuracy in this contest was way off the mark. Moreover, I didn't write quality codes in 20 | any of the questions. I didn't even realize that the time complexity of the 4th question is O(n^2). I ended up taking down that post and my other 21 | solutions received bad reviews too. I need to focus more on writing quality codes with optimal complexity along with a thorough explanation. This 22 | would benefit me more than anyone else, as it would be a great help during my revision. I was going through the solution of the top 10 people 23 | in the contest and I was literally amazed by the elegance of their solution. Now I realize why are they able to complete the contest within 10 24 | to 15 minutes. **I have to see the codes of atleast top 10 people from the next contest**. 25 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#45 Jump Game II/Bruteforce BFS (TLE).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int jump(vector& nums); 5 | }; 6 | 7 | int Solution :: jump(vector& a) 8 | { 9 | int n = a.size(); 10 | 11 | // This also functions as the visited array 12 | vector level(n,-1); 13 | 14 | // Queue contains the indexes 15 | queue bfs; 16 | bfs.push(0); 17 | level[0] = 0; 18 | 19 | int nextIndex; 20 | 21 | // Perform the bfs 22 | while(!bfs.empty()) 23 | { 24 | int currentIndex = bfs.front(); 25 | bfs.pop(); 26 | 27 | // Notice the equality 28 | for(int steps = 1; steps <= a[currentIndex]; steps++) 29 | { 30 | // Go Left 31 | nextIndex = currentIndex + steps; 32 | if(nextIndex < n and level[nextIndex] == -1) 33 | { 34 | bfs.push(nextIndex); 35 | level[nextIndex] = level[currentIndex] + 1; 36 | } 37 | 38 | // Go Right 39 | nextIndex = currentIndex - steps; 40 | if(nextIndex >= 0 and level[nextIndex] == -1) 41 | { 42 | bfs.push(nextIndex); 43 | level[nextIndex] = level[currentIndex] + 1; 44 | } 45 | } 46 | } 47 | 48 | return level.back(); 49 | } 50 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #127/#1008 Minimum Domino Rotations For Equal Row/Explanation and Link.md: -------------------------------------------------------------------------------- 1 | **Intuition** 2 | * Create a helper function `minSteps` that takes as input 2 vectors and a `candidate` and returns the minimum steps to convert every element in the `target` array to `candidate`. It returns -1 if the target vector cannot be converted in the desired fashion. This function is used to remove code redundancy. 3 | * Create a frquency array and update the frequency of each element (as every element is in the range `[1,6]`.) 4 | * Traverse the frequency array and capture the `candidates`, i.e, elements which occur atleast half the time [inclusive]. Note that this is not the same as majority element as majority element should occur strictly more than `n/2` times(and hence Moore's Algorithm won't work). However, there can be atmost 2 candidates. 5 | * If there is no candidate, return -1 6 | * For each of the candidate, try to adjust it in both the top and bottom half and take the best outcome of the two. 7 | 8 | 9 | **Blog** https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/252446/detailed-explanation 10 | 11 | **Alternate link** https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/252242/JavaPython-Find-Intersection-of-Dominos 12 | 13 | https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/252266/C%2B%2B-check-A0-and-B0 14 | -------------------------------------------------------------------------------- /HackerRank/String Algorithms/LCS/Common Child/Simple LCS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Complete the commonChild function below. 6 | int commonChild(string str1, string str2) 7 | { 8 | int row = str1.length() + 1; 9 | int col = str2.length() + 1; 10 | 11 | vector> lcs(row, vector (col, 0)); 12 | 13 | /* LCS[i][j] represents the lcs of the first i characters of str1 14 | * and first j characters of str2 15 | */ 16 | 17 | for(int i = 1; i <= str1.length(); i++) 18 | { 19 | for(int j = 1; j <= str2.length(); j++) 20 | { 21 | // If the last character match, take it 22 | if(str1[i-1] == str2[j-1]) 23 | lcs[i][j] = 1 + lcs[i-1][j-1]; 24 | 25 | else 26 | lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]); 27 | } 28 | } 29 | 30 | return lcs[str1.length()][str2.length()]; 31 | } 32 | 33 | int main() 34 | { 35 | ofstream fout(getenv("OUTPUT_PATH")); 36 | 37 | string s1; 38 | getline(cin, s1); 39 | 40 | string s2; 41 | getline(cin, s2); 42 | 43 | int result = commonChild(s1, s2); 44 | 45 | fout << result << "\n"; 46 | 47 | fout.close(); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Pseudocode/Dynamic Programming/Maximum Sum Subarray/SourceCode.tex: -------------------------------------------------------------------------------- 1 | % Set the Page Layout 2 | \documentclass[12pt]{article} 3 | \usepackage[inner = 2.0cm, outer = 2.0cm, top = 2.0cm, bottom = 2.0cm]{geometry} 4 | 5 | 6 | % Package to write pseudo-codes 7 | \usepackage{algorithm} 8 | 9 | % Remove the 'end' at the end of the algorithm 10 | \usepackage[noend]{algpseudocode} 11 | 12 | % Define Left Justified Comments 13 | \algnewcommand{\LeftComment}[1]{\Statex \(\triangleright\) #1} 14 | 15 | % Remove the Numbering of the Algorithm 16 | \usepackage{caption} 17 | \DeclareCaptionLabelFormat{algnonumber}{Algorithm} 18 | \captionsetup[algorithm]{labelformat = algnonumber} 19 | 20 | \begin{document} 21 | 22 | \begin{algorithm} 23 | 24 | \caption{Find the length of the subarray with the maximum sum} 25 | 26 | \begin{algorithmic}[1] 27 | \Ensure One Based Indexing 28 | \Statex 29 | 30 | \Function{Kadane}{$Arr, len$} 31 | 32 | \LeftComment{$start[i]$ denotes the length of the maximum sum subarray which starts at the $i-th$ index} 33 | \Statex 34 | 35 | \State $start[len] \gets a[len]$ 36 | \For{$ i = len-1 : 1$} 37 | \State $start[i] \gets max(a[i] + start[i+1], a[i])$ 38 | \EndFor 39 | 40 | \State \Return{Maximum element of $Start$ array} 41 | \EndFunction 42 | \end{algorithmic} 43 | 44 | \end{algorithm} 45 | 46 | \end{document} 47 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #131/#1022 Sum of root to leaf Binary Numbers/Vector Based Enumeration.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | vector bits; 4 | public: 5 | int sumRootToLeaf(TreeNode* root); 6 | }; 7 | 8 | /* Returns the sum of all paths from root to leaf */ 9 | int Solution :: sumRootToLeaf(TreeNode* root) 10 | { 11 | // If the tree doesn't exist, the number formed is 0 12 | if(!root) return 0; 13 | 14 | // Take this element on our path 15 | bits.push_back(root->val); 16 | 17 | // If it is a leaf node, we have enumerated a path 18 | if(!root->left and !root->right) 19 | { 20 | // We have the binary representation, Convert to decimal 21 | int sum=0; 22 | int power_of_2 = 1; 23 | for(int i=bits.size()-1; i>=0; i--) 24 | { 25 | sum += power_of_2*bits[i]; 26 | power_of_2 *= 2; 27 | } 28 | 29 | // Remove the element from the path and back track 30 | bits.pop_back(); 31 | return sum; 32 | } 33 | 34 | // If it is not a leaf node, enumerate paths in both directions 35 | int leftAnswer = sumRootToLeaf(root->left); 36 | int rightAnswer = sumRootToLeaf(root->right); 37 | 38 | // Remove this element from the path to backtrack 39 | bits.pop_back(); 40 | 41 | // Return the sum of all numbers in both the halfs 42 | return leftAnswer+rightAnswer; 43 | } 44 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #138/#1054 Distant Barcodes/Max Heap Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector rearrangeBarcodes(vector& barcodes); 5 | }; 6 | 7 | vector Solution :: rearrangeBarcodes(vector& a) 8 | { 9 | // Vector to store the final answer 10 | vector answer; 11 | 12 | // Update the frequency of each character 13 | unordered_map myMap; 14 | for(auto ele : a) 15 | myMap[ele]++; 16 | 17 | // Priority queue to store the elements by frequency 18 | priority_queue, vector>> maxHeap; 19 | 20 | // Populate the max Heap. Frequency is the first field, value is second 21 | for(auto ele : myMap) 22 | maxHeap.push(make_pair(ele.second, ele.first)); 23 | 24 | pair previous = {0,0}; 25 | while(!maxHeap.empty()) 26 | { 27 | // Extract the top element 28 | auto topElement = maxHeap.top(); 29 | maxHeap.pop(); 30 | 31 | // Interleave it 32 | answer.push_back(topElement.second); 33 | 34 | // Push the previously pulled element 35 | if(previous.first>0) 36 | maxHeap.push(previous); 37 | 38 | // Used once, reduce frequency and update previous 39 | topElement.first = topElement.first - 1; 40 | previous = topElement; 41 | } 42 | 43 | // Return the populated vector 44 | return answer; 45 | } 46 | -------------------------------------------------------------------------------- /HackerRank/Dynamic Programming/Red John is Back/Simple DP and Sieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /* Returns the number of ways to lay the bricks */ 6 | int ways(int n) 7 | { 8 | vector dp(n+1, 0); 9 | 10 | // As per the sample test cases 11 | dp[1] = 1; 12 | dp[2] = 1; 13 | dp[3] = 1; 14 | dp[4] = 2; 15 | 16 | // Either place a vertical or horizontal block first 17 | for(int i = 5; i <= n; i++) 18 | dp[i] = dp[i-1] + dp[i-4]; 19 | 20 | return dp[n]; 21 | } 22 | 23 | int redJohn(int n) 24 | { 25 | int limit = ways(n); 26 | 27 | // Standard Sieve begins 28 | vector prime(limit + 1, true); 29 | 30 | prime[0] = false; 31 | prime[1] = false; 32 | 33 | // Be careful not to start outer loop from 1. Cost me a WA 34 | for(int i = 2; i <= limit; i++) 35 | for(int j = 2*i; j <= limit; j += i) 36 | prime[j] = false; 37 | 38 | int count = 0; 39 | for(int i = 0; i <= limit; i++) 40 | if(prime[i]) 41 | count++; 42 | 43 | return count; 44 | } 45 | 46 | 47 | int main() 48 | { 49 | ofstream fout(getenv("OUTPUT_PATH")); 50 | 51 | int t; 52 | cin >> t; 53 | cin.ignore(numeric_limits::max(), '\n'); 54 | 55 | for (int t_itr = 0; t_itr < t; t_itr++) { 56 | int n; 57 | cin >> n; 58 | cin.ignore(numeric_limits::max(), '\n'); 59 | 60 | int result = redJohn(n); 61 | 62 | fout << result << "\n"; 63 | } 64 | 65 | fout.close(); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Codechef/Dynamic Programming/Squared Subsequences (SQRDSUB)/DP_Approach.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | /* Returns the total number of subarrays a[i...j] such that a[i]*...*a[j] is divisible by mod */ 6 | long Total_Subarrays_Divisible_By(int mod, vector &a) 7 | { 8 | int n = a.size(); 9 | vector> dp(n, vector(mod, 0)); 10 | 11 | /* DP[i][rem] dentoes the number of subarrays ending at 'i' with remainder 'rem' */ 12 | 13 | dp[0][a[0]%mod]++; 14 | for(int i = 1; i < n; i++) 15 | { 16 | int current_rem = a[i]%mod; 17 | 18 | // A single element subarray 19 | dp[i][current_rem]++; 20 | 21 | for(int old_rem = 0; old_rem < mod; old_rem++) 22 | { 23 | int new_rem = (current_rem*old_rem)%mod; 24 | dp[i][new_rem] += dp[i-1][old_rem]; 25 | } 26 | } 27 | 28 | long res = 0; 29 | for(int i = 0; i < n; i++) 30 | res += dp[i][0]; 31 | 32 | return res; 33 | } 34 | 35 | void Squared_Subsequences(vector &a) 36 | { 37 | long n = a.size(); 38 | long ans = Total_Subarrays_Divisible_By(4, a); 39 | ans += n*(n+1)/2 - Total_Subarrays_Divisible_By(2, a); 40 | 41 | cout << ans << endl; 42 | } 43 | 44 | int main() 45 | { 46 | int t; 47 | cin >> t; 48 | 49 | for(int i = 0; i < t; i++) 50 | { 51 | int n; 52 | cin >> n; 53 | 54 | vector a(n); 55 | for(auto &ele : a) 56 | cin >> ele, ele = abs(ele); 57 | 58 | Squared_Subsequences(a); 59 | } 60 | return 0; 61 | } 62 | 63 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #129/#1023 Binary string with substring from 1 to N/ReadMe.md: -------------------------------------------------------------------------------- 1 | [Blog](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/261123/detailed-explanation-still-bruteforce-though-c) 2 | 3 | **Credits** 4 | * I thought this bruteforce idea during the contest but didn't have the courage to code it up during the contest. (As I was afraid of **TLE**). However, after seeing the solution of the top performers after the contest, especially [neal_wu's](https://leetcode.com/neal_wu/) submission, I realized that the problem was indeed a simple one and I should've gone for the bruteforce solution. **Sometimes, you just have to trust your instincts**. 5 | * You can refer to [votrubac's post](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/260882/C%2B%2B-O(S-log-N)-vs.-O(N-*-(S-%2B-log-N))) to convince yourself why the bruteforce method works. As **Vlad** pointed out, there aren't too many numbers you can fit in such a small string. Hence, the loop would break very soon. 6 | 7 | **Intuition** 8 | * For each number from 1 to `N`, convert its binary representation to a string and check whether the string is present in the original string or not. Alhough string matching can be done in O(n) using **KMP** or **Rabin Karp**, I've used the bruteforce method of string library (which in practcice is more faster than the above mentioned algorithms since the chances of a lot of partial matches is very less.) 9 | -------------------------------------------------------------------------------- /UVa Online Judge/Binary Search the Answer/Monkey and Oiled Bamboo (12032)/Clean Implementation (Safe).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Assumes that the sentinel is appended at the front */ 5 | bool possible(vector &a, int max_jump_length) 6 | { 7 | int n = a.size(); 8 | 9 | for(int i = 1; i < n; i++) 10 | { 11 | if(max_jump_length <= 0) 12 | return false; 13 | 14 | int jump = a[i] - a[i-1]; 15 | 16 | if(jump > max_jump_length) 17 | return false; 18 | 19 | if(jump == max_jump_length) 20 | max_jump_length--; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | int solve(vector &a) 27 | { 28 | int low = 1; 29 | int high = 1e7; 30 | 31 | int res; 32 | 33 | /* Clean implementation of Binary Search */ 34 | while(low <= high) 35 | { 36 | int mid = (low + high)/2; 37 | 38 | if(possible(a, mid)) 39 | { 40 | res = mid; 41 | high = mid - 1; 42 | } 43 | else 44 | { 45 | low = mid + 1; 46 | } 47 | } 48 | 49 | assert(possible(a, res)); 50 | 51 | return res; 52 | } 53 | 54 | int main() 55 | { 56 | int test; 57 | cin >> test; 58 | 59 | for(int i = 1; i <= test; i++) 60 | { 61 | int n; 62 | cin >> n; 63 | 64 | vector a(n); 65 | for(auto &ele : a) 66 | cin >> ele; 67 | 68 | int sentinel = 0; 69 | 70 | // Technique to insert an element at the front 71 | a.insert(a.begin(), sentinel); 72 | 73 | cout << "Case " << i << ": " << solve(a) << endl; 74 | 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode Contest #152/#1177 Can Make Palindrome Substring/Prefix Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector canMakePaliQueries(string s, vector>& queries); 5 | }; 6 | 7 | vector Solution :: canMakePaliQueries(string str, vector>& queries) 8 | { 9 | int n = str.length(); 10 | vector> dp(26, vector(n,0)); 11 | 12 | /* dp[i][j] represents the count of the i-th character in the string str[0...i] */ 13 | 14 | for(int i = 0; i < 26; i++) 15 | { 16 | char currentChar = i + 'a'; 17 | for(int j = 0; j < n; j++) 18 | { 19 | if(j == 0) 20 | dp[i][j] = (str[j] == currentChar); 21 | else 22 | dp[i][j] = dp[i][j-1] + (str[j] == currentChar); 23 | } 24 | } 25 | 26 | vector ans; 27 | for(auto query : queries) 28 | { 29 | int left = query[0]; 30 | int right = query[1]; 31 | int k = query[2]; 32 | 33 | int unMatchedCount = 0; 34 | for(int i = 0; i < 26; i++) 35 | { 36 | int occurrence = dp[i][right] - dp[i][left] + (str[left] == (i + 'a')); 37 | 38 | if(occurrence & 1) 39 | unMatchedCount++; 40 | } 41 | 42 | int requiredConversions = unMatchedCount / 2; 43 | ans.push_back(requiredConversions <= k); 44 | } 45 | 46 | return ans; 47 | } 48 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #10/#1214 Two Sum BST/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## Review 2 | I didn't realize that the 2 trees were BST. I solved it assuming normal trees (by converting to hash map). Although the complexity remains linear, it's not such a good solution. I should really code up the alternate solution using Tree Paradigms. 3 | 4 | # Time Complexity 5 | I see a lot of solutions applying **Binary Search** on the second tree. The worst case time complexity of these solution is *O(n1 * n2)*. This is because *Searching* in a Balanced BST is *O(log(n))* but searching in a normal BST is only bounded by *O(h)* where, `h` is the height of the tree. Hence, in the worst case, the second tree might be tilted to one side and hence searching would take *O(n)* time for each call resulting in *O(n1 * n2)* time complexity. 6 | 7 | **My Suggestion** : Since we are already using Linear Space (due to recursive calls), why not just store the second BST in a Red Black Tree (such as Maps in C++). This would ensure worst case **O(n log(n))**. 8 | 9 | # Intuition 10 | Perhaps this is better visualized as an array problem. Given 2 arrays, does there exists 2 numbers (one in each) that sums upto `k`. Calculating this is very easy. Just store all the values of both the trees in 2 hashmap, and then for each element in one hashmap, check if its complement is present in the other or not. 11 | 12 | 13 | ## Blog 14 | [Link](https://leetcode.com/problems/two-sum-bsts/discuss/397796/Searching-in-a-BST-is-not-O(-log(n)-)) 15 | -------------------------------------------------------------------------------- /UVa Online Judge/2D Range Sum/Maximum Sum (108)/O(n^4).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getSum(vector> &partial, int x, int y, int p, int q) 5 | { 6 | int top_left = x and y ? partial[x-1][y-1]: 0; 7 | int top_right = x ? partial[x-1][q] : 0; 8 | int bot_left = y ? partial[p][y-1] : 0; 9 | int bot_right = partial[p][q]; 10 | 11 | int res = bot_right - top_right; 12 | res -= (bot_left - top_left); 13 | 14 | return res; 15 | } 16 | 17 | void partialSum(vector> &mat) 18 | { 19 | int R = mat.size(); 20 | int C = mat[0].size(); 21 | 22 | vector> partial(R, vector(C, 0)); 23 | 24 | for(int i = 0; i < R; i++) 25 | { 26 | int runningSum = 0; 27 | for(int j = 0; j < C; j++) 28 | { 29 | runningSum += mat[i][j]; 30 | partial[i][j] = runningSum + (i ? partial[i-1][j] : 0); 31 | } 32 | } 33 | 34 | mat = partial; 35 | } 36 | 37 | int main() 38 | { 39 | 40 | int n; 41 | cin >> n; 42 | 43 | int R, C; 44 | R = C = n; 45 | 46 | vector> mat(R, vector (C, 0)); 47 | 48 | for(auto &row_vec : mat) 49 | for(auto &ele : row_vec) 50 | cin >> ele; 51 | 52 | partialSum(mat); 53 | 54 | int global_max = INT_MIN; 55 | 56 | for(int x = 0; x < R; x++) 57 | for(int y = 0; y < C; y++) 58 | for(int p = x; p < R; p++) 59 | for(int q = y; q < C; q++) 60 | global_max = max(global_max, getSum(mat, x, y, p, q)); 61 | 62 | 63 | cout << global_max << endl; 64 | } 65 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#138 Cloning a Linked List with Random Pointers/First Draft (Uncommented).cpp: -------------------------------------------------------------------------------- 1 | 2 | /* Warning ---> This code would fail for lists with cycles or duplicate node values */ 3 | 4 | class Solution 5 | { 6 | public: 7 | Node* copyRandomList(Node* orig_head); 8 | }; 9 | 10 | /* Deep Copies the given linked list */ 11 | Node* Solution :: copyRandomList(Node* orig_head) 12 | { 13 | // Handle the corner case 14 | if(!orig_head) return orig_head; 15 | 16 | Node* copyHead = new Node(orig_head->val, nullptr, nullptr); 17 | Node* newHead = copyHead; 18 | Node* oldHead = orig_head->next; 19 | 20 | while(oldHead) 21 | { 22 | newHead->next = new Node(oldHead->val, nullptr, nullptr); 23 | newHead = newHead->next; 24 | oldHead = oldHead->next; 25 | } 26 | 27 | // Map the address of the new copies 28 | unordered_map address; 29 | 30 | newHead = copyHead; 31 | while(newHead) 32 | { 33 | address[newHead->val] = newHead; 34 | newHead = newHead->next; 35 | } 36 | 37 | // Traverse both the lists together and fill the random pointers 38 | oldHead = orig_head; 39 | newHead = copyHead; 40 | 41 | while(oldHead && newHead) 42 | { 43 | newHead->random = oldHead->random? address[(oldHead->random)->val] : nullptr; 44 | oldHead = oldHead->next; 45 | newHead = newHead->next; 46 | } 47 | 48 | return copyHead; 49 | } 50 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#155 Stack to Implement getMin/Auxillary Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack 2 | { 3 | public: 4 | stack centralStack; 5 | stack minStack; 6 | 7 | void push(int x); 8 | void pop(); 9 | int top(); 10 | int getMin(); 11 | }; 12 | 13 | /* Pushes the element to the central stack and updates min value */ 14 | void MinStack :: push(int x) 15 | { 16 | centralStack.push(x); 17 | 18 | // If it is the current first element, set it to min 19 | if(minStack.empty()) minStack.push(x); 20 | 21 | // Else compare it with curr_min 22 | else 23 | { 24 | int curr_min = minStack.top(); 25 | 26 | // Update the minStack if it replaces the curr_min 27 | // Push duplicates of curr_min also to reserve min while popping 28 | if(x<=curr_min) minStack.push(x); 29 | } 30 | } 31 | 32 | /* Pops the last element from the stack */ 33 | void MinStack :: pop() 34 | { 35 | int toBeRemoved = centralStack.top(); 36 | centralStack.pop(); 37 | 38 | // Remove one copy if it is the minimum 39 | if(toBeRemoved == minStack.top()) minStack.pop(); 40 | } 41 | 42 | /* Returns the top element */ 43 | int MinStack :: top() 44 | { 45 | // Same as a normal stack 46 | return centralStack.top(); 47 | } 48 | 49 | /* Returns a copy of the minimum element */ 50 | int MinStack :: getMin() 51 | { 52 | // Just return the element at the top of the minStack 53 | return minStack.top(); 54 | } 55 | -------------------------------------------------------------------------------- /Pseudocode/Heaps/Minimum Cost to Connect Ropes/SourceCode.tex: -------------------------------------------------------------------------------- 1 | % Set the Page Layout 2 | \documentclass[12pt]{article} 3 | \usepackage[inner = 2.0cm, outer = 2.0cm, top = 2.0cm, bottom = 2.0cm]{geometry} 4 | 5 | 6 | % Package to write pseudo-codes 7 | \usepackage{algorithm} 8 | 9 | % Remove the 'end' at the end of the algorithm 10 | \usepackage[noend]{algpseudocode} 11 | 12 | % Define Left Justified Comments 13 | \algnewcommand{\LeftComment}[1]{\Statex \(\triangleright\) #1} 14 | 15 | % Remove the Numbering of the Algorithm 16 | \usepackage{caption} 17 | \DeclareCaptionLabelFormat{algnonumber}{Algorithm} 18 | \captionsetup[algorithm]{labelformat = algnonumber} 19 | 20 | \begin{document} 21 | 22 | \begin{algorithm} 23 | 24 | \caption{Find the minimum cost to connect $n$ ropes} 25 | 26 | \begin{algorithmic}[1] 27 | \Statex 28 | 29 | \Function{Connect\_Ropes}{$Arr$} 30 | \For{$i = 1 : N$} 31 | \State $min\_heap.push(a[i])$ 32 | \EndFor 33 | 34 | \State $cost \gets 0$ 35 | \While{$min\_heap.size > 1$} 36 | \State $min\_element \gets min\_heap.top$, $min\_heap.pop$ 37 | \State $second\_min\_element \gets min\_heap.top$, $min\_heap.pop$ 38 | 39 | \State $cost += min\_element + second\_element$ 40 | \State $min\_heap.push(min\_element + max\_element)$ 41 | \EndWhile 42 | \EndFunction 43 | \end{algorithmic} 44 | 45 | \end{algorithm} 46 | 47 | \end{document} 48 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #17/#5144 Matrix Block Sum/Range Sum DP.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | vector> mat; 4 | public: 5 | int get_rectangle_sum(int x, int y, int p, int q); 6 | vector> matrixBlockSum(vector>& mat, int k); 7 | }; 8 | 9 | int Solution :: get_rectangle_sum(int x, int y, int p, int q) 10 | { 11 | int top_left = x and y ? mat[x-1][y-1] : 0; 12 | int top_right = x ? mat[x-1][q] : 0; 13 | int bot_left = y ? mat[p][y-1] : 0; 14 | int bot_right = mat[p][q]; 15 | 16 | 17 | int sum = bot_right - top_right; 18 | sum -= (bot_left - top_left); 19 | 20 | return sum; 21 | } 22 | 23 | vector> Solution :: matrixBlockSum(vector>& input_matrix, int k) 24 | { 25 | // Serious Bug (Due to Name Collision) 26 | this->mat = input_matrix; 27 | 28 | int row = mat.size(); 29 | int col = mat[0].size(); 30 | 31 | // Convert to partial sum 32 | for(int i = 0; i < row; i++) 33 | { 34 | int running_sum = 0; 35 | for(int j = 0; j < col; j++) 36 | { 37 | running_sum += mat[i][j]; 38 | mat[i][j] = running_sum + (i ? mat[i-1][j] : 0); 39 | } 40 | } 41 | 42 | vector> res(row, vector(col, 0)); 43 | 44 | for(int i = 0; i < row; i++) 45 | { 46 | for(int j = 0; j < col; j++) 47 | { 48 | int x = i-k, y = j-k; 49 | int p = i+k, q = j+k; 50 | 51 | res[i][j] = get_rectangle_sum(max(0,x), max(0,y), min(row - 1, p), min(col - 1, q)); 52 | } 53 | } 54 | 55 | return res; 56 | } 57 | -------------------------------------------------------------------------------- /LeetCode Contests/LeetCode BiWeekly Contest #8/#1181 Before After Puzzle/String Stream.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector beforeAndAfterPuzzles(vector& phrases); 5 | }; 6 | 7 | vector Solution :: beforeAndAfterPuzzles(vector& phrase) 8 | { 9 | set store; 10 | int n = phrase.size(); 11 | 12 | for(int i = 0; i < n ; i++) 13 | { 14 | for(int j = 0; j < n ; j++) 15 | { 16 | if(i == j) 17 | continue; 18 | 19 | stringstream first(phrase[i]); 20 | stringstream second(phrase[j]); 21 | 22 | string temp; 23 | 24 | vector firstString; 25 | vector secondString; 26 | 27 | while(first >> temp) 28 | firstString.push_back(temp); 29 | 30 | while(second >> temp) 31 | secondString.push_back(temp); 32 | 33 | if(firstString.back() == secondString.front()) 34 | { 35 | string res = phrase[i]; 36 | 37 | for(int k = 1; k < secondString.size(); k++) 38 | res += " " + secondString[k]; 39 | 40 | store.insert(res); 41 | } 42 | } 43 | } 44 | 45 | vector ans; 46 | for(auto ele : store) 47 | ans.push_back(ele); 48 | 49 | return ans; 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode Non-Contest Solutions/#42 Trapping Rain Water/DP Approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int trap(vector& height); 5 | }; 6 | 7 | int Solution :: trap(vector& a) 8 | { 9 | int n = a.size(); 10 | 11 | if(n==0) return 0; 12 | 13 | // Stores the elevation of the highest block to the left (strictly left) 14 | int leftMax[n]; 15 | 16 | // Fill the leftMax array 17 | leftMax[0] = 0; 18 | for(int i=1; i=0; i--) 27 | rightMax[i] = max(rightMax[i+1],a[i+1]); 28 | 29 | // Create the contributions array 30 | int contribution[n]; 31 | 32 | // Calculate the contributions 33 | for(int i=0; i taken; 5 | vector count; 6 | vector score; 7 | int max_sum = 0; 8 | 9 | void update_score(vector& words); 10 | void generate_subset(vector& words, int n); 11 | int maxScoreWords(vector& words, vector& letters, vector& score); 12 | }; 13 | 14 | void Solution :: generate_subset(vector& words, int n) 15 | { 16 | if(n == 0) 17 | { 18 | update_score(words); 19 | return; 20 | } 21 | 22 | taken[n-1] = true; 23 | generate_subset(words, n-1); 24 | 25 | taken[n-1] = false; 26 | generate_subset(words, n-1); 27 | } 28 | 29 | void Solution :: update_score(vector& words) 30 | { 31 | int current_score = 0; 32 | vector freq(26, 0); 33 | 34 | for(int i = 0; i < words.size(); i++) 35 | { 36 | if(taken[i]) 37 | { 38 | for(auto ele : words[i]) 39 | { 40 | int ind = ele - 'a'; 41 | current_score += score[ind]; 42 | freq[ind]++; 43 | 44 | if(freq[ind] > count[ind]) 45 | return; 46 | } 47 | } 48 | } 49 | 50 | max_sum = max(max_sum, current_score); 51 | } 52 | 53 | int Solution :: maxScoreWords(vector& words, vector& letters, vector& score) 54 | { 55 | taken.resize(words.size(), false); 56 | count.resize(26, 0); 57 | this->score = score; 58 | 59 | for(auto ele : letters) 60 | count[ele - 'a']++; 61 | 62 | int n = words.size(); 63 | generate_subset(words, n); 64 | 65 | return max_sum; 66 | } 67 | --------------------------------------------------------------------------------