├── .gitignore ├── README.md ├── contest.md ├── editor_snippets ├── README.md ├── sublime_snippets │ ├── README.md │ ├── cpp │ │ ├── Debug.sublime-snippet │ │ ├── Number.sublime-snippet │ │ └── init.sublime-snippet │ └── sublime-snippet.gif └── vs_code_snippets │ ├── README.md │ ├── cpp.json │ └── python.json ├── lld ├── coffeeVendingMachine │ ├── Readme.md │ ├── build.gradle.kts │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle.kts │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── example │ │ ├── Main.java │ │ └── coffeeVendingMachine │ │ ├── CoffeeVendingMachine.java │ │ ├── Observer.java │ │ ├── coffee │ │ ├── Coffee.java │ │ ├── CoffeeManager.java │ │ ├── CoffeeType.java │ │ ├── Expresso.java │ │ └── Lattee.java │ │ ├── ingredient │ │ ├── FixedQuantityIngredient.java │ │ ├── Ingredient.java │ │ ├── IngredientInventory.java │ │ ├── IngredientType.java │ │ └── QuantityUpdatableIngredient.java │ │ └── payment │ │ └── Payment.java ├── flipCache │ ├── Readme.md │ ├── build.gradle.kts │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle.kts │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── example │ │ ├── Main.java │ │ ├── adaptor │ │ └── outbound │ │ │ ├── CacheHitMetricCollector.java │ │ │ ├── InMemoryDataSource.java │ │ │ └── SimpleEvictionPolicy.java │ │ └── application │ │ ├── models │ │ └── Event.java │ │ ├── ports │ │ ├── inbound │ │ │ ├── GetCache.java │ │ │ └── SetCache.java │ │ └── outbound │ │ │ ├── CacheHook.java │ │ │ ├── DataSource.java │ │ │ └── EvictionPolicy.java │ │ └── service │ │ └── FlipCache.java ├── hospitalManagementSystem │ ├── .gradle │ │ ├── 8.10 │ │ │ ├── checksums │ │ │ │ ├── checksums.lock │ │ │ │ ├── md5-checksums.bin │ │ │ │ └── sha1-checksums.bin │ │ │ ├── dependencies-accessors │ │ │ │ └── gc.properties │ │ │ ├── executionHistory │ │ │ │ ├── executionHistory.bin │ │ │ │ └── executionHistory.lock │ │ │ ├── fileChanges │ │ │ │ └── last-build.bin │ │ │ ├── fileHashes │ │ │ │ ├── fileHashes.bin │ │ │ │ ├── fileHashes.lock │ │ │ │ └── resourceHashesCache.bin │ │ │ └── gc.properties │ │ ├── buildOutputCleanup │ │ │ ├── buildOutputCleanup.lock │ │ │ ├── cache.properties │ │ │ └── outputFiles.bin │ │ ├── file-system.probe │ │ └── vcs-1 │ │ │ └── gc.properties │ ├── Readme.md │ ├── build.gradle.kts │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle.kts │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── example │ │ ├── Main.java │ │ └── domain │ │ ├── dto │ │ ├── Appointment.java │ │ ├── Doctor.java │ │ ├── DoctorRankingStrategy.java │ │ ├── DoctorSpeciality.java │ │ ├── Patient.java │ │ ├── TimeDuration.java │ │ └── TimeSlot.java │ │ ├── ports │ │ ├── BookAppointment.java │ │ ├── CancelAppointment.java │ │ ├── RegisterDoctor.java │ │ └── SearchSlotsBasedOnSpeciality.java │ │ └── service │ │ ├── DefaultRankingStrategy.java │ │ └── HospitalManagementSystem.java └── lightBulbCommandPattern │ ├── Readme.md │ ├── build.gradle.kts │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle.kts │ └── src │ └── main │ └── java │ └── org │ └── example │ ├── Main.java │ └── lightBulb │ ├── Command.java │ ├── LightBulb.java │ ├── LightBulbTurnOffCommand.java │ ├── LightBulbTurnOnCommand.java │ ├── Remote.java │ └── event │ ├── Event.java │ ├── EventHook.java │ ├── LightBulbTurnOffMetric.java │ └── LightBulbTurnOnMetric.java ├── oops ├── .gitignore ├── Kata-Log │ ├── gossiping-bus-drivers │ │ ├── README.md │ │ ├── driver.py │ │ ├── simulator.py │ │ └── simulator_test.py │ └── parallel-change │ │ ├── README.md │ │ ├── field.py │ │ ├── method.py │ │ ├── run.sh │ │ └── tests.py ├── LLD-Problems │ ├── Locker.py │ └── vending_machine │ │ ├── .gitignore │ │ ├── Readme.md │ │ ├── requirements.txt │ │ ├── setup.py │ │ ├── src │ │ ├── models │ │ │ └── product.py │ │ └── vending_machine.py │ │ └── tests │ │ ├── models │ │ └── test_product.py │ │ └── test_vending_machine.py └── README.md ├── others ├── debugger_template.cpp ├── fast_scan.cpp ├── io.cpp ├── namingConventions.md ├── palindrome_count.cpp ├── split.cpp ├── time_template.cpp └── writing_modular_code.md └── solution ├── CSES ├── Dynamic Programming │ ├── Array Description.cpp │ ├── Coin Combinations I.cpp │ ├── Dice Combinations.py │ ├── Edit Distance.cpp │ ├── Grid Paths.cpp │ ├── Minimizing Coins.cpp │ └── Removing Digits.cpp └── Introductory Problems │ └── Missing Number.py ├── HackerEarth_solutions ├── ApplyKMP.cpp ├── Cost_of_Data.cpp ├── DifDif.cpp ├── Dijkstras.cpp ├── Distinct_Integers_in_Range.cpp ├── Grid.cpp ├── Special_Pairs.cpp ├── Xor_and_Insert.cpp └── Xor_sum.cpp ├── Intern ├── README.md └── cheatSheet │ ├── Find Missing And Repeating.md │ ├── Find n^x in log N.md │ ├── GCD Of Array.md │ ├── Grid Unique Paths.md │ ├── Inversion Of Array (Using Merge Sort).md │ ├── LRU Cache.md │ ├── Largest Rectangle In Histogram.md │ ├── Next Permutation.md │ ├── Pascals Triangle.md │ ├── README.md │ └── Set Matrix Zeros.md ├── README.md ├── atcoder ├── 1or2.cpp ├── Bowls and Dishes.cpp ├── CrestedIbisVsMonster.cpp ├── EvenRelation.cpp ├── SiverFoxVsMonster.cpp ├── Sum of Divisors.cpp ├── Through Path.cpp ├── contests │ └── ABC161 │ │ ├── A.md │ │ ├── B.md │ │ ├── C.md │ │ └── README.md └── educational_dp_contest │ ├── A.cpp │ ├── B.cpp │ ├── C.cpp │ ├── D.cpp │ ├── F.cpp │ ├── G.cpp │ ├── H.cpp │ ├── K.cpp │ ├── L.cpp │ ├── N.cpp │ ├── Q.cpp │ └── README.md ├── binarysearch ├── 860.cpp ├── 861.cpp ├── Binary Search Tree Typo.py ├── Count Exact Sum.cpp ├── Create Palindrome After Deleting at Most K Characters.py ├── Double String Concatenation.cpp ├── Edges that Disconnect the Graph.cpp ├── Largest K-Divisible Subsequence.cpp ├── Largest Square Matrix with Same Value.cpp ├── Level Order Traversal.py ├── Lowest Sum of Pair Larger than Target.cpp ├── Minimum Spanning Tree.cpp ├── Moo.cpp ├── Shipping and Receiving.cpp ├── Short Circuit.cpp ├── Stacks.py └── Valid State of List.cpp ├── codechef ├── ALR20B.cpp ├── And_operation.cpp ├── BURARRAY.cpp ├── CATS.cpp ├── CCDSAP │ └── 3 │ │ ├── Horrible_queries.cpp │ │ └── LITE.cpp ├── CDRN04.cpp ├── CHEFEXQ.cpp ├── CHGORAM.cpp ├── CIRMERGE.cpp ├── COW3D.cpp ├── CW1003.cpp ├── DBYZ15F.py ├── DSALearningSearies │ ├── EURON.py │ ├── QHOUSE.py │ └── STACKS.py ├── ENCODING.py ├── HOLY.cpp ├── INTRPATH.cpp ├── IPCTRAIN.cpp ├── KAN13C.cpp ├── KETEKI2D.cpp ├── KINGCON.cpp ├── MAGICSTR.cpp ├── MAXOR.cpp ├── ONEKING.cpp ├── PEC003.cpp ├── PEC005.cpp ├── PRMQ.cpp ├── RNDRND.cpp ├── RRATING.cpp ├── SEGDIR.cpp ├── STRMCH.cpp ├── SUBARR.cpp ├── TAAND.cpp ├── TESCJ05.cpp ├── TSECJ05.cpp ├── TSECJ05.py ├── WTBTR.cpp └── ZOMACV.cpp ├── codeforces ├── Alyona_and_the_Tree.cpp ├── Barcode.cpp ├── BeautifulGraph.cpp ├── Bicolorings.cpp ├── BornThisWay.cpp ├── ByElevatorOrStairs.cpp ├── Compatible_Numbers.cpp ├── DevuAndHisBrother.cpp ├── DimaAndBacteria.cpp ├── DistanceInTree.cpp ├── EnemyIsWeak.cpp ├── EternalVictory.cpp ├── GoodSubsequences.cpp ├── LevkoAndArray.cpp ├── MexMaximizing.cpp ├── MinimumArray.py ├── NewReform.cpp ├── PaintingFence.cpp ├── PermuteDigits.cpp ├── Present.cpp ├── QuantityOfStrings.cpp ├── RestoreGraph.cpp ├── RestorerDistance.cpp ├── RidingInALift.cpp ├── RoadsInBerland.cpp ├── TreeQueries.cpp ├── UnbearableControversyOfBeing.cpp ├── Vowels.cpp ├── WorkingOut.cpp └── contests │ ├── 77 │ ├── README.md │ ├── a.md │ ├── b.md │ ├── c.md │ └── d.md │ ├── 494 │ ├── README.md │ ├── a.md │ ├── b.md │ ├── c.md │ ├── d.md │ └── e.md │ ├── 629 │ ├── README.md │ ├── a.md │ ├── b.md │ ├── c.md │ └── d.md │ └── 632 │ └── README.md ├── codewars ├── 1. Find all active students.sql ├── Duplicate Encoder.js ├── Easy SQL: Absolute Value and Log to Base.sql ├── Easy SQL: Cube Root and Natural Log.sql ├── Easy SQL: Rounding Decimals.sql ├── GROCERY STORE: Logistic Optimisation.sql ├── GROCERY STORE: Support Local Products.sql ├── Relational division: Find all movies two actors cast in together.sql ├── SQL Basics: Simple EXISTS.sql ├── SQL Basics: Simple HAVING.sql ├── SQL Basics: Simple IN.sql ├── SQL Basics: Simple JOIN.sql ├── SQL Basics: Simple WHERE and ORDER BY.sql ├── SQL Basics: Simple WITH.sql ├── SQL: Right and Left.sql └── Stop gninnipS My sdroW!.js ├── csAcademy └── DivisorClique.cpp ├── geeksforgeeks ├── 0-1knapsackProblem.cpp ├── ActivitySelection.cpp ├── Add1ToANumberRepresentedAsLinkedList.py ├── AddAllGreaterValuesToEveryNodeInABST.cpp ├── AddTwoNumbersRepresentedByLinkedLists.cpp ├── AncestorsInBinaryTree.cpp ├── BFSOfGraph.cpp ├── BinaryTreeToDLL.cpp ├── CheckForBST.cpp ├── CoinChange.cpp ├── CountNumberOfHops.cpp ├── CountSubsequencesOfType.cpp ├── DFSOfGraph.cpp ├── DeleteANodeFromBST.cpp ├── DeleteMiddleOfLinkedList.cpp ├── DetectCycleInADirectedGraph.cpp ├── DetectCycleInAnUndirectedGraph.cpp ├── DetectLoopInLinkedList.cpp ├── DetermineIfTwoTreesAreIdentical.py ├── ExpressionTree.cpp ├── FindDuplicatesInAnArray.cpp ├── FindMedianInAStream.cpp ├── FindNumberOfTimesAStringOccursAsASubsequence.cpp ├── FindPairWithGivenTargetInBST.cpp ├── GetMinAtPop.cpp ├── GetMinimumElementFromStack.cpp ├── HeapSort.cpp ├── ImplementStackUsingLinkedList.cpp ├── ImplementingDijkstra.cpp ├── IncreasingSubSequence.cpp ├── InorderTraversal.cpp ├── InversionOfArray.cpp ├── KadanesAlgorithm.cpp ├── KthLargestElementInAStream.cpp ├── KthSmallestElementInBST.cpp ├── LargestNumberFormedFromAnArray.cpp ├── LeftViewOfBinaryTree.cpp ├── LengthOfTheLongestSubstring.cpp ├── LevelOrderTraversalInSpiralForm.cpp ├── LinkedListOfStringsFormsAPalindrome.cpp ├── LongestCommonPrefixInAnArray.cpp ├── LongestCommonSubsequence.cpp ├── LongestCommonSubstring.cpp ├── LongestIncreasingSubsequence.cpp ├── LongestKUniqueCharacterSubstring.cpp ├── LongestPalindromeInAString.cpp ├── LongestPalindromicSubsequence.cpp ├── LongestPrefixSuffix.cpp ├── LowestCommonAncestorInABST.cpp ├── LowestCommonAncestorInABinaryTree.cpp ├── MaxLengthChain.cpp ├── MaximizeTheCutSegments.cpp ├── MaximumIntervalsOverlap.cpp ├── MaximumWidthOfTree.cpp ├── MergeKSortedArrays.cpp ├── MergeSort.cpp ├── MergeWithoutExtraSpace.cpp ├── MinDistanceBetweenTwoGivenNodesOfABinaryTree.cpp ├── MinimumNumberOfCoins.cpp ├── MinimumOperations.cpp ├── MinimunNumberOfJumps.cpp ├── MirrorTree.cpp ├── NMeetingsInOneRoom.cpp ├── NegativeWeightCycle.cpp ├── NegativeWeightCycle.py ├── NextLargerElement.cpp ├── NthNodeFromEndOfLinkedList.cpp ├── NumberOfUniquePaths.cpp ├── NutsAndBoltsProblem.cpp ├── PathInMatrix.cpp ├── PermutationsOfAGivenString.cpp ├── PredecessorAndSuccessor.cpp ├── PreorderToPostorder.cpp ├── PreorderTraversal.cpp ├── PreorderTraversalAndBST.cpp ├── PrintBSTElementsInGivenRange.cpp ├── QuickSort.cpp ├── ReachAGivenScore.cpp ├── RearrangeAnArrayWithO(1)ExtraSpace.cpp ├── RearrangeArrayAlternately.cpp ├── RemoveDuplicateElementFromSortedLinkedList.cpp ├── RemoveLoopInLinkedList.cpp ├── ReverseWordsInAGivenString.cpp ├── RotateALinkedList.cpp ├── RotateDoublyLinkedList.cpp ├── SearchInARotatedArray.cpp ├── ShortestCommonSupersequence.cpp ├── SkipTheWork.cpp ├── SpirallyTraversingAMatrix.cpp ├── SubarrayWithGivenSum.cpp ├── SumOfDependenciesInAGraph.cpp ├── SumTree.cpp ├── TopologicalSort.cpp ├── TrappingRainWater.cpp ├── TrieInsertAndSearch.cpp ├── UnitAreaOfLargestRegionOf1s.cpp └── WordBreak.cpp ├── hacker_rank ├── ConnectedComponent.cpp ├── ConnectedComponent.py ├── DEQUE.cpp ├── MaxArraySum.cpp ├── NewYearChaos.cpp ├── SpecialSubtree.cpp ├── SpecialSubtree.py ├── TimeDelta.py └── sherlock_and_cost.cpp ├── interviewbit ├── Hotel Reviews.cpp ├── LongestPalindromicSubstring.cpp ├── Path To Given Node.cpp ├── Remove Duplicates from Sorted Array II.cpp ├── Remove Duplicates from Sorted Array.cpp └── Remove Half Nodes.cpp ├── leetcode ├── 1.py ├── 100.py ├── 1002.java ├── 1004.cpp ├── 1008.py ├── 101.cpp ├── 1014.py ├── 102.py ├── 1022.py ├── 1025.py ├── 1028.cpp ├── 1034.py ├── 1038.py ├── 104.java ├── 104.py ├── 1046.py ├── 1048.cpp ├── 105.cpp ├── 1052.cpp ├── 109.py ├── 1094.cpp ├── 11.cpp ├── 1130.cpp ├── 1140.cpp ├── 1143.py ├── 116.cpp ├── 120.py ├── 121.py ├── 1221.cpp ├── 1239.cpp ├── 124.py ├── 1248.cpp ├── 125.py ├── 1254.cpp ├── 1255.cpp ├── 127.cpp ├── 128.cpp ├── 1281.js ├── 1282.py ├── 1284.cpp ├── 1288.cpp ├── 130.py ├── 1310.cpp ├── 1312.cpp ├── 1325.cpp ├── 133.cpp ├── 1338.py ├── 1354.py ├── 1359.cpp ├── 138.cpp ├── 1387.cpp ├── 1389.js ├── 139.cpp ├── 14.py ├── 1402.cpp ├── 1409.py ├── 141.py ├── 1411.cpp ├── 1416.py ├── 143.py ├── 1431.js ├── 1436.py ├── 1448.cpp ├── 1456.cpp ├── 146.cpp ├── 1463.cpp ├── 148.cpp ├── 151.py ├── 152.cpp ├── 1525.cpp ├── 155.py ├── 1557.cpp ├── 1578.py ├── 1584.py ├── 160.cpp ├── 1642.cpp ├── 1657.py ├── 1695.py ├── 1696.py ├── 17.py ├── 1702.py ├── 1721.py ├── 173.cpp ├── 1734.py ├── 175.sql ├── 176.sql ├── 179.cpp ├── 182.sql ├── 183.sql ├── 19.cpp ├── 191.py ├── 1944.py ├── 1975.py ├── 198.py ├── 199.cpp ├── 2.cpp ├── 2.py ├── 20.py ├── 200.py ├── 2012.py ├── 202.py ├── 204.py ├── 207.cpp ├── 209.cpp ├── 21.py ├── 22.py ├── 23.cpp ├── 230.py ├── 2301.py ├── 2302.py ├── 235.py ├── 236.cpp ├── 237.py ├── 239.cpp ├── 239.py ├── 2416.py ├── 26.cpp ├── 289.cpp ├── 295.cpp ├── 300.py ├── 303.py ├── 304.py ├── 30DayChallenge │ ├── 1 │ │ └── solution1.md │ ├── 2 │ │ └── solution.md │ ├── 3 │ │ └── solution.md │ ├── 4 │ │ └── solution.md │ ├── 5 │ │ └── solution.md │ ├── 6 │ │ └── solution.md │ ├── 7 │ │ └── solution.md │ ├── 8 │ │ └── solution.md │ ├── 9 │ │ └── solution.md │ ├── 10 │ │ └── solution.md │ ├── 11 │ │ └── solution.md │ ├── 12 │ │ └── solution.md │ ├── 13 │ │ └── solution.md │ ├── 14 │ │ └── solution1.md │ ├── 15 │ │ └── solution.md │ ├── 16 │ │ └── solution.md │ ├── 17 │ │ └── solution.md │ ├── 18 │ │ └── solution.md │ ├── 19 │ │ └── solution.md │ ├── 20 │ │ └── solution.md │ ├── 21 │ │ └── solution.md │ ├── 22 │ │ └── solution.md │ ├── 23 │ │ └── solution.md │ ├── 24 │ │ └── solution.md │ ├── 25 │ │ └── solution.md │ ├── 26 │ │ └── solution.md │ ├── 27 │ │ └── solution.md │ ├── 28 │ │ └── solution.md │ ├── 29 │ │ └── solution.md │ └── 30 │ │ └── solution.md ├── 31.py ├── 312.cpp ├── 322.cpp ├── 334.cpp ├── 337.cpp ├── 338.cpp ├── 341.cpp ├── 343.cpp ├── 36.py ├── 373.py ├── 376.cpp ├── 380.py ├── 39.cpp ├── 392.py ├── 41.cpp ├── 416.py ├── 42.cpp ├── 43.cpp ├── 435.cpp ├── 442.cpp ├── 445.py ├── 452.cpp ├── 454.cpp ├── 459.cpp ├── 46.py ├── 48.py ├── 485.cpp ├── 493.py ├── 5.cpp ├── 51.cpp ├── 516.cpp ├── 53.py ├── 54.cpp ├── 547.cpp ├── 55.cpp ├── 556.cpp ├── 56.cpp ├── 57.py ├── 572.py ├── 595.sql ├── 6.cpp ├── 60.cpp ├── 62.py ├── 623.cpp ├── 647.cpp ├── 654.py ├── 657.py ├── 658.py ├── 669.cpp ├── 673.cpp ├── 70.py ├── 72.py ├── 736.py ├── 738.py ├── 739.cpp ├── 746.py ├── 75.cpp ├── 76.cpp ├── 763.cpp ├── 771.js ├── 78.py ├── 785.cpp ├── 787.cpp ├── 791.cpp ├── 802.cpp ├── 813.cpp ├── 838.cpp ├── 84.cpp ├── 841.cpp ├── 853.py ├── 856.py ├── 86.cpp ├── 877.py ├── 88.cpp ├── 895.cpp ├── 895.py ├── 901.py ├── 907.py ├── 91.py ├── 921.cpp ├── 931.cpp ├── 938.py ├── 94.py ├── 946.cpp ├── 950.cpp ├── 955.cpp ├── 96.cpp ├── 97.cpp ├── 98.cpp ├── 983.py ├── 986.cpp ├── 99.py ├── AugChallenge │ ├── 1 │ │ └── solution.md │ └── 30 │ │ └── solution.md ├── Blind_75_Leetcode_Questions.md ├── FebChallenge2021 │ ├── 1 │ │ └── solution.md │ ├── 2 │ │ └── solution.md │ ├── 7 │ │ └── solution.md │ ├── 9 │ │ └── solution.md │ ├── 13 │ │ └── solution.md │ ├── 17 │ │ └── solution.md │ ├── 18 │ │ └── solution.md │ ├── 19 │ │ └── solution.md │ └── 23 │ │ └── solution.md ├── JanChallenge2021 │ ├── 1 │ │ └── solution.md │ ├── 2 │ │ └── solution.md │ ├── 3 │ │ └── solution.md │ ├── 4 │ │ └── solution.md │ ├── 5 │ │ └── solution.md │ ├── 6 │ │ └── solution.md │ ├── 7 │ │ └── solution.md │ ├── 8 │ │ └── solution.md │ ├── 9 │ │ └── solution.md │ ├── 12 │ │ └── solution.md │ ├── 13 │ │ └── solution.md │ ├── 14 │ │ └── solution.md │ ├── 15 │ │ └── solution.md │ ├── 19 │ │ └── solution.md │ ├── 20 │ │ └── solution.md │ ├── 21 │ │ └── solution.md │ ├── 22 │ │ └── solution.md │ ├── 23 │ │ └── solution.md │ ├── 25 │ │ └── solution.md │ └── 31 │ │ └── solution.md ├── JulyChallenge │ ├── 1 │ │ └── solution.md │ ├── 2 │ │ └── solution.md │ ├── 3 │ │ └── solution.md │ ├── 4 │ │ └── solution.md │ ├── 5 │ │ └── solution.md │ ├── 6 │ │ └── solution.md │ ├── 8 │ │ └── solution.md │ ├── 19 │ │ └── solution.md │ ├── 20 │ │ └── solution.md │ ├── 21 │ │ └── solution.md │ ├── 22 │ │ └── solution.md │ └── 27 │ │ └── solution.md ├── JuneChallenge │ ├── 1 │ │ └── solution.md │ ├── 2 │ │ └── solution.md │ ├── 3 │ │ └── solution.md │ ├── 4 │ │ └── solution.md │ ├── 7 │ │ └── solution.md │ ├── 8 │ │ └── solution.md │ ├── 9 │ │ └── solution.md │ ├── 10 │ │ └── solution.md │ ├── 11 │ │ └── solution.md │ ├── 13 │ │ └── solution.md │ ├── 14 │ │ └── solution.md │ ├── 15 │ │ └── solution.md │ ├── 17 │ │ └── solution.md │ ├── 18 │ │ └── solution.md │ ├── 23 │ │ └── solution.md │ ├── 24 │ │ └── solution.md │ ├── 26 │ │ └── solution.md │ ├── 27 │ │ └── solution.md │ └── 29 │ │ └── solution.md ├── MayChallenge │ ├── 1 │ │ └── solution.md │ ├── 2 │ │ └── solution.md │ ├── 3 │ │ └── solution.md │ ├── 4 │ │ └── solution.md │ ├── 5 │ │ └── solution.md │ ├── 6 │ │ └── solution.md │ ├── 7 │ │ └── solution.md │ ├── 8 │ │ └── solution.md │ ├── 9 │ │ └── solution.md │ ├── 10 │ │ └── solution.md │ ├── 11 │ │ └── solution.md │ ├── 12 │ │ └── solution.md │ ├── 13 │ │ └── solution.md │ ├── 14 │ │ └── solution.md │ ├── 15 │ │ └── solution.md │ ├── 16 │ │ └── solution.md │ ├── 18 │ │ └── solution.md │ ├── 19 │ │ └── solution.md │ ├── 20 │ │ └── solution.md │ ├── 21 │ │ └── solution.md │ ├── 22 │ │ └── solution.md │ ├── 23 │ │ └── solution.md │ ├── 24 │ │ └── solution.md │ ├── 25 │ │ └── solution.md │ ├── 26 │ │ └── solution.md │ ├── 27 │ │ └── solution.md │ ├── 28 │ │ └── solution.md │ ├── 29 │ │ └── solution.md │ └── 31 │ │ └── solution.md └── contests │ ├── Biweekly21 │ ├── 1370.md │ ├── 1371.md │ ├── 1372.md │ ├── 1373.md │ └── README.md │ ├── Biweekly25 │ ├── 1431.md │ ├── 1432.md │ ├── 1433.md │ ├── 1434.md │ └── README.md │ ├── Weekly148 │ ├── 1144.md │ ├── 1145.md │ ├── 1146.md │ ├── 1147.md │ └── README.md │ ├── Weekly149 │ ├── 1154.md │ ├── 1155.md │ ├── 1156.md │ ├── 1157.md │ └── README.md │ ├── Weekly150 │ ├── 1160.md │ ├── 1161.md │ ├── 1162.md │ ├── 1163.md │ └── README.md │ ├── Weekly183 │ ├── 1403.md │ ├── 1404.md │ ├── 1405.md │ ├── 1406.md │ └── README.md │ ├── Weekly84 │ ├── 832.md │ ├── 833.md │ ├── 834.md │ ├── 835.md │ └── README.md │ ├── Weekly87 │ ├── 844.md │ ├── 845.md │ ├── 846.md │ ├── 847.md │ └── README.md │ ├── Weekly89 │ ├── 852.md │ ├── 853.md │ ├── 854.md │ ├── 855.md │ └── README.md │ └── Weekly91 │ ├── 860.md │ ├── 861.md │ ├── 862.md │ ├── 863.md │ └── README.md ├── lintcode ├── 1786.py ├── 1913.sql ├── 1920.sql ├── 1921.sql ├── 1923.sql ├── 307.py └── 920.py ├── place └── reference_materials.md ├── python_programming_exercises ├── basic_implementation │ ├── README.md │ ├── ques10.py │ ├── ques11.py │ ├── ques13.py │ ├── ques14.py │ ├── ques15.py │ ├── ques2.py │ ├── ques3.py │ ├── ques4.py │ ├── ques6.py │ ├── ques7.py │ └── ques9.py └── online_judge_solutions │ ├── AngryProfessor.py │ ├── BeautifulDaysAtTheMovies.py │ ├── DiagonalDifference.py │ ├── FACTRL2.py │ ├── FLOW001.py │ ├── FLOW002.py │ ├── FLOW006.py │ ├── GOOGOL05.py │ ├── HamiltonianAndLagrangian.py │ ├── INTEST.py │ ├── LongestPalindrome.py │ ├── MinimumOperations.py │ ├── MonkAndWelcomeProblem.py │ ├── NeutralisationOfCharges.py │ ├── PolygonPossibility.py │ ├── ReduceFunction.py │ ├── START01.py │ ├── SequenceEquation.py │ ├── TSORT.py │ └── UtopianTree.py ├── spoj ├── Aggressive_cows.cpp ├── CLOPPAIR.cpp ├── DQUERY.cpp ├── EDIST.cpp ├── Elevator_trouble.cpp ├── FARIDA.cpp ├── Fashion_Shows.cpp ├── Friends_of_friends.cpp ├── GIVEAWAY.cpp ├── Horrible_queries.cpp ├── KQUERYO_merge_sort_tree.cpp ├── LATGACH3.cpp ├── LITE.cpp ├── LPS.cpp ├── Minimum_Knight_moves.cpp ├── NAJPF_Pattern_Find.cpp ├── POLYMUL.cpp ├── PT07Y.cpp ├── PT07Z.cpp ├── Permutations.cpp ├── Prime_Path.cpp ├── SARRAY.cpp ├── SUBLEX.cpp ├── SUBMERGE.cpp ├── SUBST1.cpp ├── The_Shortest_Path.cpp ├── Tropological_Sorting.cpp └── [sqrt_decomp_method]GIVEAWAY.cpp ├── timus ├── 1297.cpp ├── 1423.cpp ├── 1590(using_DA).cpp └── 1590(using_suffix_array).cpp ├── todo.md ├── topcoder ├── Alliteration.py ├── Arrfix.cpp ├── Books.cpp ├── CuttingBitString.py ├── DivFreed2.cpp ├── EllysCheckers.cpp ├── Fibonacci.cpp ├── HandsShaking.cpp ├── MutaliskEasy.cpp ├── SuperSum.cpp ├── TheLotteryBothDivs.cpp ├── ThePalindrome.cpp └── ZigZag.cpp └── uva_solutions ├── 10305.cpp ├── 10684.cpp ├── 11790.cpp ├── 11838.cpp ├── 423.cpp ├── 459.cpp └── 507.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | /lld/*/.gradle/ 2 | /lld/*/build/ 3 | /lld/*/.idea/ 4 | .idea 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### This repo is ment for sharing ```small portion``` of my problem solving works on various online platforms. 2 | 3 |

4 | ![merged](https://user-images.githubusercontent.com/46635452/99353539-bd568180-28ca-11eb-8628-8d0c44441bc0.jpg) 5 | 6 | -------------------------------------------------------------------------------- /editor_snippets/README.md: -------------------------------------------------------------------------------- 1 | These are some of my code-templates. You can create your own using [this](https://github.com/pawelgrzybek/snippet-generator) for your favourite editor. 2 | -------------------------------------------------------------------------------- /editor_snippets/sublime_snippets/README.md: -------------------------------------------------------------------------------- 1 | Place this directory in : 2 | 3 | ```/home/harsh/.config/sublime-text-3/Packages/User/``` 4 | repalce ```harsh``` with your ```username``` and type ```init, Debug, Number``` in any cpp file and hit enter to see magic. Note these work only with cpp files due to ``` .... ``` line in each snippet. 5 | 6 | Alternatively you can go to ```Preferences -> Browse Packages -> User``` 7 | (I hope a directory named ```User``` exists there) 8 | 9 | ### Demo: 10 | ![](sublime-snippet.gif) -------------------------------------------------------------------------------- /editor_snippets/sublime_snippets/sublime-snippet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/editor_snippets/sublime_snippets/sublime-snippet.gif -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | } 4 | 5 | group = "org.example" 6 | version = "1.0-SNAPSHOT" 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | compileOnly("org.projectlombok:lombok:1.18.30") 14 | annotationProcessor("org.projectlombok:lombok:1.18.30") 15 | testAnnotationProcessor("org.projectlombok:lombok:1.18.30") 16 | testImplementation(platform("org.junit:junit-bom:5.10.0")) 17 | testImplementation("org.junit.jupiter:junit-jupiter") 18 | } 19 | 20 | tasks.test { 21 | useJUnitPlatform() 22 | } -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/coffeeVendingMachine/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Feb 26 19:42:25 IST 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "coffeeVendingMachine" 2 | 3 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/Observer.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine; 2 | 3 | import org.example.coffeeVendingMachine.ingredient.Ingredient; 4 | import org.example.coffeeVendingMachine.ingredient.IngredientType; 5 | 6 | public interface Observer { 7 | public void onIngredientUpdate(IngredientType ingredientType, int quantity); 8 | } 9 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/coffee/Coffee.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.coffee; 2 | 3 | import lombok.Getter; 4 | import org.example.coffeeVendingMachine.ingredient.IngredientInventory; 5 | 6 | @Getter 7 | public abstract class Coffee { 8 | private final CoffeeType coffeeType; 9 | private int price; 10 | private final IngredientInventory ingredientInventory; 11 | 12 | protected Coffee(CoffeeType coffeeType, int price, IngredientInventory ingredientInventory) { 13 | this.coffeeType = coffeeType; 14 | this.price = price; 15 | this.ingredientInventory = ingredientInventory; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/coffee/CoffeeManager.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.coffee; 2 | 3 | import lombok.AllArgsConstructor; 4 | 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | @AllArgsConstructor 9 | public class CoffeeManager { 10 | List coffeeList; 11 | 12 | public boolean isAvailable(CoffeeType coffeeType) { 13 | return coffeeList.stream().anyMatch(coffee -> coffee.getCoffeeType().equals(coffeeType)); 14 | } 15 | 16 | public Optional getCoffee(CoffeeType coffeeType) { 17 | return coffeeList.stream().filter(coffee -> coffee.getCoffeeType().equals(coffeeType)).findFirst(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/coffee/CoffeeType.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.coffee; 2 | 3 | public enum CoffeeType { 4 | ESPRESSO, 5 | LATTE, 6 | CAPPUCCINO 7 | } 8 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/ingredient/FixedQuantityIngredient.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.ingredient; 2 | 3 | public class FixedQuantityIngredient extends Ingredient { 4 | public FixedQuantityIngredient(IngredientType ingredientType, int quantity) { 5 | super(ingredientType, quantity); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/ingredient/Ingredient.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.ingredient; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public abstract class Ingredient { 7 | private final IngredientType ingredientType; 8 | public int quantity; 9 | 10 | public Ingredient(IngredientType ingredientType, int quantity) { 11 | this.ingredientType = ingredientType; 12 | this.quantity = quantity; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/ingredient/IngredientType.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.ingredient; 2 | 3 | public enum IngredientType { 4 | SUGAR, 5 | COFFEE 6 | } 7 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/ingredient/QuantityUpdatableIngredient.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.ingredient; 2 | 3 | public class QuantityUpdatableIngredient extends Ingredient { 4 | public QuantityUpdatableIngredient(IngredientType ingredientType, int quantity) { 5 | super(ingredientType, quantity); 6 | } 7 | 8 | public void setQuantity(int quantity) { 9 | this.quantity = quantity; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /lld/coffeeVendingMachine/src/main/java/org/example/coffeeVendingMachine/payment/Payment.java: -------------------------------------------------------------------------------- 1 | package org.example.coffeeVendingMachine.payment; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @AllArgsConstructor 8 | public class Payment { 9 | private final int amount; 10 | } 11 | -------------------------------------------------------------------------------- /lld/flipCache/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | id("application") 4 | } 5 | 6 | group = "org.example" 7 | version = "1.0-SNAPSHOT" 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | testImplementation(platform("org.junit:junit-bom:5.10.0")) 15 | testImplementation("org.junit.jupiter:junit-jupiter") 16 | } 17 | 18 | application { 19 | mainClass.set("com.example.Main") // Change to your actual main class 20 | } 21 | 22 | tasks.jar { 23 | manifest { 24 | attributes["Main-Class"] = "com.example.Main" // Change to your actual main class 25 | } 26 | } 27 | 28 | tasks.test { 29 | useJUnitPlatform() 30 | } -------------------------------------------------------------------------------- /lld/flipCache/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/flipCache/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /lld/flipCache/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Feb 23 00:59:25 IST 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /lld/flipCache/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "flipCache" 2 | 3 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/adaptor/outbound/CacheHitMetricCollector.java: -------------------------------------------------------------------------------- 1 | package com.example.adaptor.outbound; 2 | 3 | import com.example.application.models.Event; 4 | import com.example.application.ports.outbound.CacheHook; 5 | 6 | public class CacheHitMetricCollector implements CacheHook { 7 | private int cacheHitCount = 0; 8 | private final K key; 9 | 10 | public CacheHitMetricCollector(K key) { 11 | this.key = key; 12 | } 13 | 14 | public int getCacheHitCount() { 15 | return cacheHitCount; 16 | } 17 | 18 | @Override 19 | public void onEvent(Event event, K key, V value) { 20 | if (event == Event.HIT && key.equals(this.key)) { 21 | cacheHitCount += 1; 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/models/Event.java: -------------------------------------------------------------------------------- 1 | package com.example.application.models; 2 | 3 | public enum Event { 4 | HIT, 5 | MISS, 6 | CREATE, 7 | EVICT 8 | } 9 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/ports/inbound/GetCache.java: -------------------------------------------------------------------------------- 1 | package com.example.application.ports.inbound; 2 | 3 | public interface GetCache { 4 | public V getCache(K key); 5 | } 6 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/ports/inbound/SetCache.java: -------------------------------------------------------------------------------- 1 | package com.example.application.ports.inbound; 2 | 3 | public interface SetCache { 4 | public V setCache(K key, V value); 5 | } 6 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/ports/outbound/CacheHook.java: -------------------------------------------------------------------------------- 1 | package com.example.application.ports.outbound; 2 | 3 | import com.example.application.models.Event; 4 | 5 | public interface CacheHook { 6 | void onEvent(Event event, K key, V value); 7 | } 8 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/ports/outbound/DataSource.java: -------------------------------------------------------------------------------- 1 | package com.example.application.ports.outbound; 2 | 3 | public interface DataSource { 4 | public V persist(K key, V value); 5 | public V retrieve(K key); 6 | public V remove(K key); 7 | public boolean contains(K key); 8 | } 9 | -------------------------------------------------------------------------------- /lld/flipCache/src/main/java/com/example/application/ports/outbound/EvictionPolicy.java: -------------------------------------------------------------------------------- 1 | package com.example.application.ports.outbound; 2 | 3 | public interface EvictionPolicy { 4 | public K evictionCandidate(); 5 | public void keyAccessed(K key); 6 | public void keyRemoved(K key); 7 | public void keyAdded(K key); 8 | public void clear(); 9 | } 10 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/checksums/checksums.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/checksums/checksums.lock -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/checksums/md5-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/checksums/md5-checksums.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/checksums/sha1-checksums.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/checksums/sha1-checksums.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/dependencies-accessors/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/dependencies-accessors/gc.properties -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/executionHistory/executionHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/executionHistory/executionHistory.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/executionHistory/executionHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/executionHistory/executionHistory.lock -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/fileHashes/resourceHashesCache.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/fileHashes/resourceHashesCache.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/8.10/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/8.10/gc.properties -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 23 20:54:43 IST 2025 2 | gradle.version=8.10 3 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/file-system.probe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/file-system.probe -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/.gradle/vcs-1/gc.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/.gradle/vcs-1/gc.properties -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | } 4 | 5 | group = "org.example" 6 | version = "1.0-SNAPSHOT" 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | compileOnly("org.projectlombok:lombok:1.18.36") 14 | annotationProcessor("org.projectlombok:lombok:1.18.36") 15 | testImplementation(platform("org.junit:junit-bom:5.10.0")) 16 | testImplementation("org.junit.jupiter:junit-jupiter") 17 | } 18 | 19 | tasks.test { 20 | useJUnitPlatform() 21 | } -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/hospitalManagementSystem/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 23 20:48:39 IST 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "hospitalManagementSystem" 2 | 3 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/dto/Appointment.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | @Data 7 | @AllArgsConstructor 8 | public class Appointment { 9 | private Doctor doctor; 10 | private Patient patient; 11 | private Integer startTime; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/dto/DoctorRankingStrategy.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.dto; 2 | 3 | import java.util.List; 4 | 5 | public interface DoctorRankingStrategy { 6 | public List rankDoctors(List doctors); 7 | } 8 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/dto/DoctorSpeciality.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.dto; 2 | 3 | public enum DoctorSpeciality { 4 | CARDIOLOGIST, 5 | DERMATOLOGIST, 6 | ORTHOPEDIC, 7 | GENERAL_PHYSICIAN 8 | } 9 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/dto/Patient.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.dto; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | 7 | @Getter 8 | @AllArgsConstructor 9 | public class Patient { 10 | String id; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/dto/TimeDuration.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.dto; 2 | 3 | public enum TimeDuration { 4 | MINS30 5 | } 6 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/ports/BookAppointment.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.ports; 2 | 3 | import org.example.domain.dto.Doctor; 4 | import org.example.domain.dto.Patient; 5 | 6 | public interface BookAppointment { 7 | public boolean bookAppointment(Patient patient, Doctor doctor, Integer startTime); 8 | } 9 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/ports/CancelAppointment.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.ports; 2 | 3 | import org.example.domain.dto.Doctor; 4 | import org.example.domain.dto.Patient; 5 | 6 | public interface CancelAppointment { 7 | public boolean cancelAppointment(Patient patient, Doctor doctor, Integer startTime); 8 | } 9 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/ports/RegisterDoctor.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.ports; 2 | 3 | import org.example.domain.dto.Doctor; 4 | 5 | public interface RegisterDoctor { 6 | public boolean registerDoctor(Doctor doctor); 7 | } 8 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/ports/SearchSlotsBasedOnSpeciality.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.ports; 2 | 3 | import org.example.domain.dto.Doctor; 4 | import org.example.domain.dto.DoctorRankingStrategy; 5 | import org.example.domain.dto.DoctorSpeciality; 6 | 7 | import java.util.ArrayList; 8 | 9 | public interface SearchSlotsBasedOnSpeciality { 10 | public ArrayList searchSlotsBasedOnSpeciality(DoctorSpeciality speciality, DoctorRankingStrategy strategy); 11 | } 12 | -------------------------------------------------------------------------------- /lld/hospitalManagementSystem/src/main/java/org/example/domain/service/DefaultRankingStrategy.java: -------------------------------------------------------------------------------- 1 | package org.example.domain.service; 2 | 3 | import org.example.domain.dto.Doctor; 4 | import org.example.domain.dto.DoctorRankingStrategy; 5 | 6 | import java.util.List; 7 | 8 | public class DefaultRankingStrategy implements DoctorRankingStrategy { 9 | @Override 10 | public List rankDoctors(List doctors) { 11 | return doctors; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/Readme.md: -------------------------------------------------------------------------------- 1 | Command, Invoker, Receiver 2 | 3 | Command contains the Receiver and the action to be performed on the Receiver. Invoker is the one who invokes the command. Receiver is the one who performs the action. 4 | Here LightBulb is the Receiver, TurnOnCommand is the Command and Remote is the Invoker. 5 | 6 | Command Pattern is most helpful in adding Undo Redo Functionality. -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | } 4 | 5 | group = "org.example" 6 | version = "1.0-SNAPSHOT" 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | testImplementation(platform("org.junit:junit-bom:5.10.0")) 14 | testImplementation("org.junit.jupiter:junit-jupiter") 15 | } 16 | 17 | tasks.test { 18 | useJUnitPlatform() 19 | } -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/lld/lightBulbCommandPattern/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Feb 24 14:40:26 IST 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "lightBulbCommandPattern" 2 | 3 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/Main.java: -------------------------------------------------------------------------------- 1 | package org.example; 2 | 3 | import org.example.lightBulb.LightBulb; 4 | import org.example.lightBulb.LightBulbTurnOnCommand; 5 | import org.example.lightBulb.Remote; 6 | import org.example.lightBulb.event.LightBulbTurnOnMetric; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | Remote remote = new Remote(); 11 | LightBulb lightBulb = new LightBulb(); 12 | LightBulbTurnOnCommand lightBulbTurnOnCommand = new LightBulbTurnOnCommand(lightBulb); 13 | LightBulbTurnOnMetric lightBulbTurnOnMetric = new LightBulbTurnOnMetric(); 14 | lightBulbTurnOnCommand.addEventHook(lightBulbTurnOnMetric); 15 | 16 | remote.addCommand(lightBulbTurnOnCommand); 17 | remote.pressButton(); 18 | remote.pressUndo(); 19 | } 20 | } -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/Command.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb; 2 | 3 | public interface Command { 4 | public void execute(); 5 | public void undo(); 6 | public void redo(); 7 | } 8 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/LightBulbTurnOffCommand.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb; 2 | 3 | import org.example.lightBulb.event.EventHook; 4 | 5 | public class LightBulbTurnOffCommand implements Command{ 6 | LightBulb lightBulb; 7 | 8 | public LightBulbTurnOffCommand(LightBulb lightBulb) { 9 | this.lightBulb = lightBulb; 10 | } 11 | 12 | public void addEventHook(EventHook eventHook) { 13 | lightBulb.addEventHook(eventHook); 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | lightBulb.turnOff(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | lightBulb.turnOn(); 24 | } 25 | 26 | @Override 27 | public void redo() { 28 | execute(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/LightBulbTurnOnCommand.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb; 2 | 3 | import org.example.lightBulb.event.EventHook; 4 | 5 | public class LightBulbTurnOnCommand implements Command{ 6 | LightBulb lightBulb; 7 | 8 | public LightBulbTurnOnCommand(LightBulb lightBulb) { 9 | this.lightBulb = lightBulb; 10 | } 11 | 12 | public void addEventHook(EventHook eventHook) { 13 | lightBulb.addEventHook(eventHook); 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | lightBulb.turnOn(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | lightBulb.turnOff(); 24 | } 25 | 26 | @Override 27 | public void redo() { 28 | execute(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/Remote.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb; 2 | 3 | import java.util.Stack; 4 | 5 | public class Remote { 6 | Stack commands = new Stack<>(); 7 | 8 | public void addCommand(Command command) { 9 | this.commands.add(command); 10 | } 11 | 12 | public void pressButton() { 13 | this.commands.getFirst().execute(); 14 | } 15 | 16 | public void pressUndo() { 17 | this.commands.getFirst().undo(); 18 | } 19 | 20 | public void pressRedo() { 21 | this.commands.getFirst().redo(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/event/Event.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb.event; 2 | 3 | public enum Event { 4 | LIGHT_BULB_TURNED_ON, 5 | LIGHT_BULB_TURNED_OFF 6 | } 7 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/event/EventHook.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb.event; 2 | 3 | public interface EventHook { 4 | public void onEvent(Event event); 5 | } 6 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/event/LightBulbTurnOffMetric.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb.event; 2 | 3 | public class LightBulbTurnOffMetric implements EventHook { 4 | private int turnOffCount = 0; 5 | 6 | @Override 7 | public void onEvent(Event event) { 8 | if (event == Event.LIGHT_BULB_TURNED_OFF) { 9 | turnOffCount++; 10 | } 11 | } 12 | 13 | public int getCount() { 14 | return turnOffCount; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lld/lightBulbCommandPattern/src/main/java/org/example/lightBulb/event/LightBulbTurnOnMetric.java: -------------------------------------------------------------------------------- 1 | package org.example.lightBulb.event; 2 | 3 | public class LightBulbTurnOnMetric implements EventHook { 4 | private int turnOnCount = 0; 5 | 6 | @Override 7 | public void onEvent(Event event) { 8 | if (event == Event.LIGHT_BULB_TURNED_ON) { 9 | turnOnCount += 1; 10 | System.out.println("Light turned on count: " + turnOnCount); 11 | } 12 | } 13 | 14 | public int getCount() { 15 | return turnOnCount; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /oops/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .gradle 3 | *.iml 4 | *.ipr 5 | .idea 6 | *__pycache__ 7 | vendor 8 | -------------------------------------------------------------------------------- /oops/Kata-Log/gossiping-bus-drivers/README.md: -------------------------------------------------------------------------------- 1 | ## Gossiping Bus Drivers 2 | 3 | - problem statement: [source](https://kata-log.rocks/gossiping-bus-drivers-kata) 4 | - source code: Not Available 5 | 6 | #### Short Description: 7 | Easy Simulation to figure out solution 8 | 9 | 10 | #### Checks: 11 | - [x] unit test 12 | - [ ] pylint 13 | - [ ] applied design pattern -------------------------------------------------------------------------------- /oops/Kata-Log/gossiping-bus-drivers/driver.py: -------------------------------------------------------------------------------- 1 | # Probably a better naming convention could have been used. 2 | 3 | class Driver: 4 | def __init__(self, driver_id, route): 5 | self._route = route 6 | self._driver_id = driver_id 7 | self.position = 0 8 | self._knows = set([self._driver_id]) 9 | 10 | @property 11 | def driver_id(self): 12 | return self._driver_id 13 | 14 | @property 15 | def current_stop(self): 16 | return self._route[self.position] 17 | 18 | def move_next(self): 19 | self.position = (self.position + 1) % len(self._route) 20 | 21 | def meet(self, other_drivers): 22 | self._knows = self._knows | other_drivers 23 | 24 | @property 25 | def knows(self): 26 | return self._knows 27 | -------------------------------------------------------------------------------- /oops/Kata-Log/gossiping-bus-drivers/simulator_test.py: -------------------------------------------------------------------------------- 1 | from simulator import simulate 2 | import unittest 3 | 4 | # To run tests, cd into the directory this file is located, then run the following: 5 | # python3 -m unittest simulator_test.py 6 | 7 | class SimulationTest(unittest.TestCase): 8 | ''' unit tests for the simulator''' 9 | def test_all_drivers_know(self): 10 | routes = [ 11 | [3, 1, 2, 3], 12 | [3, 2, 3, 1], 13 | [4, 2, 3, 4, 5] 14 | ] 15 | 16 | self.assertEqual(True, simulate(routes)[0]) 17 | 18 | def test_all_drivers_do_not_know(self): 19 | routes = [ 20 | [2, 1, 2], 21 | [5, 2, 8] 22 | ] 23 | 24 | self.assertFalse(simulate(routes)[0]) 25 | 26 | 27 | -------------------------------------------------------------------------------- /oops/Kata-Log/parallel-change/README.md: -------------------------------------------------------------------------------- 1 | ## Parallel Change Kata 2 | 3 | - problem statement: [source](https://kata-log.rocks/parallel-change-kata) 4 | - source code: [github](https://github.com/unclejamal/parallel-change) 5 | 6 | #### Short Description 7 | Modify source code to make it more generic. 8 | 9 | 10 | #### Checks: 11 | - [ ] unit test 12 | - [ ] pylint 13 | - [ ] applied design pattern -------------------------------------------------------------------------------- /oops/Kata-Log/parallel-change/method.py: -------------------------------------------------------------------------------- 1 | class AuthenticationService: 2 | def is_authenticated(self, id): 3 | return id == 12345 4 | 5 | ''' 6 | the goal is to replace the method above with this one: 7 | def is_authenticated(self, role, id): 8 | return id == 12345 9 | ''' 10 | 11 | 12 | class AuthenticationClient: 13 | def __init__(self, authenticationService): 14 | self.authenticationService = authenticationService 15 | 16 | def run(self): 17 | authenticated = self.authenticationService.is_authenticated(33) 18 | print("is authenticated: ", str(authenticated)) 19 | 20 | 21 | class YetAnotherClient: 22 | def run(self): 23 | AuthenticationService().is_authenticated(100) 24 | 25 | 26 | if __name__ == "__main__": 27 | client = AuthenticationClient(AuthenticationService()) 28 | client.run() 29 | -------------------------------------------------------------------------------- /oops/Kata-Log/parallel-change/run.sh: -------------------------------------------------------------------------------- 1 | python3 method.py 2 | python3 field.py 3 | python3 tests.py 4 | -------------------------------------------------------------------------------- /oops/LLD-Problems/vending_machine/requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | pytest 3 | coverage -------------------------------------------------------------------------------- /oops/LLD-Problems/vending_machine/setup.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | from setuptools import setup 3 | 4 | here = path.abspath(path.dirname(__file__)) 5 | 6 | # Get the long description from the README file 7 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 8 | long_description = f.read() 9 | 10 | setup( 11 | name='vending_machine', 12 | version='1.0.0', 13 | description='LLD problem of Vending Machine', 14 | long_description=long_description, 15 | packages=['src'], 16 | python_requires='>=3.8' 17 | ) 18 | -------------------------------------------------------------------------------- /oops/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/oops/README.md -------------------------------------------------------------------------------- /others/fast_scan.cpp: -------------------------------------------------------------------------------- 1 | #define gc getchar_unlocked 2 | void scanint(int &x){ 3 | register int c = gc(); 4 | x = 0; 5 | int neg = 0; 6 | for(;((c<48 || c>57) && c != '-');c = gc()); 7 | if(c=='-') {neg=1;c=gc();} 8 | for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} 9 | if(neg) x=-x; 10 | } -------------------------------------------------------------------------------- /others/io.cpp: -------------------------------------------------------------------------------- 1 | #pragma warning(disable:4996) 2 | #pragma comment(linker, "/stack:200000000") 3 | #pragma GCC optimize("Ofast") 4 | #pragma GCC optimize ("unroll-loops") 5 | #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") 6 | #pragma GCC optimize ("-ffloat-store") 7 | 8 | #include 9 | using namespace std; 10 | 11 | #define IOS ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); 12 | 13 | #define ll long long int 14 | 15 | const int inf = 0x3f3f3f3f; 16 | const ll INF = 0xFFFFFFFFFFFFFFFL; -------------------------------------------------------------------------------- /others/namingConventions.md: -------------------------------------------------------------------------------- 1 | `"Code should be self-documenting, that is, your naming should make it obvious what something does. exmaple"` 2 | 3 | ```javascript 4 | public boolean shouldConsiderAbbreviating(List someNames) { 5 | for (String eachName : someNames) { 6 | if (isTooLong(eachName)) { 7 | return true; 8 | } 9 | } 10 | return false; 11 | } 12 | ``` 13 | - [src](https://softwareengineering.stackexchange.com/a/130979) 14 | 15 | Read a good post about naming conventions [here](https://dev.to/somedood/a-grammar-based-naming-convention-13jf) 16 | 17 | Read about **Design Patterns** to know standard design problems and write maintainable code. 18 | -------------------------------------------------------------------------------- /others/split.cpp: -------------------------------------------------------------------------------- 1 | // usage : https://www.codechef.com/viewsolution/25026640 2 | 3 | vector split (string s, string delimiter){ 4 | /* 5 | Beware of mixing '>>' with getline(cin,str) as '>>' leaves '\n' in buffer 6 | which is taken by getline(cin,str); use cin.ignore() or std::fflush(stdin) 7 | when getline() is followed by '>>' 8 | */ 9 | if(s.back()=='\n')s=s.substr(0,(int)s.size()-1); 10 | //removing newline char (if exists) 11 | 12 | size_t pos_start = 0, pos_end, delim_len = delimiter.length(); 13 | string token; vector res; 14 | 15 | while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { 16 | token = s.substr (pos_start, pos_end - pos_start); 17 | pos_start = pos_end + delim_len; 18 | res.push_back (token); 19 | } 20 | 21 | res.push_back (s.substr (pos_start)); 22 | return res; 23 | } -------------------------------------------------------------------------------- /others/time_template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) 6 | 7 | #define time__(d) for(long blockTime = 0; (blockTime == 0 ? (blockTime=clock()) != 0 : false); debug("%s time : %.4fs\n", d, (double)(clock() - blockTime) / CLOCKS_PER_SEC)) 8 | 9 | int main (){ 10 | ios_base::sync_with_stdio(false); 11 | cin.tie(0); cout.tie(0); 12 | /*reading data*/ 13 | time__("dfs"){ 14 | /* dfs code */ 15 | } 16 | /*some code*/ 17 | time__("solve"){ 18 | solve(); 19 | } 20 | } -------------------------------------------------------------------------------- /solution/CSES/Dynamic Programming/Dice Combinations.py: -------------------------------------------------------------------------------- 1 | # https://cses.fi/problemset/task/1633 2 | 3 | n, mod = int(input()), 10**9 + 7 4 | 5 | dp = [0 for _ in range(n+1)] 6 | dp[0], dp[1] = 1, 1 7 | 8 | for i in range(2, n+1): 9 | for j in range(1, 7): 10 | dp[i] += dp[i-j] if i - j >= 0 else 0 11 | dp[i] %= mod 12 | 13 | print(dp[-1]) 14 | -------------------------------------------------------------------------------- /solution/CSES/Dynamic Programming/Removing Digits.cpp: -------------------------------------------------------------------------------- 1 | // https://cses.fi/problemset/task/1637 2 | // Another Iterative DP 3 | 4 | #include 5 | using namespace std; 6 | 7 | #define ll long long int 8 | const int N = 1e6; 9 | 10 | int main() { 11 | vector dp(N+1, 0); 12 | 13 | for (int i = 1; i < dp.size(); i += 1) { 14 | string s = to_string(i); 15 | dp[i] = N + 2; 16 | for (auto ch: s) { 17 | if (ch == '0') 18 | continue; 19 | dp[i] = min(dp[i], 1+dp[i-(ch-'0')]); 20 | } 21 | } 22 | 23 | int n; cin >> n; 24 | cout << dp[n] << '\n'; 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /solution/CSES/Introductory Problems/Missing Number.py: -------------------------------------------------------------------------------- 1 | # https://cses.fi/problemset/task/1083 2 | 3 | from functools import reduce 4 | 5 | n, expected_xor = int(input()), 0 6 | 7 | for i in range(n+1): 8 | expected_xor ^= i 9 | 10 | nums = list(map(int, input().split())) 11 | expected_xor ^= reduce(lambda x, y: x^y, nums) 12 | 13 | print(expected_xor) 14 | -------------------------------------------------------------------------------- /solution/HackerEarth_solutions/Cost_of_Data.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | ll cnt=0; 5 | 6 | struct trie{ 7 | bool eow=false; 8 | trie* lk[26]={nullptr}; 9 | }; 10 | 11 | trie* root=nullptr; 12 | 13 | trie* get(){ 14 | trie* temp=new trie; 15 | temp->eow =false; 16 | for(auto &it:temp->lk) 17 | it={nullptr}; 18 | cnt++; 19 | return temp; 20 | } 21 | 22 | void insert(string s){ 23 | if(root ==nullptr)root=get(); 24 | trie* temp=root; 25 | for(auto it:s){ 26 | if(temp->lk[it-'a']==nullptr) 27 | temp->lk[it-'a']=get(); 28 | temp=temp->lk[it-'a']; 29 | } 30 | temp->eow=true; 31 | } 32 | 33 | int main(){ 34 | ios_base::sync_with_stdio(false); 35 | cin.tie(0); cout.tie(0); 36 | int i,j,k,n,m; 37 | cin>>n; 38 | while(n--){ 39 | string s; 40 | cin>>s; insert(s); 41 | } 42 | cout< 4 | Space: O(n * m) 5 | 6 | Idea Used: Iterative Dynamic Programming. #path from (i, j) = #path from (i+1, j) + #path from (i, j+1) 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | int uniquePaths(int m, int n) { 12 | swap(n, m); 13 | vector> grid(n+1, vector (m+1, 0)); 14 | // he can move down or right 15 | grid[n-1][m-1] = 1; 16 | for (int i = n-1; i >= 0; i -= 1) { 17 | for (int j = m-1; j >= 0; j -= 1) { 18 | grid[i][j] += (grid[i+1][j] + grid[i][j+1]); 19 | } 20 | } 21 | 22 | return grid[0][0]; 23 | } 24 | }; 25 | ``` -------------------------------------------------------------------------------- /solution/atcoder/contests/ABC161/B.md: -------------------------------------------------------------------------------- 1 | * Cakewalk again 2 | 3 | ``` c++ 4 | #include 5 | using namespace std; 6 | 7 | #define ll long long int 8 | #define pi pair 9 | 10 | void solve(){ 11 | int n, m; cin >> n >> m; 12 | int ans = 0; 13 | vector v(n); 14 | for (int i = 0; i < n; i += 1) { 15 | cin >> v[i]; 16 | } 17 | 18 | ll sum = accumulate(v.begin(), v.end(), 0LL); 19 | for (int i = 0; i < n; i += 1) { 20 | if (v[i]*4*m >= sum) 21 | ans += 1; 22 | } 23 | 24 | if (ans >= m) 25 | cout << "Yes\n"; 26 | else 27 | cout << "No\n"; 28 | } 29 | 30 | int main(){ 31 | ios_base::sync_with_stdio(false); 32 | cin.tie(0); cout.tie(0); 33 | 34 | int test = 1; 35 | // cin >> test; 36 | while(test--) 37 | solve(); 38 | return 0; 39 | } 40 | 41 | ``` -------------------------------------------------------------------------------- /solution/atcoder/contests/ABC161/C.md: -------------------------------------------------------------------------------- 1 | * So much time was not needed for this 2 | 3 | ``` c++ 4 | #include 5 | using namespace std; 6 | 7 | #define ll long long int 8 | #define pi pair 9 | 10 | void solve(){ 11 | ll a, b; cin >> a >> b; 12 | ll g = __gcd(a, b); 13 | if (g == b) 14 | cout << 0 << '\n'; 15 | else if (g == a) 16 | cout << a << '\n'; 17 | else if (b < a) { 18 | b /= g; 19 | a /= g; 20 | cout << g*min(b-a%b, a%b) << '\n'; 21 | } 22 | else { 23 | b /= g; 24 | a /= g; 25 | cout << g*min({a,b-a}) << '\n'; 26 | } 27 | } 28 | 29 | int main(){ 30 | ios_base::sync_with_stdio(false); 31 | cin.tie(0); cout.tie(0); 32 | 33 | int test = 1; 34 | // cin >> test; 35 | while(test--) 36 | solve(); 37 | return 0; 38 | } 39 | 40 | ``` -------------------------------------------------------------------------------- /solution/atcoder/contests/ABC161/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [ABC 161](https://atcoder.jp/contests/abc161/tasks) 2 | 3 | * Contest type: Real 4 | 5 | * Contest Rank: 6635 6 | 7 | * Number of upsolve: 0 8 | 9 | * Total Remaining: 3 10 | 11 | * Remarks:   `Ahhhh.... Messed up badly. Room for lots of improvements.` -------------------------------------------------------------------------------- /solution/atcoder/educational_dp_contest/A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | const int N=1e5+5; 5 | ll dp[N]={-1},v[N],n; 6 | const int inf=0x3f3f3f3f; 7 | ll check(int index); 8 | 9 | 10 | int main(){ 11 | memset(dp,-1,sizeof(dp)); 12 | cin>>n; 13 | for(int i=0;i>v[i]; 15 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | const int N=1e5+5; 5 | ll dp[N]={-1},v[N],k,n; 6 | const int inf=0x3f3f3f3f; 7 | ll check(int index); 8 | 9 | 10 | int main(){ 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(0); cout.tie(0); 13 | ll i,j,m; 14 | memset(dp,-1,sizeof(dp)); 15 | cin>>n>>k; 16 | for(i=0;i>v[i]; 18 | cout<=n)return inf; 25 | else if(dp[index]!=-1)return dp[index]; 26 | 27 | else if(index==n-1)return dp[index]=0; 28 | ll var=inf; 29 | for(int i=index+1;i<=min(n-1,k+index);i++) 30 | var=min(var,abs(v[index]-v[i])+check(i)); 31 | return dp[index]=var; 32 | } 33 | -------------------------------------------------------------------------------- /solution/atcoder/educational_dp_contest/D.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | const int N=1e5+5; 5 | 6 | ll dp[102][N]={-1},n,w,v[2][N]; 7 | ll solve(int index, ll weight); 8 | ll minf = -0x3f3f3f3f; 9 | 10 | int main(){ 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(0); cout.tie(0); 13 | memset(dp,-1,sizeof(dp)); 14 | ll i,j,m,w; cin>>n>>w; 15 | for(i=1;i<=n;i++)cin>>v[0][i]>>v[1][i]; // weight,value 16 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | const ll N=1e5+3; 5 | vector v[N]; 6 | ll ans=0,n,dp[N]; 7 | #define eb emplace_back 8 | ll dfs(int node,int par); 9 | 10 | int main(){ 11 | ll i,j,k,m; 12 | cin>>n>>m; 13 | memset(dp,-1,sizeof(dp)); 14 | while(m--){ 15 | cin>>i>>j; 16 | v[i].eb(j); 17 | } 18 | for(i=1;i<=n;i++){ 19 | if(dp[i]==-1) 20 | dfs(i,-1); 21 | } 22 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | const ll N=1e3+2; 5 | const ll md=1e9+7; 6 | ll dp[N][N],n,m,ar[N][N]; 7 | 8 | int main(){ 9 | ll i,j,k; char ch; 10 | memset(dp,0,sizeof(dp)); 11 | cin>>n>>m; 12 | for(i=1;i<=n;i++){ 13 | for(j=1;j<=m;j++){ 14 | cin>>ch; 15 | if(ch=='#') 16 | dp[i][j]=-1; 17 | } 18 | } 19 | dp[1][1]=1; 20 | for(i=1;i<=n;i++){ 21 | for(j=1;j<=m;j++){ 22 | if(!(i==1 && j==1) && dp[i][j]!=-1) 23 | dp[i][j]=(dp[i-1][j]*(dp[i-1][j]!=-1)+dp[i][j-1]*(dp[i][j-1]!=-1))%md; 24 | } 25 | } 26 | cout< 2 | using namespace std; 3 | 4 | #define ll long long int 5 | const ll INF = 0xFFFFFFFFFFFFFFFL; 6 | 7 | ll dp[402][402]={-1},n,ar[402],pr[402]; 8 | 9 | ll solve(int i,int j){ 10 | if(dp[i][j]!=-1) 11 | return dp[i][j]; 12 | else if(i==j) 13 | return dp[i][j]=0; 14 | ll var = INF; 15 | for(int k=i;k>n; 23 | for(int i=1;i<=n;i++) 24 | cin>>ar[i]; 25 | for(int i=0;i<=n;i++) 26 | pr[i]=pr[i-1]+ar[i]; 27 | memset(dp,-1,sizeof(dp)); 28 | cout<> dp; 8 | vector nums; 9 | 10 | int build(int index, int sum) { 11 | // base case 12 | if (index < 0) 13 | return sum == 0; 14 | else if (sum <= 0) 15 | return sum == 0; 16 | else if (dp[index][sum] != -1) 17 | return dp[index][sum]; 18 | 19 | // calculate 20 | return dp[index][sum] = max(build(index-1, sum), build(index-2, sum-nums[index])); 21 | } 22 | 23 | bool solve(vector& Nums, int K) { 24 | nums = Nums; 25 | n = nums.size(); 26 | k = K; 27 | dp = vector> (n+1, vector (k+1, -1)); 28 | 29 | return build(n-1, k) == 1; 30 | } -------------------------------------------------------------------------------- /solution/binarysearch/861.cpp: -------------------------------------------------------------------------------- 1 | // https://binarysearch.com/problems/Sublist-with-Largest-Min-Length-Product 2 | 3 | // Two pointers 4 | // Time: O(n), space: O(1) 5 | 6 | int solve(vector& nums, int pos) { 7 | int ans = nums[pos]; 8 | int left = pos, right = pos, n = nums.size(), lowest = nums[pos]; 9 | 10 | while (left >= 0 || right < n) { 11 | if (left >= 0 && right < n) 12 | lowest = min(lowest, max(nums[left], nums[right])); 13 | else if (left >= 0) 14 | lowest = min(lowest, nums[left]); 15 | else if (right < n) 16 | lowest = min(lowest, nums[right]); 17 | 18 | while (left >= 0 && nums[left] >= lowest) 19 | left -= 1; 20 | while (right < n && nums[right] >= lowest) 21 | right += 1; 22 | 23 | ans = max(ans, lowest * (right-left-1)); 24 | } 25 | 26 | return ans; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /solution/binarysearch/Lowest Sum of Pair Larger than Target.cpp: -------------------------------------------------------------------------------- 1 | // https://binarysearch.com/problems/Lowest-Sum-of-Pair-Larger-than-Target 2 | 3 | #define all(x) x.begin(), x.end() 4 | 5 | int solve(vector& nums, int target) { 6 | sort(all(nums)); 7 | 8 | int ans = 1e7; 9 | for (int i = 0; i < nums.size(); i += 1) { 10 | int cur = nums[i]; 11 | int req = target - cur; 12 | // find the smallest num in nums which is > req 13 | auto it = upper_bound(all(nums), req); 14 | if (i == it - nums.begin()) 15 | it = next(it); 16 | if (it == nums.end()) 17 | continue; 18 | ans = min(ans, cur + *it); 19 | } 20 | 21 | return ans; 22 | } -------------------------------------------------------------------------------- /solution/binarysearch/Stacks.py: -------------------------------------------------------------------------------- 1 | # https://binarysearch.com/problems/Stacks 2 | 3 | class Solution: 4 | def solve(self, stacks): 5 | from itertools import accumulate 6 | max_sum = 0 7 | 8 | if not stacks: 9 | return max_sum 10 | 11 | pref_sums = [ 12 | set(accumulate(stack)) for stack in stacks 13 | ] 14 | 15 | for sum in pref_sums[0]: 16 | if all([sum in pref_sum for pref_sum in pref_sums]): 17 | max_sum = max(max_sum, sum) 18 | return max_sum 19 | -------------------------------------------------------------------------------- /solution/codechef/DSALearningSearies/STACKS.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/LRNDSA04/problems/STACKS 2 | # Basic binary search 3 | 4 | from bisect import bisect_right 5 | # bisect_right is equivalent to upper_bound in cpp 6 | 7 | def solve(): 8 | n, stack = int(input()), [] 9 | nums = list(map(int, input().split())) 10 | 11 | for num in nums: 12 | index = bisect_right(stack, num) 13 | if index == len(stack): 14 | stack.append(num) 15 | else: 16 | stack[index] = num 17 | # *stack : this is called tuple unpacking 18 | print(len(stack), *stack) 19 | 20 | def main(): 21 | tests = int(input()) 22 | for test in range(tests): 23 | solve() 24 | 25 | if __name__ == '__main__': 26 | main() -------------------------------------------------------------------------------- /solution/codeforces/contests/494/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Round 494](https://codeforces.com/contest/1003) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 1237 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 1 10 | 11 | * Remarks:   `Good performance after long break. ^_` -------------------------------------------------------------------------------- /solution/codeforces/contests/494/a.md: -------------------------------------------------------------------------------- 1 | ``` c++ 2 | #pragma GCC optimize("Ofast") 3 | #pragma GCC target("avx,avx2,fma") 4 | #pragma GCC optimization ("O3") 5 | #pragma GCC optimization ("unroll-loops") 6 | 7 | #include 8 | using namespace std; 9 | 10 | #define ll long long int 11 | #define pi pair 12 | 13 | void solve(){ 14 | int n; cin >> n; 15 | map mp; 16 | int ans = 0; 17 | for (int i = 0; i < n; i += 1) { 18 | int var; cin >> var; 19 | mp[var] += 1; 20 | ans = max(ans, mp[var]); 21 | } 22 | cout << ans << '\n'; 23 | } 24 | 25 | int main(){ 26 | ios_base::sync_with_stdio(false); 27 | cin.tie(0); cout.tie(0); 28 | 29 | int test = 1; 30 | // cin >> test; 31 | while(test--) 32 | solve(); 33 | return 0; 34 | } 35 | ``` -------------------------------------------------------------------------------- /solution/codeforces/contests/629/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Round 629](https://codeforces.com/contest/1328) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 1237 6 | 7 | * Number of upsolve: 0 8 | 9 | * Total Remaining: 2 10 | 11 | * Remarks:   `Good performance after long break. ^_^ Keep practicing :)` -------------------------------------------------------------------------------- /solution/codeforces/contests/629/a.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | #include 3 | using namespace std; 4 | 5 | #define ll long long int 6 | #define pi pair 7 | 8 | void solve(){ 9 | ll a, b; 10 | cin >> a >> b; 11 | ll var = a % b; 12 | if (var == 0) 13 | cout << 0 << '\n'; 14 | else 15 | cout << b-var << '\n'; 16 | 17 | } 18 | 19 | int main(){ 20 | ios_base::sync_with_stdio(false); 21 | cin.tie(0); cout.tie(0); 22 | 23 | int test = 1; 24 | cin >> test; 25 | while(test--) 26 | solve(); 27 | return 0; 28 | } 29 | 30 | ``` 31 | -------------------------------------------------------------------------------- /solution/codeforces/contests/629/b.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | #include 3 | using namespace std; 4 | 5 | #define ll long long int 6 | #define pi pair 7 | 8 | void solve(){ 9 | ll cur = 0, k, n, diff; 10 | cin >> n >> k; 11 | ll first = n-1, second = n; 12 | diff = n - first; 13 | while (k > cur + diff) { 14 | cur += diff; 15 | first -= 1; 16 | diff = n - first; 17 | } 18 | 19 | while (k > cur + 1) { 20 | cur += 1; 21 | second -= 1; 22 | } 23 | 24 | string s(n+1, 'a'); 25 | s[first] = 'b'; 26 | s[second] = 'b'; 27 | cout << s.substr(1) << '\n'; 28 | 29 | } 30 | 31 | int main(){ 32 | ios_base::sync_with_stdio(false); 33 | cin.tie(0); cout.tie(0); 34 | 35 | int test = 1; 36 | cin >> test; 37 | while(test--) 38 | solve(); 39 | return 0; 40 | } 41 | ``` -------------------------------------------------------------------------------- /solution/codeforces/contests/632/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Div2 632](https://codeforces.com/contest/1333) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 5040 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 3 10 | 11 | * Remarks:   `Could have done faster. 1700 problems are easy ! Need to focus a little.` -------------------------------------------------------------------------------- /solution/codeforces/contests/77/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Educational 77](https://codeforces.com/contest/1260) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 3258 6 | 7 | * Number of upsolve: 2 8 | 9 | * Total Remaining: 2 10 | 11 | * Remarks:   `Easy logics. Implementation needs fast, and time taken for coming up with solution for easy problems should be improved.` -------------------------------------------------------------------------------- /solution/codewars/1. Find all active students.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5809b9ef88b750ab180001ec/train/sql 2 | 3 | -- Type your query here 4 | SELECT * FROM students WHERE IsActive; -------------------------------------------------------------------------------- /solution/codewars/Duplicate Encoder.js: -------------------------------------------------------------------------------- 1 | // https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/javascript 2 | 3 | function duplicateEncode(word){ 4 | var freq = {} 5 | 6 | word.split('').forEach( ch => { 7 | ch = ch.toLowerCase(); 8 | freq[ch] = freq[ch] ? freq[ch] + 1: 1; 9 | }); 10 | 11 | encode = ''; 12 | word.split('').forEach( ch => { 13 | ch = ch.toLowerCase(); 14 | encode += freq[ch] <= 1 ? '(': ')'; 15 | }); 16 | 17 | return encode; 18 | } 19 | -------------------------------------------------------------------------------- /solution/codewars/Easy SQL: Absolute Value and Log to Base.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/594a8f2f7ca3c692a4000041/train/sql 2 | 3 | /* SQL */ 4 | SELECT abs(number1) AS abs, log(64, number2) AS log FROM decimals; -------------------------------------------------------------------------------- /solution/codewars/Easy SQL: Cube Root and Natural Log.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/594a6ad320ac16a54400007f/train/sql 2 | 3 | /* SQL */ 4 | SELECT cbrt(number1) as cuberoot, ln(number2) as logarithm FROM decimals; -------------------------------------------------------------------------------- /solution/codewars/Easy SQL: Rounding Decimals.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/594a6133704e4daf5d00003d/train/sql 2 | 3 | /* SQL */ 4 | SELECT FLOOR(number1) as number1, CEILING(number2) as number2 FROM decimals; -------------------------------------------------------------------------------- /solution/codewars/GROCERY STORE: Logistic Optimisation.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5a8ec692b17101bfc70001ba/train/sql 2 | 3 | -- Replace with your SQL Query 4 | 5 | SELECT producer, COUNT(distinct id) as count_products_types FROM 6 | products GROUP BY producer ORDER BY count_products_types DESC, producer ASC; -------------------------------------------------------------------------------- /solution/codewars/GROCERY STORE: Support Local Products.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5a8ed96bfd8c066e7f00011a/train/sql 2 | 3 | -- Replace with your SQL Query 4 | 5 | SELECT COUNT(id) AS products, country FROM products WHERE country IN ('United States of America', 'Canada') group by country order by COUNT(id) desc; 6 | -------------------------------------------------------------------------------- /solution/codewars/Relational division: Find all movies two actors cast in together.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5817b124e7f4576fd00020a2/train/sql 2 | 3 | -- Replace with your SQL Query 4 | 5 | 6 | WITH selected AS (SELECT * FROM film_actor WHERE actor_id IN (105, 122)) SELECT film.title FROM film, selected 7 | where film.film_id = selected.film_id GROUP BY film.film_id HAVING COUNT(actor_id) = 2 ORDER BY film.title; -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple EXISTS.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/58113a64e10b53ec36000293/train/sql 2 | 3 | -- Create your SELECT statement here 4 | -- https://www.geeksforgeeks.org/sql-exists/ 5 | SELECT * FROM departments WHERE EXISTS ( SELECT * FROM sales WHERE departments.id = sales.department_id AND sales.price > 98.00 ); -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple HAVING.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/58164ddf890632ce00000220/train/sql 2 | 3 | -- Create your SELECT statement here 4 | SELECT age, count(id) as total_people from people group by age HAVING count(id) >= 10; -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple IN.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/58113c03009b4fcc66000d29/train/sql 2 | 3 | -- Create your SELECT statement here 4 | SELECT id, name FROM departments where departments.id in (SELECT department_id FROM sales WHERE price > 98.00); 5 | -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple JOIN.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5802e32dd8c944e562000020/train/sql 2 | 3 | -- Create your SELECT statement here 4 | 5 | SELECT products.id, products.name, products.isbn, products.company_id, products.price, companies.name as company_name FROM products, companies WHERE products.company_id = companies.id; -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple WHERE and ORDER BY.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5809508cc47d327c12000084/train/sql 2 | 3 | -- Create your SELECT statement here 4 | SELECT * FROM people WHERE age > 50 order by age desc -------------------------------------------------------------------------------- /solution/codewars/SQL Basics: Simple WITH.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5811501c2d35672d4f000146/train/sql 2 | 3 | -- Create your SELECT statement here 4 | WITH special_sales AS ( SELECT * FROM sales WHERE price > 90.00 ) SELECT * FROM departments WHERE departments.id IN (SELECT department_id FROM special_sales); -------------------------------------------------------------------------------- /solution/codewars/SQL: Right and Left.sql: -------------------------------------------------------------------------------- 1 | -- https://www.codewars.com/kata/5943a58f95d5f72cb900006a/train/sql 2 | 3 | /* SQL */ 4 | SELECT SUBSTR(project, 0, commits+1) as project, RIGHT(address, contributors) AS address FROM repositories; 5 | -------------------------------------------------------------------------------- /solution/codewars/Stop gninnipS My sdroW!.js: -------------------------------------------------------------------------------- 1 | // https://www.codewars.com/kata/5264d2b162488dc400000001/train/javascript 2 | 3 | function spinWords(string){ 4 | //TODO Have fun :) 5 | var lst = string.split(' '); 6 | lst = lst.map(word => { 7 | if (word.length >= 5) return word.split('').reverse().join(''); 8 | return word; 9 | }); 10 | 11 | return lst.join(' '); 12 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/BFSOfGraph.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1 2 | 3 | /* Function to do BFS of graph 4 | * g[]: adj list of the graph 5 | * N : number of vertices 6 | */ 7 | vector bfs(vector g[], int N) { 8 | vector visited(N, false); 9 | queue q = {0}; 10 | visited[0] = true; 11 | vector order; order.reserve(N); 12 | 13 | while (!q.empty()) { 14 | int cur = q.front(); 15 | order.push_back(cur); 16 | q.pop(); 17 | for (auto child: g[cur]) { 18 | if (!visited[child]) { 19 | visited[child] = true; 20 | q.push(child); 21 | } 22 | } 23 | } 24 | 25 | return order; 26 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/DeleteMiddleOfLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/delete-middle-of-linked-list/1 2 | 3 | /* Link list Node 4 | /* Link list Node 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | 9 | Node(int x){ 10 | data = x; 11 | next = NULL; 12 | } 13 | }; 14 | */ 15 | 16 | // Deletes middle of linked list and returns head of the modified list 17 | Node* deleteMid(Node* head) { 18 | if (head == nullptr || head->next == nullptr) return head; 19 | Node* slow = head; 20 | Node* fast = head->next->next; 21 | 22 | while (fast != nullptr && fast->next != nullptr) { 23 | slow = slow->next; 24 | fast = fast->next; 25 | fast = (fast == nullptr ? nullptr: fast->next); 26 | } 27 | 28 | slow->next = slow->next->next; 29 | return head; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/DetectCycleInAnUndirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1/ 2 | 3 | /* 4 | * g[]: array of vectors to represent graph 5 | * V: number of vertices 6 | */ 7 | 8 | void dfs(vector &g[], int v, int node, int par, vector &vis, bool &hasCycle) { 9 | vis[node] = true; 10 | for (auto child: g[node]) { 11 | if (child == par) 12 | continue; 13 | else if (vis[child]) 14 | hasCycle = true; 15 | dfs(g, v, child, node, vis, hasCycle); 16 | } 17 | } 18 | 19 | bool isCyclic(vector g[], int v) { 20 | vector visited(v, false); 21 | bool hasCycle = false; 22 | 23 | for (int i = 0; i < v; i += 1) { 24 | if (!visited[i]) 25 | dfs(g, v, i, -1, visited, hasCycle); 26 | } 27 | 28 | return hasCycle; 29 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/DetectLoopInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1/ 2 | // slow and fast pointer method 3 | 4 | int detectloop(Node *head) { 5 | Node* slow = head; 6 | Node* fast = head; 7 | 8 | while(fast != nullptr) { 9 | slow = slow->next; 10 | fast = fast->next; 11 | if (fast != nullptr) 12 | fast = fast->next; 13 | else 14 | break; 15 | 16 | if (slow == fast) 17 | return 1; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/ExpressionTree.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/expression-tree/1 2 | 3 | /*The structure of node is as follows 4 | struct node{ 5 | string data; 6 | node *left; 7 | node *right; 8 | }; 9 | */ 10 | 11 | /*You are required to complete below method */ 12 | int evalTree(node* root) { 13 | if (isdigit(root->data[0])) 14 | return stoi(root->data); 15 | int left = evalTree(root->left), right = evalTree(root->right); 16 | switch (root->data[0]) { 17 | case '+': 18 | return left + right; 19 | case '-': 20 | return left - right; 21 | case '*': 22 | return left * right; 23 | case '/': 24 | return left / right; 25 | } 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/FindDuplicatesInAnArray.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/find-duplicates-in-an-array/1 2 | // Idea is to store 2 numbers at one index (upper bound of input numbers is given) 3 | 4 | vector duplicates(int a[], int n) { 5 | int mod = n; vector dup; 6 | for (int i = 0; i < n; i += 1) { 7 | int num = a[i] % mod; 8 | int freq = a[num]/mod; 9 | a[num] = a[num] % mod + (freq+1) * mod; 10 | } 11 | 12 | for (int i = 0; i < n; i += 1) { 13 | int freq = a[i] / mod; 14 | if (freq > 1) 15 | dup.push_back(i); 16 | } 17 | 18 | return (dup.empty() ? vector (1, -1): dup); 19 | } 20 | 21 | 22 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/FindPairWithGivenTargetInBST.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/find-a-pair-with-given-target-in-bst/1 2 | 3 | /*Complete the function below 4 | Node is as follows 5 | struct Node 6 | { 7 | int data; 8 | struct Node *left, *right; 9 | }; 10 | */ 11 | 12 | vector pre; 13 | 14 | void getPre(Node* root) { 15 | if (root == nullptr) 16 | return; 17 | getPre(root->left); 18 | pre.push_back(root->data); 19 | getPre(root->right); 20 | } 21 | 22 | bool isPairPresent(struct Node *root, int target) { 23 | pre.clear(); pre.resize(0); 24 | getPre(root); 25 | 26 | for (int i = 0; i < pre.size(); i += 1) { 27 | if (binary_search(pre.begin()+i+1, pre.end(), target-pre[i])) 28 | return true; 29 | } 30 | return false; 31 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/GetMinAtPop.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/get-min-at-pop/1/ 2 | 3 | stack_push(int arr[],int n) { 4 | stack stk; 5 | stk.push(arr[0]); 6 | for (int i = 1; i < n; i += 1) 7 | stk.push(min(stk.top(), arr[i])); 8 | return stk; 9 | } 10 | 11 | void _getMinAtPop(stacks) { 12 | while(!s.empty()) { 13 | cout << s.top() << ' '; 14 | s.pop(); 15 | } 16 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/InorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/inorder-traversal/1 2 | 3 | // Return a vector containing the inorder traversal of the tree 4 | vector inOrder(Node* root) { 5 | Node* currentNode = root; 6 | stack parent; 7 | vector nodes; 8 | 9 | // initialize stack somehow 10 | while (!parent.empty() || currentNode != nullptr) { 11 | // left subtree visited, now visit right subtree 12 | while (currentNode == nullptr && !parent.empty()) { 13 | currentNode = parent.top(); 14 | parent.pop(); 15 | nodes.push_back(currentNode->data); 16 | currentNode = currentNode->right; 17 | } 18 | 19 | if (currentNode != nullptr) { 20 | parent.push(currentNode); 21 | currentNode = currentNode->left; 22 | } 23 | } 24 | 25 | return nodes; 26 | } 27 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/LargestNumberFormedFromAnArray.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/largest-number-formed-from-an-array/0 2 | 3 | #include 4 | using namespace std; 5 | 6 | #define ll long long int 7 | #define pi pair 8 | #define all(x) x.begin(), x.end() 9 | 10 | void solve(){ 11 | int n; cin >> n; 12 | vector nums(n); 13 | for (auto &num: nums) 14 | cin >> num; 15 | 16 | sort(all(nums), [](string a, string b){ return a+b < b+a; }); 17 | reverse(all(nums)); 18 | cout << accumulate(all(nums), string()) << '\n'; 19 | } 20 | 21 | int main(){ 22 | ios_base::sync_with_stdio(false); 23 | cin.tie(0); cout.tie(0); 24 | 25 | int test = 1; 26 | cin >> test; 27 | while(test--) 28 | solve(); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/LeftViewOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1 2 | 3 | static int maxDepthCovered = -1; 4 | 5 | void recursivelyPrint(Node* root, int curDepth) { 6 | if (root == nullptr) 7 | return; 8 | if (curDepth > maxDepthCovered) { 9 | cout << root->data << ' '; 10 | maxDepthCovered = curDepth; 11 | } 12 | 13 | recursivelyPrint(root->left, curDepth+1); 14 | recursivelyPrint(root->right, curDepth+1); 15 | } 16 | 17 | // A wrapper over leftViewUtil() 18 | void leftView(Node *root) { 19 | maxDepthCovered = -1; 20 | recursivelyPrint(root, 0); 21 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/LinkedListOfStringsFormsAPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/linked-list-of-strings-forms-a-palindrome/1 2 | 3 | /* 4 | The structure of linked list is the following 5 | struct Node { 6 | string data; 7 | Node* next; 8 | 9 | Node(int x){ 10 | data = x; 11 | next = NULL; 12 | } 13 | }; 14 | */ 15 | bool compute(Node* root) { 16 | string input, rev; 17 | while(root != nullptr) { 18 | input += root->data; 19 | root = root->next; 20 | } 21 | 22 | rev = input; 23 | reverse(rev.begin(), rev.end()); 24 | return rev == input; 25 | } 26 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/LongestPrefixSuffix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define ll long long int 5 | 6 | void solve() { 7 | string s; cin >> s; 8 | int n = s.size(); 9 | 10 | vector pi(n, 0); 11 | 12 | // standard code to find pi table 13 | for (int i = 1; i < n; i += 1) { 14 | int len = pi[i-1]; 15 | while(len && s[len] != s[i]) 16 | len = pi[len -1]; 17 | if (s[i] == s[len]) 18 | len += 1; 19 | pi[i] = len; 20 | } 21 | 22 | cout << pi.back() << '\n'; 23 | } 24 | 25 | int main() { 26 | ios_base::sync_with_stdio(false); 27 | cin.tie(0); cout.tie(0); 28 | 29 | int test = 1; 30 | cin >> test; 31 | while(test--) 32 | solve(); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/LowestCommonAncestorInABST.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1 2 | 3 | /*The structure of a BST Node is as follows: 4 | struct Node { 5 | int data; 6 | Node *left; 7 | Node *right; 8 | 9 | Node(int val) { 10 | data = val; 11 | left = right = NULL; 12 | } 13 | }; 14 | */ 15 | 16 | // Returns the LCA of the nodes with values n1 and n2 17 | // in the BST rooted at 'root' 18 | Node* LCA(Node *root, int n1, int n2) { 19 | if (root == nullptr) return root; 20 | else if (root->data == n1 || root->data == n2) return root; 21 | 22 | Node* left = LCA(root->left, n1, n2); 23 | Node* right = LCA(root->right, n1, n2); 24 | 25 | if (left == nullptr) return right; 26 | else if (right == nullptr) return left; 27 | return root; 28 | } 29 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/MaxLengthChain.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/max-length-chain/1 2 | // See how sorting before dp is required ! 3 | 4 | int maxChainLen(struct val p[],int n) { 5 | vector v(n, 1); 6 | auto cmp = [](struct val a, struct val b)->bool{ 7 | if (a.first != b.first) 8 | return a.first < b.first; 9 | return a.second < b.second; 10 | }; 11 | 12 | sort(p, p+n, cmp); 13 | 14 | for (int i = 0; i < n; i += 1) { 15 | for (int j = 0; j < i; j += 1) { 16 | if (p[i].first > p[j].second) 17 | v[i] = max(v[i], 1 + v[j]); 18 | } 19 | } 20 | 21 | return *max_element(v.begin(), v.end()); 22 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/MergeKSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/merge-k-sorted-arrays/1 2 | 3 | int *mergeKArrays(int arr[][N], int k) { 4 | vector v(k, 0); 5 | int *ans = new int[k*k], next = 0, n = k; 6 | 7 | while (next != k*k) { 8 | pair mn = {0, INT_MAX}; 9 | // the following search can be transformed from O(k) to O(logk) 10 | // using some sorted Data Structure like set/ priority_queue 11 | for (int i = 0; i < k; i += 1) { 12 | if (v[i] == n) continue; 13 | else if (arr[i][v[i]] < mn.second) 14 | mn = make_pair(i, arr[i][v[i]]); 15 | } 16 | 17 | ans[next] = mn.second; 18 | next += 1; 19 | v[mn.first] += 1; 20 | } 21 | 22 | return ans; 23 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/merge-sort/1 2 | 3 | void merge(int arr[], int l, int m, int r) { 4 | vector ans(r-l+1); 5 | int first = l, second = m+1, index = 0; 6 | while (first <= m && second <= r) { 7 | if (arr[first] < arr[second]) { 8 | ans[index] = arr[first]; 9 | first += 1; index += 1; 10 | } 11 | else { 12 | ans[index] = arr[second]; 13 | second += 1; index += 1; 14 | } 15 | } 16 | 17 | while (first <= m) { 18 | ans[index] = arr[first]; 19 | first += 1; index += 1; 20 | } 21 | 22 | while (second <= r) { 23 | ans[index] = arr[second]; 24 | second += 1; index += 1; 25 | } 26 | 27 | for (int i = 0; i < ans.size(); i += 1) { 28 | arr[i+l] = ans[i]; 29 | } 30 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/MirrorTree.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/mirror-tree/1 2 | 3 | //function Template for C++ 4 | 5 | /* A binary tree node has data, pointer to left child 6 | and a pointer to right child / 7 | struct Node { 8 | int data; 9 | struct Node* left; 10 | struct Node* right; 11 | 12 | Node(int x){ 13 | data = x; 14 | left = right = NULL; 15 | } 16 | }; */ 17 | 18 | /* Should convert tree to its mirror */ 19 | void mirror(Node* node) { 20 | if (node == nullptr) 21 | return; 22 | swap(node->left, node->right); 23 | mirror(node->left); 24 | mirror(node->right); 25 | } 26 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/NthNodeFromEndOfLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/nth-node-from-end-of-linked-list/1 2 | // Using Two Pointers at given distance 3 | 4 | /* struct Node { 5 | int data; 6 | struct Node *next; 7 | Node(int x) { 8 | data = x; 9 | next = NULL; 10 | } 11 | }; 12 | */ 13 | 14 | /* Should return data of n'th node from the end of linked list. 15 | * head: head of the linked list 16 | * n: nth node from end to find 17 | */ 18 | int getNthFromLast(Node *head, int n) { 19 | Node* fast = head; 20 | Node* slow = head; 21 | while (n--) { 22 | if (fast == nullptr) return -1; 23 | fast = fast->next; 24 | } 25 | 26 | while (fast != nullptr) { 27 | slow = slow->next; 28 | fast = fast->next; 29 | } 30 | 31 | return slow->data; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/PredecessorAndSuccessor.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/predecessor-and-successor/1 2 | // Do Inorder Traversal and find the required nodes 3 | // Time: O(N), Space: O(logn) recursion stack 4 | 5 | /* BST Node 6 | struct Node { 7 | int key; 8 | struct Node *left, *right; 9 | }; 10 | */ 11 | 12 | // This function finds predecessor and successor of key in BST. 13 | // It sets pre and suc as predecessor and successor respectively 14 | void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { 15 | if (root == nullptr) return; 16 | 17 | findPreSuc(root->left, pre, suc, key); 18 | if (root->key < key) 19 | pre = root; 20 | else if (root->key > key && suc == nullptr) 21 | suc = root; 22 | 23 | findPreSuc(root->right, pre, suc, key); 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/PreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/preorder-traversal/1 2 | 3 | vector preorder(Node* root) { 4 | Node* currentNode = root; 5 | stack parents; 6 | vector nodes; 7 | 8 | while (!parents.empty() || currentNode != nullptr) { 9 | while (currentNode == nullptr && !parents.empty()) { 10 | currentNode = parents.top(); 11 | parents.pop(); 12 | } 13 | 14 | if (currentNode != nullptr) { 15 | nodes.push_back(currentNode->data); 16 | if (currentNode->right != nullptr) 17 | parents.push(currentNode->right); 18 | currentNode = currentNode->left; 19 | } 20 | } 21 | 22 | return nodes; 23 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/quick-sort/1 2 | 3 | int partition (int arr[], int low, int high) { 4 | int left = low, right = high; 5 | while (left < right) { 6 | while (left < high && arr[left] < arr[high]) 7 | left += 1; 8 | while (right > low && arr[right] >= arr[high]) 9 | right -= 1; 10 | if (left < right) 11 | swap(arr[left], arr[right]); 12 | else 13 | break; 14 | } 15 | 16 | swap(arr[left], arr[high]); 17 | return left; 18 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/RearrangeAnArrayWithO(1)ExtraSpace.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/rearrange-an-array-with-o1-extra-space/0 2 | 3 | // Idea is to store 2 numbers at one index 4 | 5 | // Function to rarrange the elements in O(1) extra space 6 | // arr: input array 7 | // n: size of array 8 | void arrange(long long arr[], int n) { 9 | int mod = 1 + *max_element(arr, arr+n); 10 | 11 | // store second element for each position 12 | for (int i = 0; i < n; i += 1) { 13 | int original = arr[i] % mod; 14 | int extra = arr[original] % mod; 15 | arr[i] = original + mod*extra; 16 | } 17 | 18 | // remove original element for each position 19 | for (int i = 0; i < n; i += 1) 20 | arr[i] /= mod; 21 | } 22 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/RotateALinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/rotate-a-linked-list/1 2 | 3 | /* 4 | struct Node { 5 | int data; 6 | struct Node *next; 7 | Node(int x) { 8 | data = x; 9 | next = NULL; 10 | } 11 | }; */ 12 | 13 | /* This function should rotate list counter-clockwise 14 | by k and return new head (if changed) */ 15 | Node* rotate(Node* head, int k) { 16 | Node* last = head; 17 | // find tail of linked list 18 | while (last->next != nullptr) 19 | last = last->next; 20 | // make the linked list circular 21 | last->next = head; 22 | 23 | while (--k) 24 | head = head->next; 25 | 26 | // cut the circular linked list at correct position 27 | last = head->next; 28 | head->next = nullptr; 29 | return last; 30 | } 31 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/RotateDoublyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/rotate-doubly-linked-list-by-p-nodes/1 2 | 3 | /* 4 | struct node{ 5 | int data; 6 | struct node*next,*prev; 7 | 8 | node(int x){ 9 | data = x; 10 | next = NULL; 11 | prev = NULL; 12 | } 13 | }; 14 | */ 15 | struct node*update(struct node*start,int p) { 16 | struct node* tail = start; 17 | while(tail->next != nullptr) 18 | tail = tail->next; 19 | 20 | node* head = start; 21 | head->prev = tail; 22 | tail->next = head; 23 | 24 | while(p--) 25 | start = start->next; 26 | 27 | start->prev->next = nullptr; 28 | start->prev = nullptr; 29 | 30 | return start; 31 | } -------------------------------------------------------------------------------- /solution/geeksforgeeks/SumOfDependenciesInAGraph.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/sum-of-dependencies-in-a-graph/0 2 | 3 | #include 4 | using namespace std; 5 | 6 | void solve() { 7 | int v, e; cin >> v >> e; 8 | vector outdegree(v+1, 0); 9 | for (int i = 0; i < e; i += 1) { 10 | int u, v; cin >> u >> v; 11 | outdegree[u] += 1; 12 | } 13 | 14 | cout << accumulate(outdegree.begin(), outdegree.end(), 0) << '\n'; 15 | } 16 | 17 | int main() { 18 | int test; cin >> test; 19 | while (test--) 20 | solve(); 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /solution/geeksforgeeks/SumTree.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/sum-tree/1 2 | 3 | /* Tree node 4 | struct Node { 5 | int data; 6 | Node* left, * right; 7 | }; */ 8 | 9 | // Should return true if tree is Sum Tree, else false 10 | bool isSumTree(Node* root){ 11 | if (root == nullptr) 12 | return true; 13 | else if (root->left == nullptr && root->right == nullptr) 14 | return true; 15 | // check left and right subtree 16 | bool is = isSumTree(root->left) && isSumTree(root->right); 17 | int val = (root->left != nullptr ? root->left->data: 0) + (root->right != nullptr ? root->right->data: 0); 18 | // check current node 19 | is = is && (val == root->data); 20 | // updated current node 21 | root->data += val; 22 | 23 | return is; 24 | } -------------------------------------------------------------------------------- /solution/hacker_rank/MaxArraySum.cpp: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/max-array-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming 2 | // Simple DP 3 | // Time: O(n) Space: O(n) can be improved to O(1) 4 | 5 | int maxSubsetSum(vector arr) { 6 | int n = arr.size(); 7 | vector> dp(2, vector(n, 0)); 8 | 9 | // dp[0][i]: i'th is not included 10 | dp[1][0] = arr[0]; 11 | 12 | for (int i = 1; i < n; i += 1) { 13 | dp[0][i] = max(dp[0][i-1], dp[1][i-1]); 14 | dp[1][i] = arr[i] + dp[0][i-1]; 15 | } 16 | 17 | return max(dp[0][n-1], dp[1][n-1]); 18 | } 19 | -------------------------------------------------------------------------------- /solution/hacker_rank/TimeDelta.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | from datetime import datetime, timedelta 5 | 6 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 7 | 8 | for _ in range(int(input())): 9 | t1, t2 = input(), input() 10 | time1 = datetime.strptime(t1, '%a %d %b %Y %X %z') 11 | time2 = datetime.strptime(t2, '%a %d %b %Y %X %z') 12 | difference = abs(time1 - time2) 13 | ans = str(int(difference.total_seconds())) 14 | fptr.write(ans + '\n') 15 | 16 | fptr.close() 17 | -------------------------------------------------------------------------------- /solution/interviewbit/Remove Duplicates from Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/remove-duplicates-from-sorted-array-ii/ 2 | 3 | int Solution::removeDuplicates(vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | int n = A.size(), left = 0, right = 0; 9 | while (right < n) { 10 | A[left] = A[right]; 11 | left += 1; right += 1; 12 | 13 | if (right < n && A[right] == A[left-1]) { 14 | A[left] = A[right]; 15 | left += 1; right += 1; 16 | } 17 | 18 | while (right < n && A[right] == A[right-1]) 19 | right += 1; 20 | } 21 | 22 | return left; 23 | } 24 | -------------------------------------------------------------------------------- /solution/interviewbit/Remove Half Nodes.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/remove-half-nodes/ 2 | 3 | /** 4 | * Definition for binary tree 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | TreeNode* Solution::solve(TreeNode* root) { 13 | if (root == nullptr) 14 | return root; 15 | else if (root->left == nullptr && root->right == nullptr) 16 | return root; 17 | root->left = solve(root->left); 18 | root->right = solve(root->right); 19 | 20 | if (root->left == nullptr) 21 | return root->right; 22 | else if (root->right == nullptr) 23 | return root->left; 24 | return root; 25 | } 26 | -------------------------------------------------------------------------------- /solution/leetcode/100.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/same-tree/description/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 12 | if p is None: 13 | return q is None 14 | elif q is None: 15 | return p is None 16 | 17 | if p.val != q.val: 18 | return False 19 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 20 | -------------------------------------------------------------------------------- /solution/leetcode/1004.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/max-consecutive-ones-iii/ 2 | 3 | class Solution { 4 | public: 5 | int longestOnes(vector& A, int k) { 6 | int zero = 0, ans = 0, left = 0, right = 0, n = A.size(); 7 | 8 | while (right < n) { 9 | while (right < n && zero <= k) { 10 | zero += (A[right] == 0); 11 | right += 1; 12 | } 13 | 14 | ans = max(ans, right-left-1); 15 | 16 | while (zero > k) { 17 | zero -= (A[left] == 0); 18 | left += 1; 19 | } 20 | } 21 | 22 | if (zero <= k) 23 | ans = max(ans, right-left); 24 | 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /solution/leetcode/1008.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def bstFromPreorder(self, preorder: List[int]) -> TreeNode: 12 | if not preorder: 13 | return None 14 | val = preorder[0] 15 | cur = TreeNode(val) 16 | 17 | index = 1 18 | while index < len(preorder) and preorder[index] < val: 19 | index += 1 20 | 21 | cur.left = self.bstFromPreorder(preorder[1:index]) 22 | cur.right = self.bstFromPreorder(preorder[index:]) 23 | return cur -------------------------------------------------------------------------------- /solution/leetcode/1014.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-sightseeing-pair/ 2 | 3 | class Solution: 4 | import heapq 5 | def maxScoreSightseeingPair(self, values: List[int]) -> int: 6 | future = [(-value + index, index) for index, value in enumerate(values)] 7 | heapq.heapify(future) 8 | 9 | _ans = 0 10 | for index, val in enumerate(values[:-1]): 11 | _index = index - 1 12 | while _index <= index: 13 | _val, _index = heapq.heappop(future) 14 | _val = -_val 15 | 16 | _ans = max(_ans, val+index+_val) 17 | heapq.heappush(future, (-_val, _index)) 18 | return _ans 19 | -------------------------------------------------------------------------------- /solution/leetcode/1022.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 2 | # Use of Generators in Recursion Python 3 | # Time: O(n) 4 | # Space: O(h), h: height of tree 5 | 6 | 7 | # Definition for a binary tree node. 8 | # class TreeNode: 9 | # def __init__(self, val=0, left=None, right=None): 10 | # self.val = val 11 | # self.left = left 12 | # self.right = right 13 | class Solution: 14 | def recur(self, root, curSum=''): 15 | if root == None: 16 | return None 17 | elif root.left == None and root.right == None: 18 | yield curSum 19 | else: 20 | yield from self.recur(root.left, curSum + str(root.val)) 21 | yield from self.recur(root.right, curSum + str(root.val)) 22 | 23 | def sumRootToLeaf(self, root: TreeNode) -> int: 24 | integer = lambda x: int(x, 2) 25 | return sum(map(integer, self.recur(root))) 26 | -------------------------------------------------------------------------------- /solution/leetcode/1046.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/last-stone-weight/ 2 | 3 | class Solution: 4 | import heapq 5 | def lastStoneWeight(self, stones: List[int]) -> int: 6 | # heaps in python are min-heap by default compared to cpp 7 | # where they are max heap 8 | stones = [-stone for stone in stones] 9 | heapq.heapify(stones) 10 | 11 | while len(stones) > 1: 12 | first, second = heapq.heappop(stones), heapq.heappop(stones) 13 | if first != second: 14 | heapq.heappush(stones, -abs(first - second)) 15 | 16 | if not stones: 17 | return 0 18 | return -stones[0] 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /solution/leetcode/1094.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/car-pooling/ 2 | 3 | class Solution { 4 | public: 5 | bool carPooling(vector>& trips, int capacity) { 6 | vector person(1002, 0); 7 | for (auto trip: trips) { 8 | int num = trip[0], start = trip[1], end = trip[2]; 9 | person[start] += num; 10 | person[end] -= num; 11 | } 12 | 13 | for (int i = 0, cur = 0; i < person.size(); i += 1) { 14 | cur += person[i]; 15 | if (cur > capacity) 16 | return false; 17 | } 18 | 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /solution/leetcode/1143.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-common-subsequence/ 2 | 3 | from functools import lru_cache 4 | 5 | class Solution: 6 | 7 | @lru_cache(None) 8 | def get(self, s1, s2, n, m): 9 | if min(n, m) < 0: 10 | return 0 11 | if s1[n] != s2[m]: 12 | return max(self.get(s1, s2, n-1, m), self.get(s1, s2, n, m-1)) 13 | 14 | return max( 15 | 1+ self.get(s1, s2, n-1, m-1), 16 | self.get(s1, s2, n-1, m), 17 | self.get(s1, s2, n, m-1) 18 | ) 19 | 20 | 21 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 22 | return self.get(text1, text2, len(text1)-1, len(text2)-1) 23 | -------------------------------------------------------------------------------- /solution/leetcode/120.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/triangle/ 2 | 3 | class Solution: 4 | from math import inf 5 | 6 | def minimumTotal(self, triangle: List[List[int]]) -> int: 7 | # create a copy 8 | dp = [[inf for _ in row] for row in triangle] 9 | dp[0][0] = triangle[0][0] 10 | 11 | for i, row in enumerate(dp[:-1]): 12 | for j, cell in enumerate(row): 13 | try: 14 | dp[i+1][j] = max(dp[i+1][j], dp[i][j] + triangle[i+1][j]) 15 | dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j] + triangle[i+1][j+1]) 16 | except IndexError: 17 | pass 18 | return min(dp[-1]) -------------------------------------------------------------------------------- /solution/leetcode/121.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | # solved again on Feb28, 2021 3 | 4 | class Solution: 5 | from math import inf 6 | 7 | def maxProfit(self, prices: List[int]) -> int: 8 | n, min_so_far, max_profit = len(prices), inf, 0 9 | dp = [[0 for _ in prices] for __ in [1, 2]] 10 | 11 | # dp[0], dp[1] = buy, sell 12 | for index, price in enumerate(prices): 13 | dp[0][index], dp[1][index] = -price, price - min_so_far 14 | min_so_far = min(min_so_far, price) 15 | max_profit = max(max_profit, dp[1][index]) 16 | 17 | return max_profit 18 | -------------------------------------------------------------------------------- /solution/leetcode/1221.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/split-a-string-in-balanced-strings/ 2 | 3 | class Solution { 4 | public: 5 | int balancedStringSplit(string s) { 6 | int _count = 0, open = 0; 7 | for (auto ch: s) { 8 | open += (ch == 'L'? 1: -1); 9 | if (open == 0) 10 | _count += 1; 11 | } 12 | 13 | return _count; 14 | } 15 | }; -------------------------------------------------------------------------------- /solution/leetcode/1248.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-number-of-nice-subarrays/ 2 | // two pointer based solution 3 | 4 | 5 | class Solution { 6 | public: 7 | int numberOfSubarrays(vector& nums, int k) { 8 | vector indexes = {-1}; 9 | int n = nums.size(), ans = 0; 10 | 11 | for (int i = 0; i < n; i += 1) { 12 | if (nums[i] % 2 == 1) 13 | indexes.push_back(i); 14 | } 15 | 16 | indexes.push_back(n); 17 | 18 | for (int i = 1; i+k < indexes.size(); i += 1) { 19 | int left = indexes[i] - indexes[i-1]; 20 | int right = indexes[i+k] - indexes[i+k-1]; 21 | ans += left * right; 22 | } 23 | 24 | return ans; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /solution/leetcode/125.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-palindrome/description/ 2 | 3 | class Solution: 4 | def isPalindrome(self, s: str) -> bool: 5 | s = s.lower() 6 | alphabets = 'abcdefghijklmnopqrstuvwxyz0123456789' 7 | 8 | s = ''.join([ch for ch in s if ch in alphabets]) 9 | print(s) 10 | return list(s) == list(reversed(s)) 11 | -------------------------------------------------------------------------------- /solution/leetcode/1281.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ 2 | 3 | /** 4 | * @param {number} n 5 | * @return {number} 6 | */ 7 | var subtractProductAndSum = function(n) { 8 | s = n.toString().split(''); 9 | product = s.reduce((sum, cur) => sum*parseInt(cur), 1); 10 | sum = s.reduce((sum, cur) => sum + parseInt(cur), 0); 11 | return product - sum; 12 | }; 13 | -------------------------------------------------------------------------------- /solution/leetcode/1282.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ 2 | 3 | 4 | class Solution: 5 | def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 6 | from collections import defaultdict 7 | groups, elements = [], defaultdict(list) 8 | 9 | for index, value in enumerate(groupSizes): 10 | elements[value].append(index) 11 | 12 | if len(elements[value]) == value: 13 | groups.append(elements[value]) 14 | elements[value] = [] 15 | 16 | return groups 17 | 18 | -------------------------------------------------------------------------------- /solution/leetcode/1288.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-covered-intervals/ 2 | // Time: O(nlogn) Space: O(n) 3 | // Sorting with custom comparator 4 | 5 | class Solution { 6 | public: 7 | int removeCoveredIntervals(vector>& intervals) { 8 | sort(intervals.begin(), intervals.end(), [](vector a, vector b){ 9 | if (a[0] != b[0]) 10 | return a[0] < b[0]; 11 | return a[1] > b[1]; 12 | }); 13 | 14 | int cnt = 0; 15 | set last = {-1}; 16 | for (auto v: intervals) { 17 | while (!last.empty() && v[0] >= *last.begin()) 18 | last.erase(last.begin()); 19 | if (last.empty() || *last.rbegin() < v[1]) 20 | cnt += 1; 21 | last.insert(v[1]); 22 | } 23 | 24 | return cnt; 25 | } 26 | }; 27 | 28 | // [[1,4],[2,8],[3,6]] -------------------------------------------------------------------------------- /solution/leetcode/1310.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/xor-queries-of-a-subarray/ 2 | // Time: O(N) Space: O(N) 3 | // Prefix Sum type solution 4 | // Solved again on May2, 2021 5 | 6 | class Solution { 7 | public: 8 | vector xorQueries(vector& arr, vector>& queries) { 9 | int n = arr.size(); 10 | vector pref(n, arr[0]), res; 11 | 12 | for (int i = 1; i < n; i += 1) 13 | pref[i] = pref[i-1] ^ arr[i]; 14 | 15 | for (auto q: queries) { 16 | int sum = pref[q[1]] ^ pref[q[0]] ^ arr[q[0]]; 17 | res.push_back(sum); 18 | } 19 | 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /solution/leetcode/1312.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ 2 | 3 | class Solution { 4 | int n; 5 | vector> dp; 6 | 7 | int recur(int l, int r, string &s) { 8 | if (l==r) return 0; 9 | else if (dp[l][r] != -1) 10 | return dp[l][r]; 11 | else if (l+1 == r) 12 | return dp[l][r] = (s[l] == s[r] ? 0: 1); 13 | return dp[l][r] = (s[l] == s[r] ? recur(l+1, r-1, s): 1 + min(recur(l+1, r, s), recur(l, r-1, s))); 14 | } 15 | 16 | public: 17 | int minInsertions(string s) { 18 | n = s.size(); 19 | dp = vector> (n, vector (n, -1)); 20 | 21 | return recur(0, n-1, s); 22 | } 23 | }; -------------------------------------------------------------------------------- /solution/leetcode/1338.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reduce-array-size-to-the-half/ 2 | # Time: O(nlogn) 3 | # Space: O(n) 4 | # Simple sorting and use of map/ dict 5 | 6 | 7 | class Solution: 8 | def minSetSize(self, arr: List[int]) -> int: 9 | from collections import Counter 10 | f = Counter(arr) 11 | f = sorted(f.items(), key=lambda x: (-x[1], x[0])) 12 | 13 | index, sum = 0, 0 14 | while 2*sum < len(arr): 15 | sum += f[index][1] 16 | index += 1 17 | 18 | return index -------------------------------------------------------------------------------- /solution/leetcode/1359.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/ 2 | 3 | class Solution { 4 | const static int mod = 1e9 + 7; 5 | public: 6 | int countOrders(int n) { 7 | vector dp(n+1, 1); 8 | for (int i = 2; i <= n; i += 1) { 9 | dp[i] = dp[i-1]*((2*i-1) + (i-1)*(2*i-1)); 10 | dp[i] %= mod; 11 | } 12 | 13 | return dp.back() % mod; 14 | } 15 | }; -------------------------------------------------------------------------------- /solution/leetcode/1389.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/create-target-array-in-the-given-order/ 2 | 3 | /** 4 | * @param {number[]} nums 5 | * @param {number[]} index 6 | * @return {number[]} 7 | */ 8 | var createTargetArray = function(nums, index) { 9 | let ans = []; 10 | for (let i = 0; i < index.length; i += 1) { 11 | ans.splice(index[i], 0, nums[i]); 12 | } 13 | 14 | return ans; 15 | }; 16 | 17 | /* 18 | # python3 19 | class Solution: 20 | def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: 21 | target = [] 22 | for num, position in zip(nums, index): 23 | target.insert(position, num) 24 | 25 | return target 26 | 27 | */ -------------------------------------------------------------------------------- /solution/leetcode/14.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | 4 | class Solution: 5 | def longestCommonPrefix(self, strs: List[str]) -> str: 6 | common = [] 7 | 8 | for chars in zip(*strs): 9 | if len(set(chars)) == 1: 10 | common.append(chars[0]) 11 | else: 12 | break 13 | 14 | return ''.join(common) -------------------------------------------------------------------------------- /solution/leetcode/1402.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reducing-dishes/ 2 | // solved again on Apr28, 2021 3 | 4 | class Solution { 5 | public: 6 | int maxSatisfaction(vector& satisfaction) { 7 | int ans = 0, n = satisfaction.size(); 8 | sort(satisfaction.begin(), satisfaction.end()); 9 | 10 | for (int start = 0; start < n; start += 1) { 11 | int sum = 0; 12 | for (int i = start; i < n; i += 1) { 13 | sum += satisfaction[i] * (i-start+1); 14 | } 15 | ans = max(ans, sum); 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /solution/leetcode/1409.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/queries-on-a-permutation-with-key/ 2 | 3 | class Solution: 4 | def processQueries(self, queries: List[int], m: int) -> List[int]: 5 | perm, sol = list(range(1, m+1)), [] 6 | 7 | for query in queries: 8 | i = perm.index(query) 9 | sol.append(i) 10 | perm = [query] + perm[:i] + perm[i+1:] 11 | 12 | return sol -------------------------------------------------------------------------------- /solution/leetcode/141.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution: 10 | def hasCycle(self, head: Optional[ListNode]) -> bool: 11 | slow = head 12 | fast = head 13 | 14 | while fast: 15 | slow = slow.next 16 | fast = fast.next 17 | 18 | if fast: 19 | fast = fast.next 20 | 21 | if slow and slow == fast: 22 | return True 23 | -------------------------------------------------------------------------------- /solution/leetcode/1431.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 2 | 3 | /** 4 | * @param {number[]} candies 5 | * @param {number} extraCandies 6 | * @return {boolean[]} 7 | */ 8 | // Copied implementation just to get familiar with js 9 | var kidsWithCandies = function(candies, extraCandies) { 10 | let maxCandies = Math.max(...candies); 11 | return candies.map(candy => candy+extraCandies >= maxCandies); 12 | }; 13 | -------------------------------------------------------------------------------- /solution/leetcode/1448.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-good-nodes-in-binary-tree/ 2 | // solved on March3, 2021 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | int goodNodes(TreeNode* root, int mx = -100000) { 18 | if (root == nullptr) 19 | return 0; 20 | return (root->val >= mx) + goodNodes(root->left, max(mx, root->val)) + goodNodes(root->right, max(mx, root->val)); 21 | } 22 | }; -------------------------------------------------------------------------------- /solution/leetcode/1456.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/ 2 | 3 | class Solution { 4 | public: 5 | int maxVowels(string s, int k) { 6 | int ans = 0, l = 0, r = 0, _cnt = 0; 7 | 8 | string vowel = "aeiou"; 9 | 10 | while (r < s.size()) { 11 | if (vowel.find(s[r]) != string::npos) 12 | _cnt += 1; 13 | 14 | while (r-l+1 > k) { 15 | if (vowel.find(s[l]) != string::npos) 16 | _cnt -= 1; 17 | l += 1; 18 | } 19 | 20 | ans = max(ans, _cnt); 21 | r += 1; 22 | } 23 | 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /solution/leetcode/1557.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ 2 | 3 | class Solution { 4 | public: 5 | vector findSmallestSetOfVertices(int n, vector>& edges) { 6 | vector indegree(n, 0), ans; 7 | for (auto e: edges) 8 | indegree[e[1]] += 1; 9 | for (int i = 0; i < n; i += 1) 10 | if (indegree[i] == 0) 11 | ans.push_back(i); 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /solution/leetcode/160.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/intersection-of-two-linked-lists/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 14 | ListNode* fast = headA; 15 | ListNode* slow = headB; 16 | 17 | while (fast != nullptr && slow != nullptr) { 18 | if (fast == slow) return fast; 19 | 20 | fast = fast->next; 21 | slow = slow->next; 22 | if (fast == slow) return fast; 23 | if (fast == nullptr) fast = headB; 24 | if (slow == nullptr) slow = headA; 25 | } 26 | 27 | return nullptr; 28 | } 29 | }; -------------------------------------------------------------------------------- /solution/leetcode/1657.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/determine-if-two-strings-are-close/ 2 | 3 | class Solution: 4 | def closeStrings(self, word1: str, word2: str) -> bool: 5 | from collections import Counter 6 | 7 | if set(word1) != set(word2): 8 | return False 9 | 10 | c1 = list(Counter(word1).values()) 11 | c2 = list(Counter(word2).values()) 12 | 13 | return sorted(c1) == sorted(c2) 14 | -------------------------------------------------------------------------------- /solution/leetcode/1695.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-erasure-value/ 2 | 3 | class Solution: 4 | def maximumUniqueSubarray(self, nums: List[int]) -> int: 5 | window = set() 6 | cur_sum, best_sum = 0, 0 7 | left, right = 0, 0 8 | 9 | while right < len(nums): 10 | while nums[right] in window: 11 | window.discard(nums[left]) 12 | cur_sum -= nums[left] 13 | left += 1 14 | 15 | cur_sum += nums[right] 16 | window.add(nums[right]) 17 | 18 | best_sum = max(best_sum, cur_sum) 19 | right += 1 20 | 21 | return best_sum 22 | 23 | -------------------------------------------------------------------------------- /solution/leetcode/1696.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/jump-game-vi/ 2 | 3 | from sortedcontainers import SortedList 4 | 5 | 6 | class Solution: 7 | from math import inf 8 | 9 | def maxResult(self, nums: List[int], k: int) -> int: 10 | n = len(nums) 11 | scores = [nums[-1] for _ in nums] 12 | window = SortedList([(nums[-1], n-1)]) 13 | 14 | for i in range(n-2, -1, -1): 15 | cur_score = nums[i] + window[-1][0] 16 | if i + k < n: 17 | window.discard((scores[i+k], i+k)) 18 | scores[i] = cur_score 19 | window.add((scores[i], i)) 20 | 21 | return scores[0] 22 | -------------------------------------------------------------------------------- /solution/leetcode/17.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/109/backtracking/793/ 2 | # Backtracking based solution 3 | 4 | class Solution: 5 | def __init__(self): 6 | self.letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'kjl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} 7 | def letterCombinations(self, digits: str) -> List[str]: 8 | if not digits: 9 | return [] 10 | elif len(digits) == 1: 11 | return list(self.letters[digits[0]]) 12 | words = self.letterCombinations(digits[1:]) 13 | return [ch+word for ch in self.letters[digits[0]] for word in words] 14 | -------------------------------------------------------------------------------- /solution/leetcode/1702.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-binary-string-after-change/ 2 | 3 | class Solution: 4 | def maximumBinaryString(self, binary: str) -> str: 5 | if '0' not in binary or binary.count('0') == 1: 6 | return binary 7 | num_zeros = binary.count('0') 8 | index_of_first_zero = binary.index('0') 9 | ans = ['1' for _ in binary] 10 | ans[index_of_first_zero + num_zeros -1] = '0' 11 | return ''.join(ans) 12 | 13 | 14 | -------------------------------------------------------------------------------- /solution/leetcode/1721.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def get(self, head, k): 10 | while k-1: 11 | head = head.next 12 | k = k-1 13 | return head 14 | 15 | def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: 16 | kth = self.get(head, k) 17 | left, right = head, kth 18 | while right.next: 19 | left = left.next 20 | right = right.next 21 | 22 | kth.val, left.val = left.val, kth.val 23 | return head 24 | -------------------------------------------------------------------------------- /solution/leetcode/1734.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/decode-xored-permutation/ 2 | 3 | class Solution: 4 | def decode(self, encoded: List[int]) -> List[int]: 5 | total_zor = 0 6 | n = len(encoded) + 1 7 | for i in range(n+1): 8 | total_zor ^= i 9 | 10 | nums = [0 for _ in range(n)] 11 | for perm in encoded[1::2]: 12 | nums[0] = nums[0] ^ perm 13 | nums[0] ^= total_zor 14 | for index, _ in enumerate(nums[1:], 1): 15 | nums[index] = nums[index-1] ^ encoded[index-1] 16 | 17 | return nums 18 | -------------------------------------------------------------------------------- /solution/leetcode/175.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/combine-two-tables/description/ 2 | 3 | # Write your MySQL query statement below 4 | SELECT firstName, lastName, city, state from Person LEFT Join Address on Person.personId = Address.personId; 5 | -------------------------------------------------------------------------------- /solution/leetcode/176.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/second-highest-salary/description/ 2 | 3 | # Write your MySQL query statement below 4 | SELECT MAX(salary) as SecondHighestSalary FROM Employee where salary not in (SELECT MAX(salary) from Employee); 5 | -------------------------------------------------------------------------------- /solution/leetcode/182.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/duplicate-emails/description/ 2 | 3 | # Write your MySQL query statement below 4 | select email from person group by email having count(id) > 1; 5 | -------------------------------------------------------------------------------- /solution/leetcode/183.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/customers-who-never-order/description/ 2 | 3 | # Write your MySQL query statement below 4 | select name as Customers from customers where id not in (select customers.id from customers join orders where customers.id = orders.customerId); 5 | -------------------------------------------------------------------------------- /solution/leetcode/191.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-1-bits/description/ 2 | 3 | class Solution: 4 | def hammingWeight(self, n: int) -> int: 5 | print(bin(n)[2:], n) 6 | return bin(n)[2:].count('1') 7 | -------------------------------------------------------------------------------- /solution/leetcode/1944.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-visible-people-in-a-queue/ 2 | 3 | 4 | class Solution: 5 | from collections import deque 6 | def canSeePersonsCount(self, heights: List[int]) -> List[int]: 7 | _count = [0 for _ in heights] 8 | n = len(heights) 9 | _stack = deque([heights[-1]]) 10 | 11 | for i in range(n-2, -1, -1): 12 | while _stack and heights[i] > _stack[0]: 13 | _stack.popleft() 14 | _count[i] += 1 15 | _count[i] += len(_stack) != 0 16 | _stack.appendleft(heights[i]) 17 | return _count 18 | -------------------------------------------------------------------------------- /solution/leetcode/1975.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-matrix-sum/ 2 | 3 | class Solution: 4 | def maxMatrixSum(self, matrix: List[List[int]]) -> int: 5 | _sum = sum(sum(map(abs, row)) for row in matrix) 6 | negatives = 0 7 | for row in matrix: 8 | for val in row: 9 | if val < 0: 10 | negatives = (negatives + 1) % 2 11 | 12 | # if num of -ve nums is odd, then subtract else not 13 | if negatives: 14 | offset = min(min(map(abs, row)) for row in matrix) 15 | else: 16 | offset = 0 17 | print(negatives, offset, _sum) 18 | return _sum - 2*offset 19 | -------------------------------------------------------------------------------- /solution/leetcode/198.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/house-robber/submissions/ 2 | # Another simple DP 3 | 4 | class Solution: 5 | def rob(self, cost: List[int]) -> int: 6 | if len(cost) < 3: 7 | return max(cost) if cost else 0 8 | 9 | # dp[0][i] = profit when not rob i'th house 10 | dp = [[0 for _ in cost] for __ in [1, 2]] 11 | dp[1][:2], dp[0][1] = cost[:2], cost[0] 12 | 13 | for index, val in enumerate(cost[2:], 2): 14 | dp[0][index] = max(dp[0][index-1], dp[1][index-1]) 15 | dp[1][index] = val + max(dp[0][index-2], dp[1][index-2]) 16 | 17 | return max(dp[0][-1], dp[1][-1]) -------------------------------------------------------------------------------- /solution/leetcode/20.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-parentheses/ 2 | 3 | 4 | class Solution: 5 | 6 | def isValid(self, s: str) -> bool: 7 | stack = [] 8 | opening = list('({[') 9 | closing = list(')}]') 10 | 11 | for ch in s: 12 | if ch in opening: 13 | stack.append(ch) 14 | else: 15 | index = closing.index(ch) 16 | if not stack: 17 | return False 18 | elif stack[-1] != opening[index]: 19 | return False 20 | stack.pop() 21 | return len(stack) == 0 22 | -------------------------------------------------------------------------------- /solution/leetcode/2012.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sum-of-beauty-in-the-array/ 2 | 3 | class Solution: 4 | def sumOfBeauties(self, nums: List[int]) -> int: 5 | left_max = [nums[0] for _ in nums] 6 | right_min = [nums[-1] for _ in nums] 7 | 8 | for index, num in enumerate(nums[1:], 1): 9 | left_max[index] = max(num, left_max[index-1]) 10 | 11 | n = len(nums) 12 | for index in range(n-2, -1, -1): 13 | right_min[index] = min(nums[index], right_min[index+1]) 14 | 15 | ans = 0 16 | for i in range(1, n-1): 17 | if left_max[i-1] < nums[i] < right_min[i+1]: 18 | ans += 2 19 | elif nums[i-1] < nums[i] < nums[i+1]: 20 | ans += 1 21 | 22 | return ans 23 | -------------------------------------------------------------------------------- /solution/leetcode/202.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/happy-number/description/?envType=study-plan&id=level-2 2 | 3 | class Solution: 4 | def isHappy(self, n: int) -> bool: 5 | n = str(n) 6 | visited = set() 7 | 8 | while not n in visited: 9 | x = sum( 10 | int(ch) **2 for ch in n 11 | ) 12 | visited.add(n) 13 | n = str(x) 14 | # print(n) 15 | 16 | return n == '1' 17 | -------------------------------------------------------------------------------- /solution/leetcode/204.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-primes/ 2 | 3 | class Solution: 4 | def countPrimes(self, n: int) -> int: 5 | is_prime = [True for _ in range(n)] 6 | is_prime[:2] = [False, False] 7 | 8 | for i in range(2, n): 9 | if is_prime[i]: 10 | for j in range(i*2, n, i): 11 | is_prime[j] = False 12 | 13 | return sum(is_prime) 14 | -------------------------------------------------------------------------------- /solution/leetcode/209.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-size-subarray-sum/ 2 | 3 | #define all(x) x.begin(), x.end() 4 | 5 | class Solution { 6 | public: 7 | int minSubArrayLen(int target, vector& nums) { 8 | // create a prefix sum 9 | vector pref(1); 10 | for (auto num: nums) 11 | pref.push_back(num + pref.back()); 12 | 13 | int ans = nums.size() + 2, n = nums.size(); 14 | 15 | for (int i = 1; i <= n; i += 1) { 16 | int req = pref[i-1] + target; 17 | // find index whose val is >= req 18 | int index = lower_bound(all(pref), req) - pref.begin(); 19 | if (index <= n) 20 | ans = min(ans, index-i+1); 21 | } 22 | 23 | if (ans > nums.size()) ans = 0; 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /solution/leetcode/237.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution: 10 | def deleteNode(self, node): 11 | """ 12 | :type node: ListNode 13 | :rtype: void Do not return anything, modify node in-place instead. 14 | """ 15 | node.val = node.next.val 16 | node.next = node.next.next 17 | -------------------------------------------------------------------------------- /solution/leetcode/300.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-increasing-subsequence/description/ 2 | 3 | from math import inf 4 | from bisect import bisect_left 5 | 6 | 7 | class Solution: 8 | def lengthOfLIS(self, nums: List[int]) -> int: 9 | dp = [inf for _ in nums] + [inf] 10 | for num in nums: 11 | index = bisect_left(dp, num) 12 | if dp[index] >= num: 13 | dp[index] = num 14 | else: 15 | dp[index+1] = min(dp[index+1], num) 16 | 17 | for index, val in enumerate(dp): 18 | if dp[index+1] == inf: 19 | return index+1 20 | -------------------------------------------------------------------------------- /solution/leetcode/303.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/range-sum-query-immutable/ 2 | # Another basic prefix sum based solution 3 | 4 | class NumArray: 5 | 6 | def __init__(self, nums: List[int]): 7 | self.pref = nums 8 | for index, val in enumerate(nums[1:], 1): 9 | self.pref[index] = val + self.pref[index-1] 10 | 11 | 12 | def sumRange(self, i: int, j: int) -> int: 13 | return self.pref[j] - self.pref[i-1] if i > 0 else self.pref[j] 14 | 15 | 16 | # Your NumArray object will be instantiated and called as such: 17 | # obj = NumArray(nums) 18 | # param_1 = obj.sumRange(i,j) -------------------------------------------------------------------------------- /solution/leetcode/30DayChallenge/1/solution1.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day1](https://leetcode.com/explore/other/card/30-day-leetcoding-challenge/528/week-1/3283/) 3 | 4 | Tried: 5 | - ```for_each``` function from ```algorithm``` library. 6 | - ```labmda``` functions in c++. 7 | 8 | ``` c++ 9 | class Solution { 10 | public: 11 | int singleNumber(vector& nums) { 12 | int ans = 0; 13 | auto Xor = [&](int i)->void{ans ^= i;}; 14 | for_each(nums.begin(), nums.end(), Xor); 15 | return ans; 16 | } 17 | }; 18 | 19 | ``` 20 | 21 | Tried: 22 | - ```Reduce``` function from ```functools``` 23 | 24 | ``` python 25 | from functools import reduce 26 | 27 | class Solution: 28 | def singleNumber(self, nums: List[int]) -> int: 29 | return reduce(lambda x,y: x^y, nums) 30 | 31 | ``` -------------------------------------------------------------------------------- /solution/leetcode/30DayChallenge/22/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day22](https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/531/week-4/3307/) 3 | 4 | Tried: 5 | - Simple `Prefix Sum` 6 | 7 | ``` c++ 8 | class Solution { 9 | public: 10 | #define ll long long int 11 | 12 | int subarraySum(vector& nums, int k) { 13 | map freq {{0, 1}}; 14 | int ans = 0; ll pref = 0; 15 | for (auto it: nums) { 16 | pref += it; 17 | ans += freq[pref-k]; 18 | freq[pref] += 1; 19 | } 20 | 21 | return ans; 22 | } 23 | }; 24 | ``` -------------------------------------------------------------------------------- /solution/leetcode/30DayChallenge/23/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day23](https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/531/week-4/3308/) 3 | 4 | Tried: 5 | - Observation based `Bitwise` 6 | 7 | ``` c++ 8 | class Solution { 9 | public: 10 | bool isSet(long long int num, int bit) { 11 | return num & (1LL << bit); 12 | } 13 | 14 | int rangeBitwiseAnd(long long int m, long long int n) { 15 | long long int ans = 0; 16 | for (int i = 40; i >= 0; i -= 1) { 17 | if (isSet(m, i) && isSet(n, i)) 18 | ans = ans | (1LL << i); 19 | else if (isSet(m, i) != isSet(n, i)) 20 | break; 21 | } 22 | return ans; 23 | } 24 | }; 25 | ``` -------------------------------------------------------------------------------- /solution/leetcode/30DayChallenge/4/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day4](https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3286/) 3 | 4 | Tried: 5 | - ```Two Pointer Method```:   O(n) 6 | 7 | ``` c++ 8 | class Solution { 9 | public: 10 | void moveZeroes(vector& nums) { 11 | int n = nums.size(); 12 | int zero = 0, nonZero = 0; 13 | while(nonZero < n && zero < n) { 14 | if (nonZero > zero) 15 | swap(nums[zero], nums[nonZero]); 16 | else 17 | nonZero += 1; 18 | while(nonZero < n && nums[nonZero] == 0) 19 | nonZero += 1; 20 | while (zero < n && nums[zero] != 0) 21 | zero += 1; 22 | } 23 | } 24 | }; 25 | ``` -------------------------------------------------------------------------------- /solution/leetcode/30DayChallenge/7/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day7](https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3289/) 3 | 4 | Tried: 5 | - Basic `binary search` 6 | 7 | ``` c++ 8 | class Solution { 9 | public: 10 | int countElements(vector& arr) { 11 | sort(arr.begin(), arr.end()); 12 | int ans = 0; 13 | for (auto it:arr) { 14 | if (binary_search(arr.begin(), arr.end(), it +1)) 15 | ans += 1; 16 | } 17 | return ans; 18 | } 19 | }; 20 | ``` -------------------------------------------------------------------------------- /solution/leetcode/338.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/counting-bits/ 2 | // solved on Feb28, 2021 3 | 4 | class Solution { 5 | int count_bits(int num) { 6 | int ans = 0; 7 | for (int i = 0; i <= 32; i += 1) { 8 | ans += (num & (1LL << i)) ? 1: 0; 9 | } 10 | return ans; 11 | } 12 | public: 13 | vector countBits(int num) { 14 | vector v(num+1); 15 | for (int i = 0; i <= num; i += 1) 16 | v[i] = count_bits(i); 17 | return v; 18 | } 19 | }; -------------------------------------------------------------------------------- /solution/leetcode/343.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/integer-break/ 2 | 3 | class Solution { 4 | vector dp; 5 | 6 | long long int get(int n) { 7 | if (dp[n] != -1) 8 | return dp[n]; 9 | else if (n < 3) 10 | return n; 11 | dp[n] = n; 12 | for (int i = 1; i < n; i += 1) 13 | dp[n] = max(dp[n], get(n-i)*i); 14 | return dp[n]; 15 | } 16 | 17 | public: 18 | Solution() { 19 | dp.resize(1000001); 20 | fill(dp.begin(), dp.end(), -1); 21 | } 22 | 23 | int integerBreak(int n) { 24 | long long int ans = 0; 25 | for (int i = 1; i < n; i += 1) 26 | ans = max(ans, get(n-i)*i); 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /solution/leetcode/373.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ 2 | 3 | 4 | class Solution: 5 | import heapq 6 | def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: 7 | 8 | queue, pairs = [(nums1[0]+nums2[0], 0, 0)], [] 9 | is_valid = lambda x, y: 0 <= x < len(nums1) and 0 <= y < len(nums2) 10 | 11 | while len(pairs) < k and queue: 12 | _sum, i, j = heapq.heappop(queue) 13 | pairs.append([nums1[i], nums2[j]]) 14 | 15 | if is_valid(i, j+1): 16 | heapq.heappush(queue, (nums1[i]+nums2[j+1], i, j+1)) 17 | if j == 0 and is_valid(i+1, j): 18 | heapq.heappush(queue, (nums1[i+1]+nums2[j], i+1, j)) 19 | 20 | return pairs 21 | -------------------------------------------------------------------------------- /solution/leetcode/376.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/wiggle-subsequence/ 2 | 3 | class Solution { 4 | public: 5 | int wiggleMaxLength(vector& nums) { 6 | int n = nums.size(), ans = 0; 7 | if (n == 0) return 0; 8 | vector> dp(2, vector (n, 0)); 9 | 10 | // dp[1][i]: ending with downward slope at i 11 | // larger number creates an upward slope 12 | for (int i = 1; i < n; i += 1) { 13 | for (int j = 0; j < i; j += 1) { 14 | if (nums[i] > nums[j]) 15 | dp[0][i] = max(dp[0][i], 1 + dp[1][j]); 16 | else if (nums[i] < nums[j]) 17 | dp[1][i] = max(dp[1][i], 1 + dp[0][j]); 18 | } 19 | ans = max({ans, dp[0][i], dp[1][i]}); 20 | } 21 | 22 | return ans + 1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /solution/leetcode/392.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/is-subsequence/ 2 | 3 | class Solution: 4 | def isSubsequence(self, s: str, t: str) -> bool: 5 | s, t = iter(s), iter(t) 6 | for s_i in s: 7 | for t_i in t: 8 | if s_i == t_i: # start comparing s[i+1] 9 | break 10 | else: # if t has been consumed completely 11 | return False 12 | 13 | # if s is fully consumed, return True 14 | # else return False 15 | return True 16 | -------------------------------------------------------------------------------- /solution/leetcode/416.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/partition-equal-subset-sum/description/ 2 | 3 | from functools import lru_cache 4 | 5 | class Solution: 6 | def __init__(self): 7 | self.nums = None 8 | 9 | @lru_cache(None) 10 | def get(self, index, target): 11 | if index >= len(self.nums): 12 | return target == 0 13 | elif target < 0: 14 | return False 15 | return self.get(index+1, target) or self.get(index+1, target - self.nums[index]) 16 | 17 | def canPartition(self, nums: List[int]) -> bool: 18 | if sum(nums) % 2 == 1: 19 | return False 20 | target = sum(nums) / 2 21 | self.nums = nums 22 | 23 | return self.get(0, target) 24 | 25 | -------------------------------------------------------------------------------- /solution/leetcode/46.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/permutations/ 2 | 3 | class Solution: 4 | def permute(self, nums: List[int]) -> List[List[int]]: 5 | permutations = [] 6 | 7 | def recur(cur, more): 8 | if not more: 9 | permutations.append(cur) 10 | 11 | for index, val in enumerate(more): 12 | recur(cur+[val], more[:index]+more[index+1:]) 13 | 14 | recur([], nums) 15 | return permutations -------------------------------------------------------------------------------- /solution/leetcode/48.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-image/ 2 | 3 | class Solution: 4 | def rotate(self, matrix: List[List[int]]) -> None: 5 | """ 6 | Do not return anything, modify matrix in-place instead. 7 | """ 8 | new_matrix = [list(row)[::-1] for row in zip(*matrix)] 9 | matrix[:] = new_matrix 10 | -------------------------------------------------------------------------------- /solution/leetcode/485.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | class Solution { 4 | public: 5 | int findMaxConsecutiveOnes(vector& nums) { 6 | int ans = 0, left = 0, right = 0; 7 | for (int i = 0; i < nums.size(); i += 1) { 8 | if (nums[i] == 0) { 9 | ans = max(ans, right-left); 10 | right = left = i+1; 11 | } 12 | else { 13 | right += 1; 14 | } 15 | } 16 | 17 | ans = max(ans, right-left); 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /solution/leetcode/493.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-pairs/ 2 | 3 | from bisect import bisect_right as upper_bound 4 | 5 | class Solution: 6 | def __init__(self): 7 | self.ans = 0 8 | 9 | def recur(self, nums): 10 | if len(nums) < 2: return nums 11 | 12 | mid = len(nums) // 2 13 | left, right = self.recur(nums[:mid]), self.recur(nums[mid:]) 14 | 15 | for val in right: 16 | index = upper_bound(left, 2 * val) 17 | self.ans += len(left) - index 18 | 19 | return sorted(left + right) 20 | 21 | def reversePairs(self, nums: List[int]) -> int: 22 | if len(nums) < 2: return 0 23 | self.recur(nums) 24 | 25 | 26 | return self.ans 27 | -------------------------------------------------------------------------------- /solution/leetcode/53.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-subarray/ 2 | 3 | from sortedcontainers import SortedList 4 | class Solution: 5 | def maxSubArray(self, nums: List[int]) -> int: 6 | pref = [0 for _ in nums] 7 | window = SortedList([nums[0]]) 8 | ans = nums[0] 9 | pref[0] = nums[0] 10 | 11 | for i, num in enumerate(nums[1:], 1): 12 | pref[i] = pref[i-1] + num 13 | min_sum = window[0] 14 | offset = min_sum if min_sum < 0 else 0 15 | ans = max(ans, pref[i] - offset) 16 | window.add(pref[i]) 17 | 18 | return ans 19 | -------------------------------------------------------------------------------- /solution/leetcode/556.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/next-greater-element-iii/ 2 | 3 | class Solution { 4 | public: 5 | int nextGreaterElement(int n) { 6 | string s = to_string(n); 7 | n = s.size(); map pos; 8 | for (int i = n-1; i > 0; i -= 1) { 9 | pos[s[i]] = i; 10 | if (s[i] > s[i-1]) { 11 | int index = pos.upper_bound(s[i-1])->second; 12 | swap(s[index], s[i-1]); 13 | sort(s.begin()+i, s.end()); 14 | return (stol(s) >= INT_MAX) ? -1: stoi(s); 15 | } 16 | } 17 | return -1; 18 | } 19 | }; -------------------------------------------------------------------------------- /solution/leetcode/595.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/big-countries/description/ 2 | 3 | # Write your MySQL query statement below 4 | select name, population, area from world where area >= 3000000 or population >= 25000000; 5 | -------------------------------------------------------------------------------- /solution/leetcode/60.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutation-sequence/ 2 | // Basic Iteration with good logic 3 | // Time: O(nlogn) Space: O(n) 4 | 5 | class Solution { 6 | public: 7 | string getPermutation(int n, int k) { 8 | vector fact(10, 1); 9 | for (int i = 1; i < fact.size(); i += 1) 10 | fact[i] = i * fact[i-1]; 11 | 12 | vector nums(n); 13 | iota(nums.begin(), nums.end(), 1); 14 | 15 | set st(nums.begin(), nums.end()); 16 | 17 | for (int i = 0; i < n; i += 1) { 18 | int dist = n-1-i; 19 | for (auto val: st) { 20 | if (fact[dist] < k) 21 | k -= fact[dist]; 22 | else { 23 | nums[i] = val; 24 | st.erase(val); 25 | break; 26 | } 27 | } 28 | } 29 | 30 | string s; 31 | for (auto num: nums) 32 | s += to_string(num); 33 | 34 | return s; 35 | } 36 | }; -------------------------------------------------------------------------------- /solution/leetcode/62.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-paths/description/ 2 | 3 | class Solution: 4 | def uniquePaths(self, m: int, n: int) -> int: 5 | dp = [[0 for _ in range(n+1)] for _ in range(m+1)] 6 | 7 | for i in range(1, m+1): 8 | for j in range(1, n+1): 9 | if i == 1 and j == 1: 10 | dp[i][j] = 1 11 | continue 12 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 13 | return dp[-1][-1] 14 | 15 | 16 | -------------------------------------------------------------------------------- /solution/leetcode/654.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-binary-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: 11 | if not nums: 12 | return None 13 | val = max(nums) 14 | index = nums.index(val) 15 | 16 | return TreeNode(val, self.constructMaximumBinaryTree(nums[:index]), self.constructMaximumBinaryTree(nums[index+1:])) -------------------------------------------------------------------------------- /solution/leetcode/657.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/robot-return-to-origin/description/ 2 | 3 | class Solution: 4 | def judgeCircle(self, moves: str) -> bool: 5 | move_mapping = { 6 | 'L': (-1, 0), 7 | 'R': (1, 0), 8 | 'U': (0, 1), 9 | 'D': (0, -1) 10 | } 11 | 12 | position = [0, 0] 13 | for move in moves: 14 | x, y = move_mapping[move] 15 | position = [position[0] + x, position[1] + y] 16 | 17 | return position == [0, 0] 18 | -------------------------------------------------------------------------------- /solution/leetcode/658.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-k-closest-elements/description/ 2 | 3 | import heapq 4 | 5 | class Solution: 6 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 7 | closest = [] 8 | for num in arr: 9 | dist = abs(x - num) 10 | heapq.heappush(closest, (-dist, -num)) 11 | if len(closest) > k: 12 | heapq.heappop(closest) 13 | 14 | return sorted([-num[1] for num in closest]) 15 | -------------------------------------------------------------------------------- /solution/leetcode/70.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs/ 2 | # Fibonachi based easy DP 3 | 4 | class Solution: 5 | def climbStairs(self, n: int) -> int: 6 | dp = [0 for _ in range(n+1)] 7 | dp[1:3] = [1, 1] 8 | for i in range(3, n+1): 9 | dp[i] = dp[i-1] + dp[i-2] 10 | 11 | return dp[n] 12 | -------------------------------------------------------------------------------- /solution/leetcode/72.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/edit-distance/ 2 | 3 | class Solution: 4 | from functools import lru_cache 5 | 6 | @lru_cache 7 | def edit(self, i, j): 8 | if i == len(self.w1): 9 | return len(self.w2) - j 10 | elif j == len(self.w2): 11 | return len(self.w1) - i 12 | if self.w1[i] == self.w2[j]: 13 | return self.edit(i+1, j+1) 14 | else: 15 | return 1 + min(self.edit(i+1, j), self.edit(i, j+1), self.edit(i+1, j+1)) 16 | 17 | def minDistance(self, word1: str, word2: str) -> int: 18 | self.w1 = word1 19 | self.w2 = word2 20 | return self.edit(0, 0) -------------------------------------------------------------------------------- /solution/leetcode/736.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/partition-labels/ 2 | 3 | class Solution: 4 | def partitionLabels(self, S: str) -> List[int]: 5 | index, sizes = dict(), [] 6 | # print(len(S)) 7 | 8 | for i, val in reversed(list(enumerate(S))): 9 | if val not in index: 10 | index[val] = i 11 | 12 | left, cur, right = 0, 0, 0 13 | while left < len(S): 14 | right = max(right, index[S[left]]) 15 | cur += 1 16 | if left == right: 17 | sizes.append(cur) 18 | right, cur = right + 1, 0 19 | left += 1 20 | return sizes 21 | -------------------------------------------------------------------------------- /solution/leetcode/746.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/min-cost-climbing-stairs/ 2 | # Simple Dynamic Programming based solution 3 | # solved again on Feb28, 2021 4 | 5 | class Solution: 6 | def minCostClimbingStairs(self, cost: List[int]) -> int: 7 | dp = [0 for _ in cost] 8 | dp[-1], dp[-2] = cost[-1], cost[-2] 9 | 10 | # iterate from end, with index 11 | for index, val in reversed(list(enumerate(cost[:-2]))): 12 | dp[index] = val + min(dp[index+1], dp[index+2]) 13 | 14 | return min(dp[:2]) -------------------------------------------------------------------------------- /solution/leetcode/771.js: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jewels-and-stones/ 2 | 3 | /** 4 | * @param {string} J 5 | * @param {string} S 6 | * @return {number} 7 | */ 8 | var numJewelsInStones = function(J, S) { 9 | J = Array.from(J); S = Array.from(S); 10 | return J.reduce((prev, val) => prev + S.filter(x => x === val).length, 0) 11 | }; 12 | -------------------------------------------------------------------------------- /solution/leetcode/78.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/109/backtracking/796/ 2 | 3 | class Solution: 4 | def subsets(self, nums: List[int]) -> List[List[int]]: 5 | if len(nums) == 0: 6 | return [] 7 | elif len(nums) == 1: 8 | return [nums, []] 9 | others = self.subsets(nums[1:]) 10 | return [[nums[0]]+sub for sub in others] + others 11 | -------------------------------------------------------------------------------- /solution/leetcode/841.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/keys-and-rooms/ 2 | 3 | class Solution { 4 | void dfs(int node, vector &vis, vector>& rooms) { 5 | if (vis[node]) 6 | return; 7 | vis[node] = true; 8 | for (auto child: rooms[node]) 9 | dfs(child, vis, rooms); 10 | } 11 | 12 | public: 13 | bool canVisitAllRooms(vector>& rooms) { 14 | int n = rooms.size(); 15 | vector vis(n, false); 16 | 17 | dfs(0, vis, rooms); 18 | return all_of(vis.begin(), vis.end(), [](bool x) {return x;}); 19 | } 20 | }; -------------------------------------------------------------------------------- /solution/leetcode/853.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/car-fleet/ 2 | 3 | class Solution: 4 | def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: 5 | tups = list(zip(position, speed)) 6 | tups.sort() 7 | time_req = [(target-_position)/ _speed for _position, _speed in tups] 8 | _max_val = -2 9 | _st = set() 10 | 11 | for req in reversed(time_req): 12 | if req <= _max_val: 13 | continue 14 | _st.add(req) 15 | _max_val = req 16 | 17 | return len(_st) 18 | -------------------------------------------------------------------------------- /solution/leetcode/901.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/online-stock-span/ 2 | 3 | class StockSpanner: 4 | 5 | def __init__(self): 6 | self.stack = [] 7 | self.prices = [] 8 | 9 | def next(self, price: int) -> int: 10 | self.prices.append(price) 11 | while self.stack and self.prices[self.stack[-1]] <= price: 12 | self.stack.pop() 13 | self.stack.append(len(self.prices) - 1) 14 | 15 | if len(self.stack) == 1: 16 | return len(self.prices) 17 | return len(self.prices) - self.stack[-2] - 1 18 | 19 | 20 | # Your StockSpanner object will be instantiated and called as such: 21 | # obj = StockSpanner() 22 | # param_1 = obj.next(price) -------------------------------------------------------------------------------- /solution/leetcode/91.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/decode-ways/description/ 2 | 3 | from functools import lru_cache 4 | 5 | class Solution: 6 | def __init__(self): 7 | self.s = None 8 | self.mappings = dict() 9 | for index, val in enumerate('abcdefghijklmnopqrstuvwxyz', 1): 10 | self.mappings[str(index)] = val 11 | 12 | @lru_cache(None) 13 | def get(self, i): 14 | if i >= len(self.s): 15 | return 1 16 | elif self.s[i] == '0': 17 | return 0 18 | ans = self.get(i+1) 19 | if i+1 < len(self.s) and self.s[i:i+2] in self.mappings: 20 | ans += self.get(i+2) 21 | return ans 22 | 23 | def numDecodings(self, s: str) -> int: 24 | self.s = s 25 | return self.get(0) 26 | -------------------------------------------------------------------------------- /solution/leetcode/921.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 2 | // Time: O(n), Space: O(1) 3 | 4 | class Solution { 5 | public: 6 | int minAddToMakeValid(string s) { 7 | int n = s.size(), _count = 0, ans = 0; 8 | 9 | // when the seq becomes invalid, add corresponding 10 | // parenthesis and make it valid 11 | for (auto ch: s) { 12 | _count += (ch == '('? 1 : -1); 13 | if (_count < 0) { 14 | ans += 1; 15 | _count = 0; 16 | } 17 | } 18 | 19 | return ans + abs(_count); 20 | } 21 | }; -------------------------------------------------------------------------------- /solution/leetcode/946.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/validate-stack-sequences/ 2 | // Time: O(N), Space: O(N), Two Pointers 3 | 4 | class Solution { 5 | public: 6 | bool validateStackSequences(vector& pushed, vector& popped) { 7 | stack stk; 8 | int l = 0, r = 0; 9 | while (l < pushed.size()) { 10 | while (!stk.empty() && r < popped.size() && stk.top() == popped[r]) { 11 | r += 1; stk.pop(); 12 | } 13 | 14 | stk.push(pushed[l]); 15 | l += 1; 16 | } 17 | 18 | while (r < popped.size() && stk.empty() == false && stk.top() == popped[r]) { 19 | stk.pop(); r += 1; 20 | } 21 | 22 | return stk.empty(); 23 | } 24 | }; -------------------------------------------------------------------------------- /solution/leetcode/950.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reveal-cards-in-increasing-order/ 2 | 3 | class Solution { 4 | public: 5 | vector deckRevealedIncreasing(vector& deck) { 6 | int n = deck.size(), j = 0; 7 | sort(deck.begin(), deck.end()); 8 | vector ans(n); 9 | deque dq; 10 | 11 | for (int i = 0; i < n; i += 1) 12 | dq.push_back(i); 13 | 14 | while (!dq.empty()) { 15 | int i = dq.front(); 16 | dq.pop_front(); 17 | ans[i] = deck[j]; 18 | j += 1; 19 | 20 | if (!dq.empty()) { 21 | dq.push_back(dq.front()); 22 | dq.pop_front(); 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /solution/leetcode/96.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-binary-search-trees/ 2 | 3 | class Solution { 4 | public: 5 | int numTrees(int n) { 6 | // (a C b) : number of ways of selecting 'a' from 'b' 7 | #define ll long long int 8 | 9 | // number of unique bst = catalan number = (1/(n+1))*(2n C n) 10 | vector< vector > dp (n+1, vector (2*n +1, 0)); 11 | 12 | for (int j = 1; j <= 2*n; j += 1) { 13 | for (int i = 1; i <= min(n,j); i += 1) { 14 | // dp[i][j] = (j C i) 15 | if (i == 1) { 16 | dp[i][j] = j; 17 | continue; 18 | } 19 | dp[i][j] = dp[i][j-1] + dp[i-1][j-1]; 20 | } 21 | } 22 | 23 | return dp[n][2*n]/(n+1); 24 | } 25 | }; -------------------------------------------------------------------------------- /solution/leetcode/AugChallenge/1/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 1](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3409/) 3 | 4 | Tried: 5 | - Simple `Brute Force`. 6 | 7 | 8 | ```python 9 | class Solution: 10 | def detectCapitalUse(self, word: str) -> bool: 11 | return any([word == word.upper(), word == word.lower(), word == word.capitalize()]) 12 | ``` 13 | -------------------------------------------------------------------------------- /solution/leetcode/Blind_75_Leetcode_Questions.md: -------------------------------------------------------------------------------- 1 | Link: [Leetcode](https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions) 2 | 3 | Array: 4 | - [x] Two Sum 5 | - [x] Best Time to Buy and Sell Stock 6 | - [x] Contains duplicate 7 | - [x] Product of Array Except Self 8 | - [x] Maximum Subarray 9 | - [ ] Maximum Product Subarray 10 | - [ ] Find Minimum in Rotated Sorted Array 11 | - [ ] Search in Rotated Sorted Array 12 | - [ ] 3 Sum 13 | - [ ] Container With Most Water -------------------------------------------------------------------------------- /solution/leetcode/FebChallenge2021/1/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day1](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/) 3 | 4 | Tried: 5 | - Convert int to binary string 6 | 7 | ``` python 8 | class Solution: 9 | def hammingWeight(self, n: int) -> int: 10 | s = bin(n)[2:] 11 | return s.count('1') 12 | 13 | ``` -------------------------------------------------------------------------------- /solution/leetcode/FebChallenge2021/2/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day2](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3626/) 3 | 4 | Tried: 5 | - Recursive tree traversal 6 | 7 | ``` python 8 | class Solution: 9 | def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: 10 | if not root: 11 | return None 12 | elif low <= root.val <= high: 13 | root.left = self.trimBST(root.left, low, high) 14 | root.right = self.trimBST(root.right, low, high) 15 | return root 16 | elif low > root.val: 17 | return self.trimBST(root.right, low, high) 18 | else: # high < root.val 19 | return self.trimBST(root.left, low, high) 20 | ``` -------------------------------------------------------------------------------- /solution/leetcode/FebChallenge2021/9/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day9](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3634/) 3 | 4 | Tried: 5 | - Tree Traversal 6 | 7 | ``` python 8 | class Solution: 9 | def convertBST(self, root: TreeNode) -> TreeNode: 10 | self.convertBST1(root) 11 | return root 12 | 13 | def convertBST1(self, root: TreeNode, carry=0) -> TreeNode: 14 | if not root: 15 | return 0 16 | right = self.convertBST1(root.right, carry) 17 | left = self.convertBST1(root.left, carry+root.val+right) 18 | 19 | sum = left + right + root.val 20 | root.val += right + carry 21 | 22 | return sum 23 | 24 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/1/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day1](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3589/) 3 | 4 | Tried: 5 | - Simple Recursive Bruteforce solution 6 | - Can be probably solved using Trie, as all nums are distinct 7 | 8 | ``` python 9 | class Solution: 10 | def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: 11 | if not arr: 12 | return True 13 | 14 | for piece in pieces: 15 | n = len(piece) 16 | if n <= len(arr) and arr[:n] == piece: 17 | return self.canFormArray(arr[n:], pieces) 18 | 19 | return False 20 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/15/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day15](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3605/) 3 | 4 | Tried: 5 | - simple implementation 6 | 7 | ``` python 8 | class Solution: 9 | def getMaximumGenerated(self, n: int) -> int: 10 | nums = [0 for _ in range(2*n+3)] 11 | nums[:2] = [0, 1] 12 | 13 | for i in range(n+1): 14 | if 2 <= 2*i <= n: 15 | nums[2*i] = nums[i] 16 | if 2 <= 2*i + 1 <= n: 17 | nums[2*i+1] = nums[i] + nums[i+1] 18 | 19 | return max(nums[:n+1]) 20 | 21 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/20/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day20](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3610/) 3 | 4 | Tried: 5 | - Simple stack based solution 6 | - Time: O(n), space: O(n) 7 | 8 | ``` python 9 | class Solution: 10 | def isValid(self, s: str) -> bool: 11 | from collections import deque 12 | stack = deque([]) 13 | counter_part = { 14 | '(': ')', 15 | '{': '}', 16 | '[': ']' 17 | } 18 | 19 | for ch in s: 20 | if ch in ['(', '{', '[']: 21 | stack.append(ch) 22 | elif not stack: #stack is empty 23 | return False 24 | else: 25 | top = stack.pop() 26 | if ch != counter_part[top]: 27 | return False 28 | return not stack 29 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/21/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day21](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3611/) 3 | 4 | Tried: 5 | - stack based concept to find next greater number 6 | - Help from editorial 7 | 8 | ``` python 9 | class Solution: 10 | def mostCompetitive(self, nums: List[int], k: int) -> List[int]: 11 | from collections import deque 12 | stack = [] 13 | 14 | for index, num in enumerate(nums): 15 | if not stack or num >= stack[-1]: 16 | stack.append(num) 17 | else: 18 | while stack and len(stack) + (len(nums) - index) > k and stack[-1] > num: 19 | stack.pop() 20 | stack.append(num) 21 | return stack[:k] 22 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/22/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day22](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3613/) 3 | 4 | Tried: 5 | - Bruteforce solution 6 | 7 | ``` python 8 | class Solution: 9 | def closeStrings(self, word1: str, word2: str) -> bool: 10 | if set(word1) != set(word2): 11 | return False 12 | from collections import Counter 13 | w1 = Counter(word1).values() 14 | w2 = Counter(word2).values() 15 | return sorted(w1) == sorted(w2) 16 | 17 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/25/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day25](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3616/) 3 | 4 | Tried: 5 | - Linear time constant space, single pass 6 | 7 | ``` python 8 | class Solution: 9 | def kLengthApart(self, nums: List[int], k: int) -> bool: 10 | from math import inf 11 | last = -inf 12 | for index, val in enumerate(nums): 13 | if val != 1: 14 | continue 15 | if index - last <= k: 16 | return False 17 | last = index 18 | return True 19 | 20 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/4/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day4](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3592/) 3 | 4 | Tried: 5 | - Simple Recursive solution 6 | 7 | ``` python 8 | class Solution: 9 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 10 | ''' Recursively merges the two LinkedLists ''' 11 | if not all([l1, l2]): 12 | return l1 if not l2 else l2 13 | 14 | if l1.val < l2.val: 15 | l2, l1 = l1, l2 16 | 17 | # now, l2.val <= l1.val 18 | l2.next = self.mergeTwoLists(l1, l2.next) 19 | return l2 20 | 21 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/6/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day6](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3594/) 3 | 4 | Tried: 5 | - Linear Time, Constant Space, Single Pass 6 | 7 | ``` python 8 | class Solution: 9 | def findKthPositive(self, arr: List[int], k: int) -> int: 10 | lastNum = 0 11 | 12 | for index, val in enumerate(arr): 13 | if k > val - lastNum - 1: 14 | k -= (val - lastNum - 1) 15 | else: 16 | return lastNum + k 17 | lastNum = val 18 | return arr[-1] + k 19 | 20 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/7/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day7](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3595/) 3 | 4 | Tried: 5 | - Linear Time, Two pointers, Single Pass 6 | - Space: O(num of diff chars) 7 | 8 | ``` python 9 | class Solution: 10 | def lengthOfLongestSubstring(self, s: str) -> int: 11 | longest, left, chars = 0, 0, set() 12 | 13 | for right, char in enumerate(s): 14 | while char in chars: 15 | chars.discard(s[left]) 16 | left += 1 17 | chars.add(char) 18 | longest = max(longest, len(chars)) 19 | 20 | return longest 21 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JanChallenge2021/8/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day8](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/580/week-2-january-8th-january-14th/3597/) 3 | 4 | Tried: 5 | - Simple Bruteforce 6 | 7 | ``` python 8 | class Solution: 9 | def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: 10 | return ''.join(word1) == ''.join(word2) 11 | 12 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JulyChallenge/1/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 1](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3377/) 3 | 4 | Tried: 5 | - Simple `Brute Force`. 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | int arrangeCoins(int n) { 12 | int _count = 0; 13 | for (int i = 1; i <= n; i += 1) { 14 | _count += 1; 15 | n -= i; 16 | } 17 | 18 | return _count; 19 | } 20 | }; 21 | ``` 22 | -------------------------------------------------------------------------------- /solution/leetcode/JulyChallenge/4/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 4](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3381/) 3 | 4 | Tried: 5 | - Simple `Bit Manipulation` 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | int hammingDistance(int x, int y) { 12 | int _count = 0; 13 | for (int i = 0; i < 32; i += 1) 14 | _count += (((x & (1 << i)) ^ (y & (1 << i))) > 0 ? 1: 0); 15 | 16 | return _count; 17 | } 18 | }; 19 | ``` 20 | -------------------------------------------------------------------------------- /solution/leetcode/JulyChallenge/5/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 5](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3382/) 3 | 4 | Tried: 5 | - Simple `Brute Force` 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | vector plusOne(vector& digits) { 12 | int carry = 1, n = digits.size(); 13 | vector sum(n, 0); 14 | for (int i = n-1; i >= 0; i -= 1) { 15 | int cur = digits[i] + carry; 16 | carry = cur/ 10; 17 | sum[i] = cur % 10; 18 | } 19 | 20 | if (carry > 0) 21 | sum.insert(sum.begin(), 1); 22 | 23 | return sum; 24 | } 25 | }; 26 | ``` 27 | -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/10/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 10](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3356/) 3 | 4 | Tried: 5 | - Simple `Binary Search` 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | int searchInsert(vector& nums, int target) { 12 | if (nums.empty()) return 0; 13 | else if (target > nums.back()) return nums.size(); 14 | return upper_bound(nums.begin(), nums.end(), target) - nums.begin() - binary_search(nums.begin(), nums.end(), target); 15 | } 16 | }; 17 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/2/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 2](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3348/) 3 | 4 | Tried: 5 | - Simple `Linked List Reversal` 6 | 7 | 8 | ```c++ 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | void deleteNode(ListNode* node) { 20 | ListNode* par=node; 21 | ListNode* var=node->next; 22 | while(var->next!=nullptr){ 23 | par->val = var->val; 24 | par = par->next; 25 | var = var->next; 26 | } 27 | par->val = var->val; 28 | par->next = nullptr; 29 | } 30 | }; 31 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/27/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 27](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/542/week-4-june-22nd-june-28th/3373/) 3 | 4 | Tried: 5 | - Simple `Dynamic Programming` 6 | 7 | ```c++ 8 | class Solution { 9 | int recur(int n, vector &dp) { 10 | if (n < 0) 11 | return 1e7; 12 | else if (dp[n] != -1) 13 | return dp[n]; 14 | dp[n] = 1e7; 15 | for (int i = 1; i*i <= n; i += 1) 16 | dp[n] = min(dp[n], 1+recur(n-i*i, dp)); 17 | return dp[n]; 18 | } 19 | 20 | public: 21 | int numSquares(int n) { 22 | vector dp(n+3, -1); 23 | dp[0] = 0; dp[1] = 1; dp[2] = 2; 24 | return recur(n, dp); 25 | } 26 | }; 27 | ``` 28 | -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/4/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 4](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3350/) 3 | 4 | Tried: 5 | - Nothing 6 | 7 | 8 | ```python 9 | class Solution: 10 | def reverseString(self, s: List[str]) -> None: 11 | """ 12 | Do not return anything, modify s in-place instead. 13 | """ 14 | s.reverse() 15 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/8/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 8](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3354/) 3 | 4 | Tried: 5 | - Standard `bitset` 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | bool isPowerOfTwo(int n) { 12 | return (__builtin_popcount(n) == 1) && (n > 0); 13 | } 14 | }; 15 | ``` -------------------------------------------------------------------------------- /solution/leetcode/JuneChallenge/9/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 9](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3355/) 3 | 4 | Tried: 5 | - Standard `Recursion`, similar to `Dp` 6 | 7 | 8 | ```c++ 9 | class Solution { 10 | public: 11 | bool isSubsequence(string s, string t) { 12 | if (s.size() == 0) 13 | return true; 14 | else if (t.size() == 0) 15 | return false; 16 | if (s[0] == t[0]) 17 | return isSubsequence(s.substr(1), t.substr(1)); 18 | return isSubsequence(s, t.substr(1)); 19 | } 20 | }; 21 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/1/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 1](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3316/) 3 | 4 | Tried: 5 | - Simple `Binary Search` based solution. 6 | 7 | 8 | ```python 9 | # The isBadVersion API is already defined for you. 10 | # @param version, an integer 11 | # @return a bool 12 | # def isBadVersion(version): 13 | 14 | class Solution: 15 | def firstBadVersion(self, n): 16 | """ 17 | :type n: int 18 | :rtype: int 19 | """ 20 | low, high = 1, n 21 | while low < high: 22 | mid = (low + high)//2 23 | if isBadVersion(mid): 24 | high = mid 25 | else: 26 | low = mid + 1 27 | return low 28 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/10/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 10](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3325/) 3 | 4 | Tried: 5 | - Used basic `graph representation` 6 | 7 | ```python 8 | class Solution: 9 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 10 | if n == 1: 11 | return 1 if len(trust) == 0 else -1 12 | indegree = [0 for _ in range(n+1)] 13 | outdegree = [0 for _ in range(n+1)] 14 | for u, v in trust: 15 | indegree[v] += 1 16 | outdegree[u] += 1 17 | if indegree.count(max(indegree)) != 1: 18 | return -1 19 | elif max(indegree) != n-1: 20 | return -1 21 | index = indegree.index(max(indegree)) 22 | return -1 if outdegree[index] else index 23 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/2/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 2](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3317/) 3 | 4 | Tried: 5 | - Use of `dict` or `map` 6 | 7 | 8 | ```python 9 | class Solution: 10 | def numJewelsInStones(self, J: str, S: str) -> int: 11 | from collections import Counter 12 | freq = dict(Counter(S)) 13 | return sum(freq.get(j, 0) for j in J) 14 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/21/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 21](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/536/week-3-may-15th-may-21st/3336/) 3 | 4 | Tried: 5 | - Used DP 6 | 7 | ```python 8 | class Solution: 9 | def countSquares(self, matrix: List[List[int]]) -> int: 10 | n, m = len(matrix), len(matrix[0]) 11 | isValid = lambda x, y: 0 <= x < n and 0 <= y < m 12 | 13 | dp = [[0 for _ in range(m)] for __ in range(n)] 14 | for i, row in enumerate(matrix): 15 | for j, element in enumerate(row): 16 | if element == 0: 17 | continue 18 | dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) 19 | 20 | return sum(map(sum, dp)) 21 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/28/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 28](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/537/week-4-may-22nd-may-28th/3343/) 3 | 4 | Tried: 5 | - Used simple bit manipulation 6 | 7 | ```c++ 8 | class Solution { 9 | int count_bits(int num) { 10 | int ans = 0; 11 | for (int i = 0; i <= 32; i += 1) { 12 | ans += (num & (1LL << i)) ? 1: 0; 13 | } 14 | return ans; 15 | } 16 | public: 17 | vector countBits(int num) { 18 | vector v(num+1); 19 | for (int i = 0; i <= num; i += 1) 20 | v[i] = count_bits(i); 21 | return v; 22 | } 23 | }; 24 | ``` -------------------------------------------------------------------------------- /solution/leetcode/MayChallenge/5/solution.md: -------------------------------------------------------------------------------- 1 | Problem: 2 | - [Day 5](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3320/) 3 | 4 | Tried: 5 | - Simple use of `Dictonary` of `Hash Map` 6 | 7 | ```python 8 | class Solution: 9 | def firstUniqChar(self, s: str) -> int: 10 | from collections import Counter 11 | freq, n = Counter(s), len(s) 12 | 13 | for index, ch in enumerate(s): 14 | if freq[ch] == 1: 15 | return index 16 | 17 | return -1 18 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Biweekly21/1371.md: -------------------------------------------------------------------------------- 1 | * Couldn't solve during contest 2 | * Idea taken from discussion fourm 3 | * Added in todo list 4 | 5 | ``` c++ 6 | class Solution { 7 | public: 8 | int findTheLongestSubstring(string s) { 9 | map mp = {{'a',1}, {'e',2}, {'i',4}, {'o',16}, {'u',32}}; 10 | string alp = "aeiou"; 11 | int cur = 0, n = s.size(), ans = 0; map > fk = {{0,{-1,0}}}; 12 | 13 | for (int i = 0; i < n; i += 1) { 14 | if (alp.find(s[i]) != string::npos) 15 | cur ^= mp[s[i]]; 16 | if (fk.find(cur) == fk.end()) 17 | fk[cur] = {i, i}; 18 | fk[cur].second = i; 19 | 20 | ans = max(ans, fk[cur].second - fk[cur].first); 21 | } 22 | return ans; 23 | } 24 | }; 25 | 26 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Biweekly21/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Biweekly 21](https://leetcode.com/contest/biweekly-contest-21) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 348 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 0 10 | 11 | * Remarks:   `The contest is good. Some practice can make land at better place.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Biweekly25/1431.md: -------------------------------------------------------------------------------- 1 | * Easy :) 2 | 3 | ```c++ 4 | class Solution { 5 | public: 6 | vector kidsWithCandies(vector& candies, int extraCandies) { 7 | int n = candies.size(), largest = *max_element(candies.begin(), candies.end()); 8 | vector ans(n); 9 | for (int i = 0; i < n; i += 1) { 10 | if (candies[i] + extraCandies >= largest) 11 | ans[i] = true; 12 | else 13 | ans[i] = false; 14 | } 15 | return ans; 16 | } 17 | }; 18 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Biweekly25/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Biweekly 52](https://leetcode.com/contest/biweekly-contest-25) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 164 6 | 7 | * Number of upsolve: 0 8 | 9 | * Total Remaining: 0 10 | 11 | * Remarks:   `It was awesome. Problems were easy. Last one was based on bitmask + knapsack dp. I can't belive I solved it within time.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly148/1147.md: -------------------------------------------------------------------------------- 1 | * Yet to upsolve @_@ -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly148/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 148](https://leetcode.com/contest/weekly-contest-148) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 1072 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 1 10 | 11 | * Remarks:   `Problems were really interesting. Enjoyed alot solving them ^_^` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly149/1154.md: -------------------------------------------------------------------------------- 1 | * Simple Brute Force 2 | 3 | ```c++ 4 | class Solution { 5 | public: 6 | int dayOfYear(string date) { 7 | // 2004-03-01 8 | int year = 0, month = 0, day = 0, ans = 0; 9 | year = stoi(date.substr(0, 4)); 10 | month = stoi(date.substr(5, 2))-1; 11 | day = stoi(date.substr(8, 2)); 12 | 13 | vector numOfDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 14 | if (year % 4 == 0 && year % 100 != 0) 15 | numOfDays[1] += 1; 16 | 17 | for (int i = 0; i < month; i += 1) 18 | ans += numOfDays[i]; 19 | ans += day; 20 | 21 | return ans; 22 | } 23 | }; 24 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly149/1157.md: -------------------------------------------------------------------------------- 1 | * Problem involving `Segment Tree`. Couldn't complete within time. -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly149/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 149](https://leetcode.com/contest/weekly-contest-149) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 213 6 | 7 | * Number of upsolve: 0 8 | 9 | * Total Remaining: 1 10 | 11 | * Remarks:   `Was fun solving. Seems Segment Tree should be avoided on leetcode.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly150/1160.md: -------------------------------------------------------------------------------- 1 | * Simple brute-force 2 | 3 | ``` c++ 4 | class Solution { 5 | public: 6 | int in(string &pat, string &text) { 7 | // search pat in text 8 | map freq_text, freq_pat; 9 | for (auto ch: text) 10 | freq_text[ch] += 1; 11 | for (auto ch:pat) { 12 | if (freq_text[ch] <= 0) 13 | return 0; 14 | else 15 | freq_text[ch] -= 1; 16 | } 17 | return pat.size(); 18 | } 19 | 20 | int countCharacters(vector& words, string chars) { 21 | int count = 0; 22 | for (auto word: words) { 23 | count += in(word, chars); 24 | } 25 | 26 | return count; 27 | } 28 | }; 29 | 30 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly150/1162.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/solution/leetcode/contests/Weekly150/1162.md -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly150/1163.md: -------------------------------------------------------------------------------- 1 | * Good question. Solved using Discussion fourm 2 | * Added in todo list 3 | * nlog2n suffix array solution passed [23/24](https://leetcode.com/submissions/detail/322103552/) test cases 4 | 5 | ``` c++ 6 | class Solution { 7 | public: 8 | string lastSubstring(string s) { 9 | int i = 0, j = 1, n = s.size(), k = 0; 10 | while(j + k < n) { 11 | if (s[i+k] == s[j+k]) 12 | k += 1; 13 | else if (s[i+k] > s[j+k]) { 14 | j = j + k + 1; 15 | k = 0; 16 | } 17 | else { 18 | i = j; 19 | j += 1; 20 | k = 0; 21 | } 22 | } 23 | return s.substr(i); 24 | } 25 | }; 26 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly150/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 150](https://leetcode.com/contest/weekly-contest-150) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 1485 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 1 10 | 11 | * Remarks:   `Mmmmm. Need to improve on good set of questions.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly183/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 183](https://leetcode.com/contest/weekly-contest-183) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 2696 6 | 7 | * Number of upsolve: 2 8 | 9 | * Total Remaining: 0 10 | 11 | * Remarks:   `Leaving practice can be dangerous ^_^` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly84/832.md: -------------------------------------------------------------------------------- 1 | * Too simple to say 2 | 3 | ``` c++ 4 | class Solution { 5 | public: 6 | vector> flipAndInvertImage(vector>& A) { 7 | for (auto &row:A) { 8 | reverse(row.begin(), row.end()); 9 | } 10 | 11 | for (auto &row:A) { 12 | for (auto &element:row) 13 | element = 1 - element; 14 | } 15 | 16 | return A; 17 | } 18 | }; 19 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly84/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 84](https://leetcode.com/contest/weekly-contest-84) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 48 6 | 7 | * Number of upsolve: 0 8 | 9 | * Total Remaining: 0 10 | 11 | * Remarks:   `Seriously I had seen similar questions before.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly87/844.md: -------------------------------------------------------------------------------- 1 | * Ahh.... One of the very good problems based on `stack` 2 | 3 | ``` c++ 4 | class Solution { 5 | public: 6 | bool backspaceCompare(string s, string t) { 7 | stack stackForS, stackForT; 8 | for (auto it:s) { 9 | if (it == '#') { 10 | if (!stackForS.empty()) 11 | stackForS.pop(); 12 | } 13 | else 14 | stackForS.push(it); 15 | } 16 | 17 | for (auto it:t) { 18 | if (it == '#') { 19 | if (!stackForT.empty()) 20 | stackForT.pop(); 21 | } 22 | else 23 | stackForT.push(it); 24 | } 25 | 26 | return stackForS == stackForT; 27 | } 28 | }; 29 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly87/845.md: -------------------------------------------------------------------------------- 1 | * It was a standard problem 2 | 3 | ``` c++ 4 | class Solution { 5 | public: 6 | int longestMountain(vector& A) { 7 | int n = A.size(); 8 | 9 | vector lengthDecr(n, 0); 10 | for (int i = n-2; i >= 0; i -= 1) { 11 | if (A[i] > A[i+1]) 12 | lengthDecr[i] = 1 + lengthDecr[i+1]; 13 | } 14 | 15 | int cur = 1, ans = 0; 16 | for (int i = 1; i+1 < n; i += 1) { 17 | if (A[i] > A[i-1]){ 18 | cur += 1; 19 | if (lengthDecr[i]) 20 | ans = max(ans, cur + lengthDecr[i]); 21 | } 22 | else 23 | cur = 1; 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly87/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 87](https://leetcode.com/contest/weekly-contest-87) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 241 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 0 10 | 11 | * Remarks:   `Wow ! Last one was a great question. Giving these contests are surely going to help everyone.` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly89/852.md: -------------------------------------------------------------------------------- 1 | 2 | ```c++ 3 | class Solution { 4 | public: 5 | int peakIndexInMountainArray(vector& A) { 6 | int n = A.size(); 7 | for (int i = 1; i+1 < n; i += 1) { 8 | if (A[i-1] < A[i] && A[i] > A[i+1]) 9 | return i; 10 | } 11 | return 2; 12 | } 13 | }; 14 | ``` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly89/854.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/solution/leetcode/contests/Weekly89/854.md -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly89/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 89](https://leetcode.com/contest/weekly-contest-89) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 426 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 1 10 | 11 | * Remarks:   `Problems were good. Keep Working %^_^%` -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly91/861.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/solution/leetcode/contests/Weekly91/861.md -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly91/862.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/harshraj22/problem_solving/d47c9d65dded316470f1800e697459cabb889fb2/solution/leetcode/contests/Weekly91/862.md -------------------------------------------------------------------------------- /solution/leetcode/contests/Weekly91/README.md: -------------------------------------------------------------------------------- 1 | * Contest Link: [Weekly 91](https://leetcode.com/contest/weekly-contest-91) 2 | 3 | * Contest type: Virtual 4 | 5 | * Contest Rank: 1030 6 | 7 | * Number of upsolve: 1 8 | 9 | * Total Remaining: 2 10 | 11 | * Remarks:   `Use bad tricks if required to get AC` -------------------------------------------------------------------------------- /solution/lintcode/1913.sql: -------------------------------------------------------------------------------- 1 | -- https://www.lintcode.com/problem/1913/?showListFe=true&page=1&problemTypeId=3&ordering=level&pageSize=50 2 | 3 | -- Write your SQL Query here -- 4 | -- example: SELECT * FROM XX_TABLE WHERE XXX -- 5 | SELECT student_name, phone, hometown, address FROM students left join enrollments on students.id = enrollments.student_id -------------------------------------------------------------------------------- /solution/lintcode/1920.sql: -------------------------------------------------------------------------------- 1 | -- https://www.lintcode.com/problem/1920/?showListFe=true&page=1&problemTypeId=3&ordering=level&pageSize=50 2 | 3 | -- Write your SQL Query here -- 4 | -- example: SELECT * FROM XX_TABLE WHERE XXX -- 5 | SELECT name FROM students group by name having count(id) > 1 -------------------------------------------------------------------------------- /solution/lintcode/1921.sql: -------------------------------------------------------------------------------- 1 | -- https://www.lintcode.com/problem/1921/?showListFe=true&page=1&problemTypeId=3&ordering=level&pageSize=50 2 | 3 | -- Write your SQL Query here -- 4 | -- example: SELECT * FROM XX_TABLE WHERE XXX -- 5 | 6 | SELECT name as player FROM users as U WHERE U.id not in (SELECT users.id FROM users inner join recharges on users.id = recharges.user_id) -------------------------------------------------------------------------------- /solution/lintcode/1923.sql: -------------------------------------------------------------------------------- 1 | -- https://www.lintcode.com/problem/1923/?showListFe=true&page=1&problemTypeId=3&ordering=level&pageSize=50 2 | 3 | -- Write your SQL Query here -- 4 | -- example: SELECT * FROM XX_TABLE WHERE XXX -- 5 | 6 | SELECT id FROM new_cases as outer_db WHERE increased_count > 7 | (SELECT increased_count FROM new_cases WHERE new_cases.date = DATE_SUB(outer_db.date, Interval 1 DAY)) -------------------------------------------------------------------------------- /solution/place/reference_materials.md: -------------------------------------------------------------------------------- 1 | ### SDE 2 | 3 | - A detailed list on [Leetcode](https://leetcode.com/discuss/interview-question/1098600/topics-which-you-cant-skip-interview-preparation-study-plan-using-leetcode) 4 | 5 | 6 | ### Data Science 7 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/basic_implementation/README.md: -------------------------------------------------------------------------------- 1 | ### This repo contains solution to the python programming questions tried from [this github repo](https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt). Most of the comments have been added in the code snippet itself. -------------------------------------------------------------------------------- /solution/python_programming_exercises/basic_implementation/ques15.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__' : 2 | n = 1 + 11 + 111 + 1111 3 | m = int(input().strip()) 4 | print(n*m) 5 | 6 | 7 | # Question 15 8 | # Level 2 9 | 10 | # Question: 11 | # Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. 12 | # Suppose the following input is supplied to the program: 13 | # 9 14 | # Then, the output should be: 15 | # 11106 16 | 17 | # Hints: 18 | # In case of input data being supplied to the question, it should be assumed to be a console input. 19 | 20 | # Solution: 21 | # a = raw_input() 22 | # n1 = int( "%s" % a ) 23 | # n2 = int( "%s%s" % (a,a) ) 24 | # n3 = int( "%s%s%s" % (a,a,a) ) 25 | # n4 = int( "%s%s%s%s" % (a,a,a,a) ) 26 | # print n1+n2+n3+n4 -------------------------------------------------------------------------------- /solution/python_programming_exercises/basic_implementation/ques2.py: -------------------------------------------------------------------------------- 1 | # For command line argument 2 | from sys import argv 3 | 4 | def fact(x): 5 | return x if x is 1 else x*fact(x-1) 6 | shortFact = lambda x: x if x is 1 else x*shortFact(x-1) 7 | 8 | try : 9 | print(shortFact(int(argv[1]))) 10 | except : 11 | print("No argument passed") 12 | finally: 13 | pass 14 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/basic_implementation/ques4.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__' : 2 | n = input().strip().split(',') 3 | print(list(n),tuple(n),sep='\n') 4 | 5 | # Question 4 6 | # Level 1 7 | 8 | # Question: 9 | # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. 10 | # Suppose the following input is supplied to the program: 11 | # 34,67,55,33,12,98 12 | # Then, the output should be: 13 | # ['34', '67', '55', '33', '12', '98'] 14 | # ('34', '67', '55', '33', '12', '98') 15 | 16 | # Hints: 17 | # In case of input data being supplied to the question, it should be assumed to be a console input. 18 | # tuple() method can convert list to tuple 19 | 20 | # Solution: 21 | # values=raw_input() 22 | # l=values.split(",") 23 | # t=tuple(l) 24 | # print l 25 | # print t -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/DiagonalDifference.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/diagonal-difference/problem 2 | 3 | import os 4 | import sys 5 | 6 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 7 | 8 | numOfRows = int(input().strip()) 9 | matrix = [[] for _ in range(numOfRows)] 10 | for row in range(numOfRows): 11 | matrix[row] = list(map(int, input().strip().split())) 12 | sum1, sum2 = 0,0 13 | for i in range(numOfRows): 14 | for j in range(numOfRows): 15 | if i == j: 16 | sum1 += matrix[i][j] 17 | if numOfRows - 1 - i == j: 18 | sum2 += matrix[i][j] 19 | 20 | fptr.write(str(abs(sum2 - sum1)) + "\n") 21 | fptr.close() 22 | # print(sum1, sum2) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/FACTRL2.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/FCTRL2 2 | 3 | # precalculate factorials 4 | fact = [1,1] 5 | for i in range(2,101): 6 | fact.append(i*fact[-1]) 7 | 8 | for _ in range(int(input().strip())): 9 | n = int(input().strip()) 10 | print(fact[n]) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/FLOW001.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/FLOW001 2 | for _ in range(int(input().strip())): 3 | a,b = map(int,input().strip().split()) 4 | print(a+b) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/FLOW002.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/FLOW002 2 | import sys 3 | for _ in range(int(sys.stdin.readline())): 4 | a,b = map(int,sys.stdin.readline().split()) 5 | print(a%b) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/FLOW006.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/FLOW006 2 | for _ in range(int(input().strip())): 3 | n,ans = input(),0 4 | for i in n: 5 | ans += int(i) 6 | print(ans) 7 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/GOOGOL05.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/GOOGOL05 2 | # implementation of std::map 3 | 4 | words = dict() 5 | for _ in range(int(input())): 6 | word = input().strip() 7 | try: 8 | words[word] += 1 9 | except: 10 | words[word] = 1 11 | 12 | for key, value in sorted(words.items()): 13 | print(key, value) 14 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/HamiltonianAndLagrangian.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/hamiltonian-and-lagrangian/ 2 | n = int(input()) 3 | arr = list(map(int, input().strip().split())) 4 | 5 | ans, grtr = [], 0 6 | for i in arr[::-1]: 7 | if i >= grtr: 8 | ans.append(i) 9 | grtr = i 10 | for i in ans[::-1]: 11 | print(i, end = ' ') 12 | print() -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/INTEST.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/INTEST 2 | n,k = map(int,input().strip().split()) 3 | ans = 0 4 | for _ in range(n): 5 | t = int(input().strip()) 6 | if t%k is 0: 7 | # remember ans = ans + 1 creates a local variable 8 | ans += 1 9 | print(ans) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/MinimumOperations.py: -------------------------------------------------------------------------------- 1 | # https://practice.geeksforgeeks.org/problems/find-optimum-operation/0 2 | 3 | from collections import defaultdict 4 | from itertools import permutations, combinations 5 | import sys 6 | 7 | sys.setrecursionlimit(100000) 8 | 9 | dp = [] 10 | 11 | def recur(i,n): 12 | if i == n: 13 | return 0 14 | elif i > n: 15 | return 10**12 16 | elif dp[i] != -1: 17 | return dp[i] 18 | dp[i] = 1 + min(recur(2*i,n), recur(i+1,n)) 19 | return dp[i] 20 | 21 | def solve(): 22 | n = int(input().strip()) 23 | print(1 + recur(1,n)) 24 | 25 | if __name__ == '__main__': 26 | test = int(input().strip()) 27 | for _ in range(test): 28 | dp = [-1 for i in range(10**4+3)] 29 | solve() -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/MonkAndWelcomeProblem.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/monk-and-welcome-problem/ 2 | import sys 3 | 4 | N = int(sys.stdin.readline()) 5 | 6 | A = list(map(int, sys.stdin.readline().split())) 7 | B = list(map(int, sys.stdin.readline().split())) 8 | for i in [x + y for x, y in zip(A, B)]: 9 | print(i, end = ' ') 10 | 11 | print() -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/NeutralisationOfCharges.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/charges-repel/ 2 | 3 | n = int(input()) 4 | s = input() 5 | last, cnt, ans = "*", 0, [] 6 | for i in range(len(s)): 7 | try: 8 | if ans[-1] == s[i]: 9 | ans.pop() 10 | else: 11 | ans.append(s[i]) 12 | except: 13 | ans.append(s[i]) 14 | ans = ''.join(ans) 15 | print(len(ans)) 16 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/PolygonPossibility.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/polygon-possible/ 2 | # Refer : https://www.geeksforgeeks.org/check-if-it-is-possible-to-create-a-polygon-with-given-n-sides/ 3 | for _ in range(int(input())): 4 | n = int(input()) 5 | sides = list(map(int, input().strip().split())) 6 | 7 | print("Yes" if max(sides) < sum(sides) - max(sides) else "No") -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/ReduceFunction.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/reduce-function/problem 2 | 3 | from fractions import gcd 4 | 5 | def product(fracs): 6 | t = reduce(lambda x,y: x*y, fracs, Fraction('1/1')) 7 | Gcd = gcd(t.numerator, t.denominator) 8 | return t.numerator//Gcd, t.denominator//Gcd 9 | -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/START01.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/START01 2 | import sys 3 | print(sys.stdin.readline().split()) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/SequenceEquation.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/permutation-equation/problem 2 | 3 | import os 4 | import sys 5 | 6 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 7 | 8 | numberOfElements = int(input()) 9 | elements = list(map(int, input().strip().split())) 10 | 11 | solution = [None for _ in range(numberOfElements)] 12 | for index in range(1, numberOfElements+1): 13 | for i in range(numberOfElements): 14 | if elements[elements[i]-1] == index: 15 | solution[index-1] = i + 1 16 | break 17 | 18 | fptr.write('\n'.join(map(str, solution)) + "\n") 19 | fptr.close() -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/TSORT.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/TSORT 2 | import sys 3 | l = [] 4 | for _ in range(int(sys.stdin.readline())): 5 | l.append(int(sys.stdin.readline())) 6 | for i in sorted(l): 7 | print(i) -------------------------------------------------------------------------------- /solution/python_programming_exercises/online_judge_solutions/UtopianTree.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/utopian-tree/problem 2 | 3 | #!/bin/python3 4 | 5 | import math 6 | import os 7 | import random 8 | import re 9 | import sys 10 | 11 | # Complete the utopianTree function below. 12 | def utopianTree(n): 13 | height = 1 14 | if n is 0: 15 | return 1 16 | 17 | for i in range(1,n+1): 18 | if i%2 == 0: 19 | height += 1 20 | else: 21 | height *= 2 22 | # n -= 1 23 | return height 24 | 25 | if __name__ == '__main__': 26 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 27 | 28 | t = int(input()) 29 | 30 | for t_itr in range(t): 31 | n = int(input()) 32 | 33 | result = utopianTree(n) 34 | 35 | fptr.write(str(result) + '\n') 36 | 37 | fptr.close() 38 | -------------------------------------------------------------------------------- /solution/spoj/Aggressive_cows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fun(int val); 5 | vector v; 6 | int n,c; 7 | 8 | int main(){ 9 | ios_base::sync_with_stdio(false); 10 | int test; 11 | cin>>test; 12 | while(test--){ 13 | int k,j,i,m; 14 | cin>>n>>c; 15 | v.resize(n); 16 | for(i=0;i>v[i]; 18 | sort(v.begin(),v.end()); 19 | int low=0,high=v[n-1]; 20 | while(low=val){ 36 | prev=v[i]; 37 | cnt++; 38 | } 39 | if(cnt==c) 40 | return 1; 41 | } 42 | return 0; 43 | } -------------------------------------------------------------------------------- /solution/spoj/EDIST.cpp: -------------------------------------------------------------------------------- 1 | // https://www.spoj.com/problems/EDIST/ 2 | #include 3 | using namespace std; 4 | #define ll long long int 5 | 6 | ll table[3003][3003]; 7 | string s,ss; 8 | ll solve(int i,int j); 9 | 10 | int main(){ 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(0); cout.tie(0); 13 | int test; cin>>test; 14 | while(test--){ 15 | ll i,j,k,n,m; 16 | cin>>s>>ss; 17 | memset(table,-1,sizeof(table)); 18 | cout< 3 | using namespace std; 4 | #define ll long long int 5 | 6 | int main(){ 7 | ios_base::sync_with_stdio(false); 8 | cin.tie(0); cout.tie(0); 9 | int test; cin>>test; 10 | for(int ii=1;ii<=test;ii++){ 11 | ll i,j,k,n,m; 12 | cin>>n; vector v(n); 13 | if(n==0){ 14 | cout<<"Case "<>v[i]; 20 | if(i==0)sum[1][i]=v[i]; 21 | else{ 22 | sum[1][i]=sum[0][i-1]+v[i]; 23 | sum[0][i]=max(sum[0][i-1],sum[1][i-1]); 24 | } 25 | } 26 | cout<<"Case "< 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int main(){ 6 | ios_base::sync_with_stdio(false); 7 | cin.tie(0); cout.tie(0); 8 | ll test; 9 | cin>>test; 10 | while(test--){ 11 | ll i,j,k,n,m=0; 12 | cin>>n; 13 | vector v(n),fe(n); 14 | for(i=0;i>v[i]; 16 | for(i=0;i>fe[i]; 18 | sort(v.begin(),v.end()); 19 | sort(fe.begin(),fe.end()); 20 | for(i=0;i 2 | using namespace std; 3 | #define ll long long int 4 | #define mp set 5 | int main(){ 6 | ios_base::sync_with_stdio(false); 7 | cin.tie(0); cout.tie(0); 8 | ll test=1; 9 | // cin>>test; 10 | while(test--){ 11 | ll i,j,k,n,m=0; 12 | cin>>n; 13 | unordered_map look_up; 14 | for(i=0;i>j; 16 | cin>>k; 17 | for(m=0;m>var; 20 | look_up[j].insert(var); 21 | } 22 | } 23 | set sta; 24 | for(auto it1:look_up){ 25 | for(auto it2:it1.second){//it2 is id of friends of bob's friends 26 | if(look_up.find(it2)==look_up.end()){ 27 | sta.insert(it2); 28 | } 29 | } 30 | } 31 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int main(){ 6 | ios_base::sync_with_stdio(false); 7 | ll dp[2][32]; 8 | memset(dp,0,sizeof(dp)); 9 | dp[0][0]=1, dp[1][1]=1; 10 | for(ll i=2;i<32;i++){ 11 | dp[0][i]=dp[0][i-2]+dp[1][i-1]*2; 12 | dp[1][i]=dp[0][i-1]+dp[1][i-2]; 13 | } 14 | ll n; 15 | cin>>n; 16 | while(n!=-1){ 17 | cout<>n; 19 | } 20 | return 0; 21 | } -------------------------------------------------------------------------------- /solution/spoj/PT07Y.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | vector v[(int)1e4+3]; 5 | #define eb emplace_back 6 | bool tree=true,vis[(int)1e4+3]; 7 | void search(int node,int par); 8 | 9 | int main(){ 10 | ll n,m,i,j,k; 11 | cin>>n>>m; 12 | for(i=0;i>j>>k; 14 | v[j].eb(k); v[k].eb(j); 15 | } 16 | search(j,-1); 17 | if(m==n-1 && tree)cout<<"YES\n"; 18 | else cout<<"NO\n"; 19 | return 0; 20 | } 21 | 22 | void search(int node,int par){ 23 | if(vis[node]){ 24 | tree=false; 25 | return ; 26 | } 27 | vis[node]=true; 28 | for(auto it:v[node]){ 29 | if(it==par)continue; 30 | search(it,node); 31 | } 32 | } -------------------------------------------------------------------------------- /solution/topcoder/Alliteration.py: -------------------------------------------------------------------------------- 1 | https://vjudge.net/problem/TopCoder-6808 2 | 3 | class Alliteration(): 4 | def __init__(self): 5 | pass 6 | 7 | def count(self, String): 8 | # arr = [0 for _ in range(26)] 9 | ans, cur = 0, 1 10 | for index, word in enumerate(String): 11 | if index is 0: 12 | continue 13 | elif word[0].lower() == String[index -1][0].lower(): 14 | cur += 1 15 | else: 16 | if cur > 1: 17 | ans += 1 18 | cur = 1 19 | if cur > 1: 20 | ans += 1 21 | return ans 22 | 23 | # myObj = Alliteration() 24 | # inp = ["Round", "the", "rugged", "rock", "the", "ragged", "rascal", "ran"] 25 | 26 | # print(myObj.count(inp)) -------------------------------------------------------------------------------- /solution/topcoder/Arrfix.cpp: -------------------------------------------------------------------------------- 1 | // https://community.topcoder.com/stat?c=problem_statement&pm=14361 2 | #include 3 | using namespace std; 4 | #define ll long long int 5 | 6 | class Arrfix{ 7 | public: 8 | int mindiff(vector A,vector B,vector F){ 9 | map _mp; 10 | int len = F.size(); 11 | for(auto i=0;i0)_mp[B[i]]--; 17 | else cn++; 18 | } 19 | } 20 | return cn; 21 | } 22 | }; 23 | 24 | // int main(){ 25 | // Arrfix alpha; 26 | // vector A= {1,2,3}; 27 | // vector B= {3,2,1}; 28 | // vector F= {}; 29 | // cout< 3 | using namespace std; 4 | #define ll long long int 5 | 6 | class ShorterSuperSum{ 7 | public: 8 | ll table[15][15]; 9 | ShorterSuperSum(){ 10 | memset(table,0,sizeof(table)); 11 | for(int i=0;i<15;i++){ 12 | for(int j=1;j<15;j++){ 13 | if(i==0)table[i][j]=j; 14 | else{ 15 | ll sum=0; 16 | for(int var=1;var<=j;var++) 17 | sum+=table[i-1][var]; 18 | table[i][j]=sum; 19 | } 20 | } 21 | } 22 | } 23 | 24 | int calculate(int k,int n){ 25 | return table[k][n]; 26 | } 27 | 28 | }; 29 | 30 | // int main(){ 31 | // ShorterSuperSum alpha; 32 | // int n,k; 33 | // cin>>k>>n; 34 | // cout< 3 | using namespace std; 4 | 5 | int main(){ 6 | ios_base::sync_with_stdio(false); 7 | cin.tie(0); cout.tie(0); 8 | int n,i; 9 | cin>>n; 10 | while(n){ 11 | vector v(n); 12 | int mx=0,mx_so=0; 13 | for(i=0;i>v[i]; 15 | for(i=0;i>n; 25 | } 26 | 27 | return 0; 28 | } --------------------------------------------------------------------------------