[
  {
    "path": ".gitignore",
    "content": ".idea\nalgorithms-java/out\n*.class\n"
  },
  {
    "path": "README.md",
    "content": "\nLeetCode\n========\n\n### LeetCode Algorithm\n\n(Notes: \"🔒\" means you need to buy a book from Leetcode)\n\n\n| # | Title | Solution | Difficulty |\n|---| ----- | -------- | ---------- |\n|1946|[Largest Number After Mutating Substring](https://leetcode.com/problems/largest-number-after-mutating-substring/) | [C++](./algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp), [Java](./algorithms/java/src/LargestNumberAfterMutatingSubtring/largestNumberAfterMutatingSubstring.java)|Medium|\n|1945|[Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/) | [C++](./algorithms/cpp/leetcode/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp)|Easy|\n|1935|[Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type/) | [C++](./algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp)|Easy|\n|1884|[Egg Drop With 2 Eggs and N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/) | [C++](./algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp)|Medium|\n|1882|[Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) | [C++](./algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp)|Medium|\n|1881|[Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion/) | [C++](./algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp)|Medium|\n|1880|[Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/) | [C++](./algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp)|Easy|\n|1877|[Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/) | [C++](./algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp)|Medium|\n|1876|[Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/) | [C++](./algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp)|Easy|\n|1871|[Jump Game VII](https://leetcode.com/problems/jump-game-vii/) | [C++](./algorithms/cpp/jumpGame/jumpGame.VII.cpp)|Medium|\n|1870|[Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) | [C++](./algorithms/cpp/minimumSpeedToArriveOnTime/MinimumSpeedToArriveOnTime.cpp)|Medium|\n|1869|[Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/) | [C++](./algorithms/cpp/longerContiguousSegmentsOfOnesThanZeros/LongerContiguousSegmentsOfOnesThanZeros.cpp)|Easy|\n|1862|[Sum of Floored Pairs](https://leetcode.com/problems/sum-of-floored-pairs/) | [C++](./algorithms/cpp/sumOfFlooredPairs/SumOfFlooredPairs.cpp)|Hard|\n|1861|[Rotating the Box](https://leetcode.com/problems/rotating-the-box/) | [C++](./algorithms/cpp/rotatingTheBox/RotatingTheBox.cpp)|Medium|\n|1860|[Incremental Memory Leak](https://leetcode.com/problems/incremental-memory-leak/) | [C++](./algorithms/cpp/incrementalMemoryLeak/IncrementalMemoryLeak.cpp)|Medium|\n|1859|[Sorting the Sentence](https://leetcode.com/problems/sorting-the-sentence/) | [C++](./algorithms/cpp/sortingTheSentence/SortingTheSentence.cpp)|Easy|\n|1857|[Largest Color Value in a Directed Graph](https://leetcode.com/problems/largest-color-value-in-a-directed-graph/) | [C++](./algorithms/cpp/largestColorValueInADirectedGraph/LargestColorValueInADirectedGraph.cpp)|Hard|\n|1856|[Maximum Subarray Min-Product](https://leetcode.com/problems/maximum-subarray-min-product/) | [C++](./algorithms/cpp/maximumSubarrayMinProduct/MaximumSubarrayMinProduct.cpp)|Medium|\n|1855|[Maximum Distance Between a Pair of Values](https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/) | [C++](./algorithms/cpp/maximumDistanceBetweenAPairOfValues/MaximumDistanceBetweenAPairOfValues.cpp)|Medium|\n|1854|[Maximum Population Year](https://leetcode.com/problems/maximum-population-year/) | [C++](./algorithms/cpp/maximumPopulationYear/MaximumPopulationYear.cpp)|Easy|\n|1851|[Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) | [C++](./algorithms/cpp/minimumIntervalToIncludeEachQuery/MinimumIntervalToIncludeEachQuery.cpp)|Hard|\n|1850|[Minimum Adjacent Swaps to Reach the Kth Smallest Number](https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/) | [C++](./algorithms/cpp/minimumAdjacentSwapsToReachTheKthSmallestNumber/MinimumAdjacentSwapsToReachTheKthSmallestNumber.cpp)|Medium|\n|1849|[Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/) | [C++](./algorithms/cpp/splittingAStringIntoDescendingConsecutiveValues/SplittingAStringIntoDescendingConsecutiveValues.cpp)|Medium|\n|1848|[Minimum Distance to the Target Element](https://leetcode.com/problems/minimum-distance-to-the-target-element/) | [C++](./algorithms/cpp/minimumDistanceToTheTargetElement/MinimumDistanceToTheTargetElement.cpp)|Easy|\n|1847|[Closest Room](https://leetcode.com/problems/closest-room/) | [C++](./algorithms/cpp/closestRoom/ClosestRoom.cpp)|Hard|\n|1846|[Maximum Element After Decreasing and Rearranging](https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/) | [C++](./algorithms/cpp/maximumElementAfterDecreasingAndRearranging/MaximumElementAfterDecreasingAndRearranging.cpp)|Medium|\n|1845|[Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) | [C++](./algorithms/cpp/seatReservationManager/SeatReservationManager.cpp)|Medium|\n|1844|[Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters/) | [C++](./algorithms/cpp/replaceAllDigitsWithCharacters/ReplaceAllDigitsWithCharacters.cpp)|Easy|\n|1840|[Maximum Building Height](https://leetcode.com/problems/maximum-building-height/) | [C++](./algorithms/cpp/maximumBuildingHeight/MaximumBuildingHeight.cpp)|Hard|\n|1839|[Longest Substring Of All Vowels in Order](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/) | [C++](./algorithms/cpp/longestSubstringOfAllVowelsInOrder/LongestSubstringOfAllVowelsInOrder.cpp)|Medium|\n|1838|[Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) | [C++](./algorithms/cpp/frequencyOfTheMostFrequentElement/FrequencyOfTheMostFrequentElement.cpp)|Medium|\n|1837|[Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k/) | [C++](./algorithms/cpp/sumOfDigitsInBaseK/SumOfDigitsInBaseK.cpp)|Easy|\n|1835|[Find XOR Sum of All Pairs Bitwise AND](https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/) | [C++](./algorithms/cpp/findXorSumOfAllPairsBitwiseAnd/FindXorSumOfAllPairsBitwiseAnd.cpp)|Hard|\n|1834|[Single-Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/) | [C++](./algorithms/cpp/singleThreadedCpu/SingleThreadedCpu.cpp)|Medium|\n|1833|[Maximum Ice Cream Bars](https://leetcode.com/problems/maximum-ice-cream-bars/) | [C++](./algorithms/cpp/maximumIceCreamBars/MaximumIceCreamBars.cpp)|Medium|\n|1832|[Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram/) | [C++](./algorithms/cpp/checkIfTheSentenceIsPangram/CheckIfTheSentenceIsPangram.cpp)|Easy|\n|1829|[Maximum XOR for Each Query](https://leetcode.com/problems/maximum-xor-for-each-query/) | [C++](./algorithms/cpp/maximumXorForEachQuery/MaximumXorForEachQuery.cpp)|Medium|\n|1828|[Queries on Number of Points Inside a Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/) | [C++](./algorithms/cpp/queriesOnNumberOfPointsInsideACircle/QueriesOnNumberOfPointsInsideACircle.cpp)|Medium|\n|1827|[Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/) | [C++](./algorithms/cpp/minimumOperationsToMakeTheArrayIncreasing/MinimumOperationsToMakeTheArrayIncreasing.cpp)|Easy|\n|1825|[Finding MK Average](https://leetcode.com/problems/finding-mk-average/) | [C++](./algorithms/cpp/findingMkAverage/FindingMkAverage.cpp)|Hard|\n|1824|[Minimum Sideway Jumps](https://leetcode.com/problems/minimum-sideway-jumps/) | [C++](./algorithms/cpp/minimumSidewayJumps/MinimumSidewayJumps.cpp)|Medium|\n|1823|[Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) | [C++](./algorithms/cpp/findTheWinnerOfTheCircularGame/FindTheWinnerOfTheCircularGame.cpp)|Medium|\n|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp)|Easy|\n|1819|[Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds/) | [C++](./algorithms/cpp/numberOfDifferentSubsequencesGcds/NumberOfDifferentSubsequencesGcds.cpp)|Hard|\n|1818|[Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) | [C++](./algorithms/cpp/minimumAbsoluteSumDifference/MinimumAbsoluteSumDifference.cpp)|Medium|\n|1817|[Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes/) | [C++](./algorithms/cpp/findingTheUsersActiveMinutes/FindingTheUsersActiveMinutes.cpp)|Medium|\n|1816|[Truncate Sentence](https://leetcode.com/problems/truncate-sentence/) | [C++](./algorithms/cpp/truncateSentence/TruncateSentence.cpp)|Easy|\n|1815|[Maximum Number of Groups Getting Fresh Donuts](https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/) | [C++](./algorithms/cpp/maximumNumberOfGroupsGettingFreshDonuts/MaximumNumberOfGroupsGettingFreshDonuts.cpp)|Hard|\n|1814|[Count Nice Pairs in an Array](https://leetcode.com/problems/count-nice-pairs-in-an-array/) | [C++](./algorithms/cpp/countNicePairsInAnArray/CountNicePairsInAnArray.cpp)|Medium|\n|1813|[Sentence Similarity III](https://leetcode.com/problems/sentence-similarity-iii/) | [C++](./algorithms/cpp/sentenceSimilarity/SentenceSimilarity.III.cpp)|Medium|\n|1812|[Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square/) | [C++](./algorithms/cpp/determineColorOfAChessboardSquare/DetermineColorOfAChessboardSquare.cpp)|Easy|\n|1808|[Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors/) | [C++](./algorithms/cpp/maximizeNumberOfNiceDivisors/MaximizeNumberOfNiceDivisors.cpp)|Hard|\n|1807|[Evaluate the Bracket Pairs of a String](https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/) | [C++](./algorithms/cpp/evaluateTheBracketPairsOfAString/EvaluateTheBracketPairsOfAString.cpp)|Medium|\n|1806|[Minimum Number of Operations to Reinitialize a Permutation](https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/) | [C++](./algorithms/cpp/minimumNumberOfOperationsToReinitializeAPermutation/MinimumNumberOfOperationsToReinitializeAPermutation.cpp)|Medium|\n|1805|[Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string/) | [C++](./algorithms/cpp/numberOfDifferentIntegersInAString/NumberOfDifferentIntegersInAString.cpp)|Easy|\n|1803|[Count Pairs With XOR in a Range](https://leetcode.com/problems/count-pairs-with-xor-in-a-range/) | [C++](./algorithms/cpp/countPairsWithXorInARange/CountPairsWithXorInARange.cpp)|Hard|\n|1802|[Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/) | [C++](./algorithms/cpp/maximumValueAtAGivenIndexInABoundedArray/MaximumValueAtAGivenIndexInABoundedArray.cpp)|Medium|\n|1801|[Number of Orders in the Backlog](https://leetcode.com/problems/number-of-orders-in-the-backlog/) | [C++](./algorithms/cpp/numberOfOrdersInTheBacklog/NumberOfOrdersInTheBacklog.cpp)|Medium|\n|1800|[Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum/) | [C++](./algorithms/cpp/maximumAscendingSubarraySum/MaximumAscendingSubarraySum.cpp)|Easy|\n|1799|[Maximize Score After N Operations](https://leetcode.com/problems/maximize-score-after-n-operations/submissions/) | [C++](./algorithms/cpp/maximizeScoreAfterNOperations/MaximizeScoreAfterNOperations.cpp)|Hard|\n|1798|[Maximum Number of Consecutive Values You Can Make](https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/submissions/) | [C++](./algorithms/cpp/maximumNumberOfConsecutiveValuesYouCanMake/MaximumNumberOfConsecutiveValuesYouCanMake.cpp)|Medium|\n|1797|[Design Authentication Manager](https://leetcode.com/problems/design-authentication-manager/) | [C++](./algorithms/cpp/designAuthenticationManager/DesignAuthenticationManager.cpp)|Medium|\n|1796|[Second Largest Digit in a String](https://leetcode.com/problems/second-largest-digit-in-a-string/) | [C++](./algorithms/cpp/secondLargestDigitInAString/SecondLargestDigitInAString.cpp)|Easy|\n|1793|[Maximum Score of a Good Subarray](https://leetcode.com/problems/maximum-score-of-a-good-subarray/) | [C++](./algorithms/cpp/maximumScoreOfAGoodSubarray/MaximumScoreOfAGoodSubarray.cpp)|Hard|\n|1792|[Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio/) | [C++](./algorithms/cpp/maximumAveragePassRatio/MaximumAveragePassRatio.cpp)|Medium|\n|1791|[Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph/) | [C++](./algorithms/cpp/findCenterOfStarGraph/FindCenterOfStarGraph.cpp)|Medium|\n|1790|[Check if One String Swap Can Make Strings Equal](https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/) | [C++](./algorithms/cpp/checkIfOneStringSwapCanMakeStringsEqual/CheckIfOneStringSwapCanMakeStringsEqual.cpp)|Easy|\n|1787|[Make the XOR of All Segments Equal to Zero](https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/) | [C++](./algorithms/cpp/makeTheXorOfAllSegmentsEqualToZero/MakeTheXorOfAllSegmentsEqualToZero.cpp)|Hard|\n|1786|[Number of Restricted Paths From First to Last Node](https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/) | [C++](./algorithms/cpp/numberOfRestrictedPathsFromFirstToLastNode/NumberOfRestrictedPathsFromFirstToLastNode.cpp)|Medium|\n|1785|[Minimum Elements to Add to Form a Given Sum](https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/) | [C++](./algorithms/cpp/minimumElementsToAddToFormAGivenSum/MinimumElementsToAddToFormAGivenSum.cpp)|Medium|\n|1784|[Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/) | [C++](./algorithms/cpp/checkIfBinaryStringHasAtMostOneSegmentOfOnes/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.cpp)|Easy|\n|1782|[Count Pairs Of Nodes](https://leetcode.com/problems/count-pairs-of-nodes/) | [C++](./algorithms/cpp/countPairsOfNodes/CountPairsOfNodes.cpp)|Hard|\n|1781|[Sum of Beauty of All Substrings](https://leetcode.com/problems/sum-of-beauty-of-all-substrings/) | [C++](./algorithms/cpp/sumOfBeautyOfAllSubstrings/SumOfBeautyOfAllSubstrings.cpp)|Medium|\n|1780|[Check if Number is a Sum of Powers of Three](https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/) | [C++](./algorithms/cpp/checkIfNumberIsASumOfPowersOfThree/CheckIfNumberIsASumOfPowersOfThree.cpp)|Medium|\n|1779|[Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/) | [C++](./algorithms/cpp/findNearestPointThatHasTheSameXOrYCoordinate/FindNearestPointThatHasTheSameXOrYCoordinate.cpp)|Easy|\n|1775|[Equal Sum Arrays With Minimum Number of Operations](https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/) | [C++](./algorithms/cpp/equalSumArraysWithMinimumNumberOfOperations/EqualSumArraysWithMinimumNumberOfOperations.cpp)|Medium|\n|1774|[Closest Dessert Cost](https://leetcode.com/problems/closest-dessert-cost/) | [C++](./algorithms/cpp/closestDessertCost/ClosestDessertCost.cpp)|Medium|\n|1773|[Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule/) | [C++](./algorithms/cpp/countItemsMatchingARule/CountItemsMatchingARule.cpp)|Easy|\n|1771|[Maximize Palindrome Length From Subsequences](https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/) | [C++](./algorithms/cpp/maximizePalindromeLengthFromSubsequences/MaximizePalindromeLengthFromSubsequences.cpp)|Hard|\n|1770|[Maximum Score from Performing Multiplication Operations](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/) | [C++](./algorithms/cpp/maximumScoreFromPerformingMultiplicationOperations/MaximumScoreFromPerformingMultiplicationOperations.cpp)|Medium|\n|1769|[Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/) | [C++](./algorithms/cpp/minimumNumberOfOperationsToMoveAllBallsToEachBox/MinimumNumberOfOperationsToMoveAllBallsToEachBox.cpp)|Medium|\n|1768|[Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) | [C++](./algorithms/cpp/mergeStringsAlternately/MergeStringsAlternately.cpp)|Easy|\n|1766|[Tree of Coprimes](https://leetcode.com/problems/tree-of-coprimes/) | [C++](./algorithms/cpp/treeOfCoprimes/TreeOfCoprimes.cpp)|Hard|\n|1765|[Map of Highest Peak](https://leetcode.com/problems/map-of-highest-peak/) | [C++](./algorithms/cpp/mapOfHighestPeak/MapOfHighestPeak.cpp)|Medium|\n|1764|[Form Array by Concatenating Subarrays of Another Array](https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/) | [C++](./algorithms/cpp/formArrayByConcatenatingSubarraysOfAnotherArray/FormArrayByConcatenatingSubarraysOfAnotherArray.cpp)|Medium|\n|1763|[Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring/) | [C++](./algorithms/cpp/longestNiceSubstring/LongestNiceSubstring.cpp)|Easy|\n|1761|[Minimum Degree of a Connected Trio in a Graph](https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/) | [C++](./algorithms/cpp/minimumDegreeOfAConnectedTrioInAGraph/MinimumDegreeOfAConnectedTrioInAGraph.cpp)|Hard|\n|1760|[Minimum Limit of Balls in a Bag](https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/) | [C++](./algorithms/cpp/minimumLimitOfBallsInABag/MinimumLimitOfBallsInABag.cpp)|Medium|\n|1759|[Count Number of Homogenous Substrings](https://leetcode.com/problems/count-number-of-homogenous-substrings/) | [C++](./algorithms/cpp/countNumberOfHomogenousSubstrings/CountNumberOfHomogenousSubstrings.cpp)|Medium|\n|1758|[Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/) | [C++](./algorithms/cpp/minimumChangesToMakeAlternatingBinaryString/MinimumChangesToMakeAlternatingBinaryString.cpp)|Easy|\n|1755|[Closest Subsequence Sum](https://leetcode.com/problems/closest-subsequence-sum/) | [C++](./algorithms/cpp/closestSubsequenceSum/ClosestSubsequenceSum.cpp)|Hard|\n|1754|[Largest Merge Of Two Strings](https://leetcode.com/problems/largest-merge-of-two-strings/) | [C++](./algorithms/cpp/largestMergeOfTwoStrings/LargestMergeOfTwoStrings.cpp)|Medium|\n|1753|[Maximum Score From Removing Stones](https://leetcode.com/problems/maximum-score-from-removing-stones/) | [C++](./algorithms/cpp/maximumScoreFromRemovingStones/MaximumScoreFromRemovingStones.cpp)|Medium|\n|1752|[Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C++](./algorithms/cpp/checkIfArrayIsSortedAndRotated/CheckIfArrayIsSortedAndRotated.cpp)|Easy|\n|1751|[Maximum Number of Events That Can Be Attended II](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/) | [C++](./algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.II.cpp)|Hard|\n|1750|[Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/) | [C++](./algorithms/cpp/minimumLengthOfStringAfterDeletingSimilarEnds/MinimumLengthOfStringAfterDeletingSimilarEnds.cpp)|Medium|\n|1749|[Maximum Absolute Sum of Any Subarray](https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/) | [C++](./algorithms/cpp/maximumAbsoluteSumOfAnySubarray/MaximumAbsoluteSumOfAnySubarray.cpp)|Medium|\n|1748|[Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements/) | [C++](./algorithms/cpp/sumOfUniqueElements/SumOfUniqueElements.cpp)|Easy|\n|1743|[Restore the Array From Adjacent Pairs](https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/) | [C++](./algorithms/cpp/restoreTheArrayFromAdjacentPairs/RestoreTheArrayFromAdjacentPairs.cpp)|Medium|\n|1742|[Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box/) | [C++](./algorithms/cpp/maximumNumberOfBallsInABox/MaximumNumberOfBallsInABox.cpp)|Easy|\n|1739|[Building Boxes](https://leetcode.com/problems/building-boxes/) | [C++](./algorithms/cpp/buildingBoxes/BuildingBoxes.cpp)|Hard|\n|1738|[Find Kth Largest XOR Coordinate Value](https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/) | [C++](./algorithms/cpp/findKthLargestXorCoordinateValue/FindKthLargestXorCoordinateValue.cpp)|Medium|\n|1736|[Latest Time by Replacing Hidden Digits](https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/) | [C++](./algorithms/cpp/latestTimeByReplacingHiddenDigits/LatestTimeByReplacingHiddenDigits.cpp)|Easy|\n|1734|[Decode XORed Permutation](https://leetcode.com/problems/decode-xored-permutation/) | [C++](./algorithms/cpp/decodeXORedPermutation/DecodeXoredPermutation.cpp)|Medium|\n|1733|[Minimum Number of People to Teach](https://leetcode.com/problems/minimum-number-of-people-to-teach/) | [C++](./algorithms/cpp/minimumNumberOfPeopleToTeach/MinimumNumberOfPeopleToTeach.cpp)|Medium|\n|1732|[Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude/) | [C++](./algorithms/cpp/findTheHighestAltitude/FindTheHighestAltitude.cpp)|Easy|\n|1727|[Largest Submatrix With Rearrangements](https://leetcode.com/problems/largest-submatrix-with-rearrangements/) | [C++](./algorithms/cpp/largestSubmatrixWithRearrangements/LargestSubmatrixWithRearrangements.cpp)|Medium|\n|1726|[Tuple with Same Product](https://leetcode.com/problems/tuple-with-same-product/) | [C++](./algorithms/cpp/tupleWithSameProduct/TupleWithSameProduct.cpp)|Medium|\n|1725|[Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/) | [C++](./algorithms/cpp/numberOfRectanglesThatCanFormTheLargestSquare/NumberOfRectanglesThatCanFormTheLargestSquare.cpp)|Easy|\n|1718|[Construct the Lexicographically Largest Valid Sequence](https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/) | [C++](./algorithms/cpp/constructTheLexicographicallyLargestValidSequence/ConstructTheLexicographicallyLargestValidSequence.cpp)|Medium|\n|1717|[Maximum Score From Removing Substrings](https://leetcode.com/problems/maximum-score-from-removing-substrings/) | [C++](./algorithms/cpp/maximumScoreFromRemovingSubstrings/MaximumScoreFromRemovingSubstrings.cpp)|Medium|\n|1716|[Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank/) | [C++](./algorithms/cpp/calculateMoneyInLeetcodeBank/CalculateMoneyInLeetcodeBank.cpp)|Easy|\n|1712|[Ways to Split Array Into Three Subarrays](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/) | [C++](./algorithms/cpp/waysToSplitArrayIntoThreeSubarrays/WaysToSplitArrayIntoThreeSubarrays.cpp)|Medium|\n|1711|[Count Good Meals](https://leetcode.com/problems/count-good-meals/) | [C++](./algorithms/cpp/countGoodMeals/CountGoodMeals.cpp)|Medium|\n|1710|[Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/) | [C++](./algorithms/cpp/maximumUnitsOnATruck/MaximumUnitsOnATruck.cpp)|Easy|\n|1700|[Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/) | [C++](./algorithms/cpp/numberOfStudentsUnableToEatLunch/NumberOfStudentsUnableToEatLunch.cpp)|Easy|\n|1695|[Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/) | [C++](./algorithms/cpp/maximumErasureValue/MaximumErasureValue.cpp)|Medium|\n|1694|[Reformat Phone Number](https://leetcode.com/problems/reformat-phone-number/) | [C++](./algorithms/cpp/reformatPhoneNumber/ReformatPhoneNumber.cpp)|Easy|\n|1625|[Lexicographically Smallest String After Applying Operations](https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/) | [C++](./algorithms/cpp/lexicographicallySmallestStringAfterApplyingOperations/LexicographicallySmallestStringAfterApplyingOperations.cpp)|Medium|\n|1624|[Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters/) | [C++](./algorithms/cpp/largestSubstringBetweenTwoEqualCharacters/LargestSubstringBetweenTwoEqualCharacters.cpp)|Easy|\n|1605|[Find Valid Matrix Given Row and Column Sums](https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/) | [C++](./algorithms/cpp/FindValidMatrixGivenRowAndColumnSums/FindValidMatrixGivenRowAndColumnSums.cpp)|Medium|\n|1573|[Number of Ways to Split a String](https://leetcode.com/problems/number-of-ways-to-split-a-string/) | [C++](./algorithms/cpp/NumberOfWaysToSplitString/NumberOfWaysToSplitString.cpp)|Medium|\n|1556|[Thousand Separator](https://leetcode.com/problems/thousand-separator/) | [C++](./algorithms/cpp/thousandSeparator/ThousandSeparator.cpp)|Easy|\n|1551|[Minimum Operations to Make Array Equal](https://leetcode.com/problems/minimum-operations-to-make-array-equal/) | [C++](./algorithms/cpp/minimumOperationsToMakeArrayEqual/MinimumOperationsToMakeArrayEqual.cpp)|Medium|\n|1550|[Three Consecutive Odds](https://leetcode.com/problems/three-consecutive-odds/) | [C++](./algorithms/cpp/threeConsecutiveOdds/ThreeConsecutiveOdds.cpp)|Easy|\n|1541|[Minimum Insertions to Balance a Parentheses String](https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/) | [C++](./algorithms/cpp/minimumInsertionsToBalanceAParenthesesString/MinimumInsertionsToBalanceAParenthesesString.cpp)|Medium|\n|1535|[Find the Winner of an Array Game](https://leetcode.com/problems/find-the-winner-of-an-array-game/) | [C++](./algorithms/cpp/findTheWinnerOfAnArrayGame/FindTheWinnerOfAnArrayGame.cpp)|Medium|\n|1529|[Bulb Switcher IV](https://leetcode.com/problems/bulb-switcher-iv/) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.IV.cpp)|Medium|\n|1528|[Shuffle String](https://leetcode.com/problems/shuffle-string/submissions/) | [C++](./algorithms/cpp/shuffleString/ShuffleString.cpp)|Easy|\n|1525|[Number of Good Ways to Split a String](https://leetcode.com/problems/number-of-good-ways-to-split-a-string/) | [C++](./algorithms/cpp/numberOfGoodWaysToSplitAString/NumberOfGoodWaysToSplitAString.cpp)|Medium|\n|1524|[Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C++](./algorithms/cpp/numberOfSubArraysWithOddSum/NumberOfSubArraysWithOddSum.cpp)|Medium|\n|1523|[Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) | [C++](./algorithms/cpp/countOddNumbersInAnIntervalRange/CountOddNumbersInAnIntervalRange.cpp)|Easy|\n|1513|[Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/) | [C++](./algorithms/cpp/numberOfSubstringsWithOnly1s/NumberOfSubstringsWithOnly1s.cpp)|Medium|\n|1470|[Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) | [C++](./algorithms/cpp/shuffleTheArray/ShuffleTheArray.cpp)|Easy|\n|1464|[Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/) | [C++](./algorithms/cpp/maximumProductOfTwoElementsInAnArray/MaximumProductOfTwoElementsInAnArray.cpp)|Easy|\n|1460|[Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/) | [C++](./algorithms/cpp/twoArraysEqualByReversingSubArrays/MakeTwoArraysEqualByReversingSubArrays.cpp)|Easy|\n|1376|[Time Needed to Inform All Employees](https://leetcode.com/problems/time-needed-to-inform-all-employees/) | [C++](./algorithms/cpp/timeNeededToInformAllEmployees/TimeNeededToInformAllEmployees.cpp)|Medium|\n|1375|[Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.III.cpp)|Medium|\n|1353|[Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | [C++](./algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.cpp)|Medium|\n|1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [C++](./algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp)|Medium|\n|1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C++](./algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp)|Easy|\n|1170|[Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [C++](./algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp)|Easy|\n|1071|[Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | [C++](./algorithms/cpp/greatestCommonDivisorOfStrings/GreatestCommonDivisorOfStrings.cpp)|Easy|\n|1030|[Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/) | [C++](./algorithms/cpp/matrixCellsInDistanceOrder/MatrixCellsInDistanceOrder.cpp)|Easy|\n|1029|[Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) | [C++](./algorithms/cpp/twoCityScheduling/TwoCityScheduling.cpp)|Easy|\n|1028|[Recover a Tree From Preorder Traversal](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/) | [C++](./algorithms/cpp/recoverATreeFromPreorderTraversal/recoverATreeFromPreorderTraversal.cpp)|Hard|\n|1024|[Video Stitching](https://leetcode.com/problems/video-stitching/) | [C++](./algorithms/cpp/videoStitching/VideoStitching.cpp)|Medium|\n|993|[Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree/) | [C++](./algorithms/cpp/cousinsInBinaryTree/CousinsInBinaryTree.cpp)|Easy|\n|991|[Broken Calculator](https://leetcode.com/problems/broken-calculator/) | [C++](./algorithms/cpp/brokenCalculator/BrokenCalculator.cpp)|Medium|\n|990|[Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) | [C++](./algorithms/cpp/satisfiabilityOfEqualityEquations/SatisfiabilityOfEqualityEquations.cpp)|Medium|\n|989|[Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/) | [C++](./algorithms/cpp/addToArrayFormOfInteger/AddToArrayFormOfInteger.cpp)|Easy|\n|988|[Smallest String Starting From Leaf](https://leetcode.com/problems/smallest-string-starting-from-leaf/) | [C++](./algorithms/cpp/smallestStringStartingFromLeaf/SmallestStringStartingFromLeaf.cpp)|Medium|\n|987|[Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/) | [C++](./algorithms/cpp/verticalOrderTraversalOfABinaryTree/VerticalOrderTraversalOfABinaryTree.cpp)|Medium|\n|986|[Interval List Intersections](https://leetcode.com/problems/interval-list-intersections/) | [C++](./algorithms/cpp/intervalListIntersectons/IntervalListIntersections.cpp)|Medium|\n|985|[Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) | [C++](./algorithms/cpp/sumOfEvenNumbersAfterQueries/SumOfEvenNumbersAfterQueries.cpp)|Easy|\n|984|[String Without AAA or BBB](https://leetcode.com/problems/string-without-aaa-or-bbb/) | [C++](./algorithms/cpp/stringWithoutAAAOrBBB/StringWithoutAAAOrBBB.cpp)|Easy|\n|983|[Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/) | [C++](./algorithms/cpp/minimumCostForTickets/MinimumCostForTickets.cpp)|Medium|\n|982|[Triples with Bitwise AND Equal To Zero](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) | [C++](./algorithms/cpp/triplesWithBitwiseANDEqualToZero/TriplesWithBitwiseAndEqualToZero.cpp)|Hard|\n|981|[Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) | [C++](./algorithms/cpp/timeBasedKeyValueStore/TimeBasedKeyValueStore.cpp)|Medium|\n|980|[Unique Paths III](https://leetcode.com/problems/unique-paths-iii/) | [C++](./algorithms/cpp/uniquePaths/UniquePaths.III.cpp),[Python](./algorithms/python/uniquePaths/uniquePathsIII.py)|Hard|\n|979|[Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/) | [C++](./algorithms/cpp/distributeCoinsInBinaryTree/DistributeCoinsInBinaryTree.cpp)|Medium|\n|978|[Longest Turbulent Subarray](https://leetcode.com/problems/longest-turbulent-subarray/) | [C++](./algorithms/cpp/longestTurbulentSubarray/LongestTurbulentSubarray.cpp),[Python](./algorithms/python/LongestTurbulentSubarray/maxTurbulenceSize.py)|Medium|\n|977|[Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C++](./algorithms/cpp/squaresOfASortedArray/SquaresOfASortedArray.cpp), [Python](./algorithms/python/SquaresOfSortedArray/sortedSquares.py)|Easy|\n|976|[Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/) | [C++](./algorithms/cpp/largestPerimeterTriangle/largestPerimeterTriangle.cpp), [Python](./algorithms/python/LargestPerimeterTriangle/largestPerimeter.py)|Easy|\n|971|[Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/) | [Python](./algorithms/python/FlipBinaryTreeToMatchPreorderTraversal/flipMatchVoyage.py)|Medium|\n|969|[Pancake Sorting](https://leetcode.com/problems/pancake-sorting/) | [Python](./algorithms/python/PancakeSorting/pancakeSort.py)|Medium|\n|961|[N-Repeated element in size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) | [C++](./algorithms/cpp/nRepeatedElementInSize2NArray/N-Repeated-Element-in-Size-2N-Array.cpp)|Easy|\n|958|[Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) | [Python](./algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py)|Medium|\n|951|[Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) | [Python](./algorithms/python/FlipEquivalentBinaryTrees/flipEquiv.py)|Medium|\n|950|[Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order/) | [Python](./algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py)|Medium|\n|941|[Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [Python](./algorithms/python/ValidMountainArray/validMountainArray.py)|Easy|\n|933|[Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) | [C++](./algorithms/cpp/numberOfRecentCalls/NumberOfRecentCalls.cpp)|Easy|\n|931|[Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/) | [C++](./algorithms/cpp/minimumFallingPathSum/MinimumFallingPathSum.cpp)|Medium|\n|929|[Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | [C++](./algorithms/cpp/uniqueEmailAddresses/UniqueEmailAddresses.cpp)|Easy|\n|922|[Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [C++](./algorithms/cpp/sortArrayByParity/SortArrayByParity.II.cpp)|Easy|\n|914|[X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/) | [Python](./algorithms/python/XOfAKindInADeckOfCards/hasGroupsSizeX.py)|Easy|\n|905|[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C++](./algorithms/cpp/sortArrayByParity/SortArrayByParity.cpp)|Easy|\n|876|[Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Python](./algorithms/python/MiddleOfTheLinkedList/middleOfTheLinkedList.py)|Easy|\n|859|[Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [C++](./algorithms/cpp/buddyStrings/BuddyStrings.cpp)|Easy|\n|858|[Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [C++](./algorithms/cpp/mirrorReflection/MirrorReflection.cpp)|Medium|\n|852|[Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) | [C++](./algorithms/cpp/peakIndexInAMountainArray/PeakIndexInAMountainArray.cpp)|Easy|\n|849|[Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [Python](./algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py)|Easy|\n|844|[Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/description/) | [C++](./algorithms/cpp/backspaceStringCompare/BackspaceStringCompare.cpp)|Easy|\n|837|[Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./algorithms/cpp/mostCommonWord/MostCommonWord.cpp)|Easy|\n|830|[Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [Python](./algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py)|Easy|\n|820|[Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./algorithms/cpp/shortEncodingOfWords/ShortEncodingOfWords.cpp)|Medium|\n|804|[Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [C++](./algorithms/cpp/uniqueMorseCodeWords/UniqueMorseCodeWords.cpp)|Easy|\n|776|[Swim In Rising Water](https://leetcode.com/problems/swim-in-rising-water/description/) | [Python](./algorithms/python/SwimInRisingWater/swim_in_rising_water.py)|Hard|\n|771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description) | [C++](./algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp)|Easy|\n|747|[Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [Python](./algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py)|Easy|\n|746|[Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./algorithms/cpp/minCostClimbingStairs/MinCostClimbingStairs.cpp), [Python](./algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py)|Easy|\n|721|[Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./algorithms/cpp/accountsMerge/AccountsMerge.cpp)|Medium|\n|717|[1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](./algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py)|Easy|\n|714|[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee) | [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/BestTimeToBuyAndSellStockWithTransactionFee.cpp)|Medium|\n|712|[Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/) | [C++](./algorithms/cpp/minimumASCIIDeleteSumForTwoStrings/MinimumAsciiDeleteSumForTwoStrings.cpp)|Medium|\n|695|[Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./algorithms/cpp/maxAreaOfIsland/MaxAreaOfIsland.cpp)|Medium|\n|687|[Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [Python](./algorithms/python/LongestUnivaluePath/longestUnivaluePath.py)|Easy|\n|684|[Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [Python](./algorithms/python/RedundantConnection/findRedundantConnection.py)|Medium|\n|674|[Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](./algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py)|Easy|\n|672|[Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/submissions/) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.II.cpp)|Medium|\n|671|[Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](./algorithms/python/SecondMinimumNodeInABinaryTree/findSecondMinimumValue.py)|Easy|\n|665|[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](./algorithms/python/Non-decreasingArray/checkPossibility.py)|Easy|\n|662|[Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [Python](./algorithms/python/MaximumWidthOfBinaryTree/widthOfBinaryTree.py)|Medium|\n|661|[Image Smoother](https://leetcode.com/problems/image-smoother/) | [Python](./algorithms/python/ImageSmoother/imageSmoother.py)|Easy|\n|655|[Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [Python](./algorithms/python/PrintBinaryTree/printTree.py)|Medium|\n|652|[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) | [Python](./algorithms/python/FindDuplicateSubtrees/findDuplicateSubtrees.py)|Medium|\n|647|[Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./algorithms/cpp/palindromicSubstrings/PalindromicSubstrings.cpp)|Medium|\n|643|[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [C++](./algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp), [Python](./algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py)|Easy|\n|628|[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](./algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py)|Easy|\n|623|[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/) | [Python](./algorithms/python/AddOneRowToTree/addOneRow.py)|Medium|\n|581|[Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) | [Python](./algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py)|Easy|\n|572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) | [Python](./algorithms/python/SubtreeOfAnotherTree/isSubtree.py)|Easy|\n|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [Python](./algorithms/python/BinaryTreeTilt/findTilt.py)|Easy|\n|547|[Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./algorithms/cpp/friendCircles/FriendCircles.cpp)|Medium|\n|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp), [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy|\n|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy|\n|532|[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [Python](./algorithms/python/K-diffPairsInAnArray/findPairs.py)|Easy|\n|520|[Detect Capital](https://leetcode.com/problems/detect-capital/) | [C++](./algorithms/cpp/detectCapital/DetectCapital.cpp)|Easy|\n|518|[Coin Change 2](https://leetcode.com/problems/coin-change-2/) | [C++](./algorithms/cpp/coinChange/CoinChange2.cpp)|Medium|\n|516|[Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) | [C++](./algorithms/cpp/longestPalindromicSubsequence/LongestPalindromicSubsequence.cpp)|Medium|\n|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [C++](./algorithms/cpp/fibonacciNumber/FibonacciNumber.cpp), [Python](./algorithms/python/FibonacciNumber/fib.py)|Easy|\n|497|[Random Point in Non-overlapping Rectangles](https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/) | [C++](./algorithms/cpp/randomPointInNonOverlappingRectangles/randomPointInNonOverlappingRectangles.cpp)|Medium|\n|494|[Target Sum](https://leetcode.com/problems/target-sum/) | [C++](./algorithms/cpp/targetSum/targetSum.cpp)|Medium|\n|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium|\n|463|[Island Perimeter](https://leetcode.com/problems/island-perimeter/) | [C++](./algorithms/cpp/islandPerimeter/IslandPerimeter.cpp)|Easy|\n|450|[DeleteNodeInABST](https://leetcode.com/problems/delete-node-in-a-bst/) | [Python](./algorithms/python/DeleteNodeInABST/deleteNode.py)|Medium|\n|449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/) | [Python](./algorithms/python/SerializeAndDeserializeBST/serialize.py)|Medium|\n|438|[Find all Anagrams in a string](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./algorithms/cpp/findAllAnagramsInAString/Find-All-Anagrams-in-a-String.cpp)|Medium|\n|437|[Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [Python](./algorithms/python/PathSumIII/pathSum.py)|Medium|\n|418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) 🔒 | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy|\n|416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium|\n|415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy|\n|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py)|Easy|\n|413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium|\n|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy|\n|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [C++](./algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp)|Hard|\n|409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./algorithms/cpp/longestPalindrome/LongestPalindrome.cpp)|Easy|\n|406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium|\n|405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy|\n|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp), [Python](./algorithms/python/SumOfLeftLeaves/sumOfLeftLeaves.py)|Easy|\n|403|[Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./algorithms/cpp/frogJump/FrogJump.cpp)|Hard|\n|402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium|\n|401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy|\n|400|[Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./algorithms/cpp/nthDigit/NthDigit.cpp)|Medium|\n|399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./algorithms/cpp/evaluateDivision/EvaluateDivision.cpp)|Medium|\n|398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./algorithms/cpp/randomPickIndex/RandomPickIndex.cpp)|Medium|\n|397|[Integer Replacement](https://leetcode.com/problems/integer-replacement/) | [C++](./algorithms/cpp/integerReplacement/IntegerReplacement.cpp)|Medium|\n|396|[Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./algorithms/cpp/rotateFunction/RotateFunction.cpp)|Easy|\n|395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium|\n|394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium|\n|393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium|\n|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium|\n|391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard|\n|390|[Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium|\n|389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy|\n|388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp)|Medium|\n|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp)|Easy|\n|386|[Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp)|Medium|\n|385|[Mini Parser](https://leetcode.com/problems/mini-parser/) | [C++](./algorithms/cpp/miniParser/MiniParser.cpp)|Medium|\n|384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp)|Medium|\n|383|[Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./algorithms/cpp/ransomNote/RansomNote.cpp)|Easy|\n|382|[Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp)|Medium|\n|381|[Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp)|Hard|\n|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp)|Hard|\n|377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium|\n|376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium|\n|371|[Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/description/) | [C++](./algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers.cpp)|Easy|\n|367|[Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/description/) | [C++](./algorithms/cpp/validPerfectSquare/ValidPerfectSquare.cpp)|Easy|\n|357|[Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./algorithms/cpp/countNumbersWithUniqueDigits/CountNumbersWithUniqueDigits.cpp)|Medium|\n|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp)|Easy|\n|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy|\n|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium|\n|345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy|\n|344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy|\n|343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium|\n|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy|\n|341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [C++](./algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp)|Medium|\n|338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium|\n|337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp), [Python](./algorithms/python/HouseRobberIII/rob.py)|Medium|\n|336|[Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./algorithms/cpp/palindromePairs/PalindromePairs.cpp)|Hard|\n|334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium|\n|332|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | [C++](./algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp)|Medium|\n|331|[Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp)|Medium|\n|330|[Patching Array](https://leetcode.com/problems/patching-array/) | [C++](./algorithms/cpp/patchingArray/PatchingArray.cpp)|Medium|\n|329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium|\n|328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy|\n|327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard|\n|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy|\n|324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./algorithms/cpp/wiggleSort/WiggleSort.II.cpp)|Medium|\n|322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium|\n|321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard|\n|319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp)|Medium|\n|318|[Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp)|Medium|\n|316|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | [C++](./algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp)|Hard|\n|315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [C++](./algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp)|Hard|\n|313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp)|Medium|\n|312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/) | [C++](./algorithms/cpp/burstBalloons/BurstBalloons.cpp)|Hard|\n|310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | [C++](./algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp)|Medium|\n|309|[Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/BestTimeToBuyAndSellStockWithCooldown.cpp)|Medium|\n|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp)|Medium|\n|306|[Additive Number](https://leetcode.com/problems/additive-number/) | [C++](./algorithms/cpp/additiveNumber/AdditiveNumber.cpp)|Medium|\n|304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | [C++](./algorithms/cpp/rangeSumQuery2D-Immutable/RangeSumQuery2dImmutable.cpp)|Medium|\n|303|[Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)  | [C++](./algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Immutable.cpp)|Easy|\n|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | [C++](./algorithms/cpp/removeInvalidParentheses/RemoveInvalidParentheses.cpp) |Hard|\n|300|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)  | [C++](./algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp)|Medium|\n|299|[Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)  | [C++](./algorithms/cpp/bullsAndCows/bullsAndCows.cpp)|Easy|\n|297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)  | [C++](./algorithms/cpp/serializeAndDeserializeBinaryTree/SerializeAndDeserializeBinaryTree.cpp)|Medium|\n|295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./algorithms/cpp/findMedianFromDataStream/FindMedianFromDataStream.cpp)|Hard|\n|292|[Nim Game](https://leetcode.com/problems/nim-game/)  | [C++](./algorithms/cpp/nimGame/nimGame.cpp)|Easy|\n|290|[Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./algorithms/cpp/wordPattern/WordPattern.cpp)|Easy|\n|289|[Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./algorithms/cpp/gameOfLife/GameOfLife.cpp)|Medium|\n|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)  | [C++](./algorithms/cpp/findTheDuplicateNumber/findTheDuplicateNumber.cpp), [Python](./algorithms/python/FindTheDuplicateNumber/findDuplicate.py)|Hard|\n|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) 🔒 | [Java](./algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBST.java)|Medium|\n|284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)  | [C++](./algorithms/cpp/peekingIterator/PeekingIterator.cpp)|Medium|\n|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)  | [C++](./algorithms/cpp/moveZeroes/moveZeroes.cpp)|Easy|\n|282|[Expression Add Operators](https://leetcode.com/problems/expression-add-operators/)  | [C++](./algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp)|Hard|\n|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [C++](./algorithms/cpp/perfectSquares/PerfectSquares.cpp)|Medium|\n|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| [C++](./algorithms/cpp/firstBadVersion/FirstBadVersion.cpp), [Java](./algorithms/java/src/firstBadVersion/firstBadVersion.java)|Easy|\n|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index.II.cpp)|Medium|\n|274|[H-Index](https://leetcode.com/problems/h-index/)| [C++](./algorithms/cpp/h-Index/h-Index.cpp)|Medium|\n|273|[Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)| [C++](./algorithms/cpp/integerToEnglishWords/IntegerToEnglishWords.cpp)|Medium|\n|268|[Missing Number](https://leetcode.com/problems/missing-number/)| [C++](./algorithms/cpp/missingNumber/MissingNumber.cpp)|Medium|\n|264|[Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.II.cpp)|Medium|\n|263|[Ugly Number](https://leetcode.com/problems/ugly-number/)| [C++](./algorithms/cpp/uglyNumber/UglyNumber.cpp)|Easy|\n|260|[Single Number III](https://leetcode.com/problems/single-number-iii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.III.cpp)|Medium|\n|258|[Add Digits](https://leetcode.com/problems/add-digits/)| [C++](./algorithms/cpp/addDigits/addDigits.cpp)|Easy|\n|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [C++](./algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp)|Easy|\n|242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./algorithms/cpp/anagrams/ValidAnagram.cpp), [Java](./algorithms/java/src/validAnagram/ValidAnagram.java)|Easy|\n|241|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)|[C++](./algorithms/cpp/differentWaysToAddParentheses/DifferentWaysToAddParentheses.cpp), [Python](./algorithms/python/DifferentWaysToAddParentheses/diffWaysToCompute.py)|Medium|\n|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)|[C++](./algorithms/cpp/search2DMatrix/search2DMatrix.II.cpp), [Java](./algorithms/java/src/searchA2DMatrixII/SearchA2DMatrixII.java), [Python](./algorithms/python/SearchA2DMatrixII/searchMatrix.py)|Medium|\n|239|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./algorithms/cpp/slidingWindowMaximum/SlidingWindowMaximum.cpp)|Hard|\n|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)| [C++](./algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp)|Medium|\n|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp)|Easy|\n|236|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| [C++](./algorithms/cpp/lowestCommonAncestorOfABinaryTree/LowestCommonAncestorOfABinaryTree.cpp), [Java](./algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTree.java), [Python](./algorithms/python/LowestCommonAncestorOfABinaryTree/lowestCommonAncestor.py)|Medium|\n|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| [C++](./algorithms/cpp/lowestCommonAncestorOfABinarySearchTree/LowestCommonAncestorOfABinarySearchTree.cpp), [Python](./algorithms/python/LowestCommonAncestorOfABinarySearchTree/lowestCommonAncestor.py)|Easy|\n|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp)|Easy|\n|233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [C++](./algorithms/cpp/numberOfDigitOne/NumberOfDigitOne.cpp)|Medium|\n|232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [C++](./algorithms/cpp/implementQueueUsingStacks/ImplementQueueUsingStacks.cpp), [Java](./algorithms/java/src/myQueue/MyQueue.java)|Easy|\n|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp)|Easy|\n|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [C++](./algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp), [Python](./algorithms/python/KthSmallestElementInABST/kthSmallest.py)|Medium|\n|229|[Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./algorithms/cpp/majorityElement/majorityElement.II.cpp)|Medium|\n|228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [C++](./algorithms/cpp/summaryRanges/SummaryRanges.cpp)|Easy|\n|227|[Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)| [C++](./algorithms/cpp/basicCalculator/BasicCalculator.II.cpp)|Medium|\n|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)| [C++](./algorithms/cpp/invertBinaryTree/InvertBinaryTree.cpp)|Easy|\n|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)| [C++](./algorithms/cpp/implementStackUsingQueues/ImplementStackUsingQueues.cpp), [Java](./algorithms/java/src/myStack/MyStack.java)|Medium|\n|224|[Basic Calculator](https://leetcode.com/problems/basic-calculator/)| [C++](./algorithms/cpp/basicCalculator/BasicCalculator.cpp)|Medium|\n|223|[Rectangle Area](https://leetcode.com/problems/rectangle-area/)| [C++](./algorithms/cpp/rectangleArea/RectangleArea.cpp)|Easy|\n|222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)| [C++](./algorithms/cpp/countCompleteTreeNodes/CountCompleteTreeNodes.cpp), [Python](./algorithms/python/CountCompleteTreeNodes/countNodes.py)|Medium|\n|221|[Maximal Square](https://leetcode.com/problems/maximal-square/)| [C++](./algorithms/cpp/maximalSquare/MaximalSquare.cpp)|Medium|\n|220|[Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)| [C++](./algorithms/cpp/containsDuplicate/ContainsDuplicate.III.cpp), [Python](./algorithms/python/ContainsDuplicateIII/containsNearbyAlmostDuplicate.py)|Medium|\n|219|[Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)| [C++](./algorithms/cpp/containsDuplicate/ContainsDuplicate.II.cpp), [Python](./algorithms/python/ContainsDuplicateII/containsNearbyDuplicate.py)|Easy|\n|218|[The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/)| [C++](./algorithms/cpp/theSkylineProblem/TheSkylineProblem.cpp)|Hard|\n|217|[Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)| [C++](./algorithms/cpp/containsDuplicate/ContainsDuplicate.cpp)|Easy|\n|216|[Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [C++](./algorithms/cpp/combinationSum/combinationSum.III.cpp)|Medium|\n|215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/)| [C++](./algorithms/cpp/kthLargestElementInAnArray/KthLargestElementInAnArray.cpp)|Medium|\n|214|[Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/)| [C++](./algorithms/cpp/shortestPalindrome/ShortestPalindrome.cpp)|Hard|\n|213|[House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./algorithms/cpp/houseRobber/houseRobber.II.cpp)|Medium|\n|212|[Word Search II](https://leetcode.com/problems/word-search-ii/)| [C++](./algorithms/cpp/wordSearch/wordSearch.II.cpp)|Hard|\n|211|[Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [C++](./algorithms/cpp/addAndSearchWord/AddAndSearchWord.cpp)|Medium|\n|210|[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [C++](./algorithms/cpp/courseSchedule/CourseSchedule.II.cpp)|Medium|\n|209|[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)| [C++](./algorithms/cpp/minimumSizeSubarraySum/MinimumSizeSubarraySum.cpp)|Medium|\n|208|[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)| [C++](./algorithms/cpp/implementTriePrefixTree/ImplementTriePrefixTree.cpp)|Medium|\n|207|[Course Schedule](https://leetcode.com/problems/course-schedule/)| [C++](./algorithms/cpp/courseSchedule/CourseSchedule.cpp)|Medium|\n|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [C++](./algorithms/cpp/reverseLinkedList/reverseLinkedList.cpp), [Java](./algorithms/java/src/reverseLinkedList/ReverseLinkedList.java)|Easy|\n|205|[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)| [C++](./algorithms/cpp/isomorphicStrings/IsomorphicStrings.cpp)|Easy|\n|204|[Count Primes](https://leetcode.com/problems/count-primes/)| [C++](./algorithms/cpp/countPrimes/CountPrimes.cpp)|Easy|\n|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./algorithms/cpp/removeLinkedListElements/RemoveLinkedListElements.cpp)|Easy|\n|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py)|Easy|\n|201|[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| [C++](./algorithms/cpp/bitwiseANDOfNumbersRange/BitwiseAndOfNumbersRange.cpp)|Medium|\n|200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [C++](./algorithms/cpp/numberOfIslands/NumberOfIslands.cpp), [Python](./algorithms/python/NumberOfIslands/numIslands.py)|Medium|\n|199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [C++](./algorithms/cpp/binaryTreeRightSideView/binaryTreeRightSideView.cpp)|Medium|\n|198|[House Robber](https://leetcode.com/problems/house-robber/)| [C++](./algorithms/cpp/houseRobber/houseRobber.cpp), [Python](./algorithms/python/HouseRobber/rob.py)|Easy|\n|191|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)| [C++](./algorithms/cpp/numberOf1Bits/numberOf1Bits.cpp)|Easy|\n|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/)| [C++](./algorithms/cpp/reverseBits/reverseBits.cpp)|Easy|\n|189|[Rotate Array](https://leetcode.com/problems/rotate-array/)| [C++](./algorithms/cpp/rotateArray/rotateArray.cpp), [Java](./algorithms/java/src/rotateArray/RotateArray.java)|Easy|\n|188|[Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.IV.cpp)|Hard|\n|187|[Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/)| [C++](./algorithms/cpp/repeatedDNASequences/repeatedDNASequences.cpp)|Medium|\n|186|[Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) 🔒 | [C++](./algorithms/cpp/reverseWordsInAString/reverseWordsInAString.II.cpp)|Medium|\n|179|[Largest Number](https://leetcode.com/problems/largest-number/) | [C++](./algorithms/cpp/largestNumber/largestNumber.cpp)|Medium|\n|174|[Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [C++](./algorithms/cpp/dungeonGame/dungeonGame.cpp)|Hard|\n|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./algorithms/cpp/binarySearchTreeIterator/binarySearchTreeIterator.cpp), [Java](./algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIterator.java), [Python](./algorithms/python/BinarySearchTreeIterator/BSTIterator.py)|Medium|\n|172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./algorithms/cpp/factorialTrailingZeroes/factorialTrailingZeroes.cpp)|Easy|\n|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp)|Easy|\n|170|[Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) 🔒 | [C++](./algorithms/cpp/twoSum/twoSum.III.cpp)|Easy|\n|169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./algorithms/cpp/majorityElement/majorityElement.cpp)|Easy|\n|168|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./algorithms/cpp/excelSheetColumnTitle/excelSheetColumnTitle.cpp)|Easy|\n|167|[Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) 🔒 | [C++](./algorithms/cpp/twoSum/twoSum.II.cpp)|Medium|\n|166|[Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./algorithms/cpp/fractionToRecurringDecimal/fractionToRecurringDecimal.cpp)|Medium|\n|165|[Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [C++](./algorithms/cpp/compareVersionNumbers/compareVersionNumbers.cpp)|Easy|\n|164|[Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./algorithms/cpp/maximumGap/maximumGap.cpp)|Hard|\n|163|[Missing Ranges](https://leetcode.com/problems/missing-ranges/) 🔒 | [C++](./algorithms/cpp/missingRanges/missingRanges.cpp)|Medium|\n|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [C++](./algorithms/cpp/findPeakElement/findPeakElement.cpp), [Java](./algorithms/java/src/findPeakElement/findPeakElement.java)|Medium|\n|161|[One Edit Distance](https://leetcode.com/problems/one-edit-distance/)🔒 | [C++](./algorithms/cpp/oneEditDistance/oneEditDistance.cpp)|Medium|\n|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | [C++](./algorithms/cpp/intersectionOfTwoLinkedLists/intersectionOfTwoLinkedLists.cpp)|Easy|\n|159|[Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) 🔒 | [C++](./algorithms/cpp/longestSubstringWithAtMostTwoDistinctCharacters/longestSubstringWithAtMostTwoDistinctCharacters.cpp)|Hard|\n|158|[Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) 🔒 | [C++](./algorithms/cpp/readNCharactersGivenRead4/readNCharactersGivenRead4.II.cpp)|Hard|\n|157|[Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) 🔒 | [C++](./algorithms/cpp/readNCharactersGivenRead4/readNCharactersGivenRead4.cpp)|Easy|\n|156|[Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) 🔒 | [C++](./algorithms/cpp/binaryTreeUpsideDown/binaryTreeUpsideDown.cpp)|Medium|\n|155|[Min Stack](https://leetcode.com/problems/min-stack/)| [C++](./algorithms/cpp/minStack/minStack.cpp), [Java](./algorithms/java/src/minStack/MinStack.java)|Easy|\n|154|[Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| [C++](./algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.II.cpp)|Hard|\n|153|[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| [C++](./algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp), [Java](./algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.java)|Medium|\n|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)| [C++](./algorithms/cpp/maximumProductSubarray/maximumProductSubarray.cpp)|Medium|\n|151|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/)| [C++](./algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp), [Java](./algorithms/java/src/reverseWordsInAString/ReverseWordsInAString.java)|Medium|\n|150|[Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./algorithms/cpp/evaluateReversePolishNotation/evaluateReversePolishNotation.cpp)|Medium|\n|149|[Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/)| [C++](./algorithms/cpp/maxPointsOnALine/maxPointsOnALine.cpp)|Hard|\n|148|[Sort List](https://leetcode.com/problems/sort-list/)| [C++](./algorithms/cpp/sortList/sortList.cpp), [Python](./algorithms/python/SortList/sortList.py)|Medium|\n|147|[Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)| [C++](./algorithms/cpp/insertionSortList/insertionSortList.cpp), [Python](./algorithms/python/InsertionSortList/insertionSortList.py)|Medium|\n|146|[LRU Cache](https://leetcode.com/problems/lru-cache/)| [C++](./algorithms/cpp/LRUCache/LRUCache.cpp), [Java](./algorithms/java/src/lruCache/LRUCache.java)|Hard|\n|145|[Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [C++](./algorithms/cpp/binaryTreePostorderTraversal/binaryTreePostorderTraversal.cpp), [Python](./algorithms/python/BinaryTreePostorderTraversal/postorderTraversal.py)|Hard|\n|144|[Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)| [C++](./algorithms/cpp/binaryTreePreorderTraversal/binaryTreePreorderTraversal.cpp), [Java](./algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.java)|Medium|\n|143|[Reorder List](https://leetcode.com/problems/reorder-list/)| [C++](./algorithms/cpp/reorderList/reorderList.cpp), [Python](./algorithms/python/ReorderList/reorderList.py)|Medium|\n|142|[Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [C++](./algorithms/cpp/linkedListCycle/linkedListCycle.II.cpp), [Python](./algorithms/python/LinkedListCycleII/detectCycle.py)|Medium|\n|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [C++](./algorithms/cpp/linkedListCycle/linkedListCycle.cpp)|Medium|\n|140|[Word Break II](https://leetcode.com/problems/word-break-ii/)| [C++](./algorithms/cpp/wordBreak/wordBreak.II.cpp)|Hard|\n|139|[Word Break](https://leetcode.com/problems/word-break/)| [C++](./algorithms/cpp/wordBreak/wordBreak.cpp)|Medium|\n|138|[Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/)| [C++](./algorithms/cpp/copyListWithRandomPointer/copyListWithRandomPointer.cpp), [Python](./algorithms/python/CopyListWithRandomPointer/copyRandomList.py)|Hard|\n|137|[Single Number II](https://leetcode.com/problems/single-number-ii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.II.cpp), [Python](./algorithms/python/SingleNumberII/SingleNumberII.py)|Medium|\n|136|[Single Number](https://leetcode.com/problems/single-number/)| [C++](./algorithms/cpp/singleNumber/singleNumber.cpp)|Medium|\n|135|[Candy](https://leetcode.com/problems/candy/)| [C++](./algorithms/cpp/candy/candy.cpp)|Hard|\n|134|[Gas Station](https://leetcode.com/problems/gas-station/)| [C++](./algorithms/cpp/gasStation/gasStation.cpp)|Medium|\n|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)| [C++](./algorithms/cpp/cloneGraph/cloneGraph.cpp)|Medium|\n|132|[Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/)| [C++](./algorithms/cpp/palindromePartitioning/palindromePartitioning.II.cpp)|Hard|\n|131|[Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)| [C++](./algorithms/cpp/palindromePartitioning/palindromePartitioning.cpp)|Medium|\n|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)| [C++](./algorithms/cpp/surroundedRegions/surroundedRegions.cpp)|Medium|\n|129|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| [C++](./algorithms/cpp/sumRootToLeafNumber/sumRootToLeafNumber.cpp), [Python](./algorithms/python/SumRootToLeafNumbers/sumNumbers.py)|Medium|\n|128|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./algorithms/cpp/longestConsecutiveSequence/longestConsecutiveSequence.cpp), [Python](./algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py)|Medium|\n|127|[Word Ladder](https://leetcode.com/problems/word-ladder/)| [C++](./algorithms/cpp/wordLadder/wordLadder.cpp)|Medium|\n|126|[Word Ladder II](https://leetcode.com/problems/word-ladder-ii/)| [C++](./algorithms/cpp/wordLadder/wordLadder.II.cpp)|Hard|\n|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [C++](./algorithms/cpp/validPalindrome/validPalindrome.cpp), [Java](./algorithms/java/src/validPalindrome/ValidPalindrome.java)|Easy|\n|124|[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [C++](./algorithms/cpp/binaryTreeMaximumPathSum/binaryTreeMaximumPathSum.cpp), [Java](./algorithms/java/src/binaryTreeMaximumPathSum/binaryTreeMaximumPathSum.java)|Hard|\n|123|[Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.III.cpp)|Hard|\n|122|[Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.II.cpp)|Medium|\n|121|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp)|Medium|\n|120|[Triangle](https://leetcode.com/problems/triangle/)| [C++](./algorithms/cpp/triangle/triangle.cpp), [Java](./algorithms/java/src/dynamicProgramming/triangle/triangle.java)|Medium|\n|119|[Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./algorithms/cpp/pascalTriangle/pascalTriangle.II.cpp)|Easy|\n|118|[Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./algorithms/cpp/pascalTriangle/pascalTriangle.cpp)|Easy|\n|117|[Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [C++](./algorithms/cpp/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.II.cpp), [Python](./algorithms/python/PopulatingNextRightPointersInEachNodeII/connect.py)|Hard|\n|116|[Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [C++](./algorithms/cpp/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.cpp), [Python](./algorithms/python/PopulatingNextRightPointersInEachNode/connect.py)|Medium|\n|115|[Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/)| [C++](./algorithms/cpp/distinctSubsequences/distinctSubsequences.cpp)|Hard|\n|114|[Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)| [C++](./algorithms/cpp/flattenBinaryTreeToLinkedList/flattenBinaryTreeToLinkedList.cpp), [Python](./algorithms/python/FlattenBinaryTreeToLinkedList/flatten.py)|Medium|\n|113|[Path Sum II](https://leetcode.com/problems/path-sum-ii/)| [C++](./algorithms/cpp/pathSum/pathSum.II.cpp), [Python](./algorithms/python/PathSumII/pathSum.py)|Medium|\n|112|[Path Sum](https://leetcode.com/problems/path-sum/)| [C++](./algorithms/cpp/pathSum/pathSum.cpp)|Easy|\n|111|[Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)| [C++](./algorithms/cpp/minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp)|Easy|\n|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)| [C++](./algorithms/cpp/balancedBinaryTree/balancedBinaryTree.cpp), [Java](./algorithms/java/src/balancedBinaryTree/balancedBinaryTree.java)|Easy|\n|109|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| [C++](./algorithms/cpp/convertSortedListToBinarySearchTree/convertSortedListToBinarySearchTree.cpp)|Medium|\n|108|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| [C++](./algorithms/cpp/convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp)|Medium|\n|107|[Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [C++](./algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.II.cpp)|Easy|\n|106|[Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| [C++](./algorithms/cpp/constructBinaryTreeFromInorderAndPostorderTraversal/constructBinaryTreeFromInorderAndPostorderTraversal.cpp), [Python](./algorithms/python/ConstructBinaryTreeFromInorderAndPostorderTraversal/buildTree.py)|Medium|\n|105|[Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| [C++](./algorithms/cpp/constructBinaryTreeFromPreorderAndInorderTraversal/constructBinaryTreeFromPreorderAndInorderTraversal.cpp), [Python](./algorithms/python/ConstructBinaryTreeFromPreorderAndInorderTraversal/buildTree.py)|Medium|\n|104|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp), [Java](./algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.java)|Easy|\n|103|[Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [C++](./algorithms/cpp/binaryTreeZigzagLevelOrderTraversal/binaryTreeZigzagLevelOrderTraversal.cpp), [Python](./algorithms/python/BinaryTreeZigzagLevelOrderTraversal/zigzagLevelOrder.py)|Medium|\n|102|[Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp), [Java](./algorithms/java/src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.java)|Easy|\n|101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./algorithms/cpp/symmetricTree/symmetricTree.cpp)|Easy|\n|100|[Same Tree](https://leetcode.com/problems/same-tree/)| [C++](./algorithms/cpp/sameTree/sameTree.cpp)|Easy|\n|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [C++](./algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp)|Hard|\n|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [C++](./algorithms/cpp/validateBinarySearchTree/validateBinarySearchTree.cpp), [Java](./algorithms/java/src/validateBinarySearchTree/validateBinarySearchTree.java), [Python](./algorithms/python/ValidateBinarySearchTree/isValidBST.py)|Medium|\n|97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [C++](./algorithms/cpp/interleavingString/interleavingString.cpp)|Hard|\n|96|[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [C++](./algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp), [Python](./algorithms/python/UniqueBinarySearchTrees/numTrees.py)|Medium|\n|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [C++](./algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.II.cpp), [Python](./algorithms/python/UniqueBinarySearchTreesII/generateTrees.py)|Medium|\n|94|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)| [C++](./algorithms/cpp/binaryTreeInorderTraversal/binaryTreeInorderTraversal.cpp)|Medium|\n|93|[Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/)| [C++](./algorithms/cpp/restoreIPAddresses/restoreIPAddresses.cpp)|Medium|\n|92|[Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./algorithms/cpp/reverseLinkedList/reverseLinkedList.II.cpp), [Java](./algorithms/java/src/reverseLinkedListII/ReverseLinkedListII.java), [Python](./algorithms/python/ReverseLinkedListII/reverseBetween.py)|Medium|\n|91|[Decode Ways](https://leetcode.com/problems/decode-ways/)| [C++](./algorithms/cpp/decodeWays/decodeWays.cpp)|Medium|\n|90|[Subsets II](https://leetcode.com/problems/subsets-ii/)| [C++](./algorithms/cpp/subsets/subsets.II.cpp), [Java](./algorithms/java/src/subsets/subsetsII.java)|Medium|\n|89|[Gray Code](https://leetcode.com/problems/gray-code/)| [C++](./algorithms/cpp/grayCode/grayCode.cpp)|Medium|\n|88|[Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./algorithms/cpp/mergeTwoSortedArray/mergeTwoSortedArray.cpp)|Easy|\n|87|[Scramble String](https://leetcode.com/problems/scramble-string/)| [C++](./algorithms/cpp/scrambleString/scrambleString.cpp)|Hard|\n|86|[Partition List](https://leetcode.com/problems/partition-list/)| [C++](./algorithms/cpp/partitionList/partitionList.cpp), [Python](./algorithms/python/PartitionList/partition.py)|Medium|\n|85|[Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./algorithms/cpp/maximalRectangle/maximalRectangle.cpp)|Hard|\n|84|[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)| [C++](./algorithms/cpp/largestRectangleInHistogram/largestRectangleInHistogram.cpp)|Hard|\n|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./algorithms/cpp/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.cpp)|Easy|\n|82|[Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./algorithms/cpp/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.II.cpp), [Python](./algorithms/python/RemoveDuplicatesFromSortedListII/deleteDuplicates.py)|Medium|\n|81|[Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| [C++](./algorithms/cpp/searchInRotatedSortedArray/searchInRotatedSortedArray.II.cpp)|Medium|\n|80|[Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.II.cpp)|Medium|\n|79|[Word Search](https://leetcode.com/problems/word-search/)| [C++](./algorithms/cpp/wordSearch/wordSearch.cpp)|Medium|\n|78|[Subsets](https://leetcode.com/problems/subsets/)| [C++](./algorithms/cpp/subsets/subsets.cpp), [Java](./algorithms/java/src/subsets/subsets.java), [Python](./algorithms/python/Subsets/subsets.py)|Medium|\n|77|[Combinations](https://leetcode.com/problems/combinations/)| [C++](./algorithms/cpp/combinations/combinations.cpp)|Medium|\n|76|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)| [C++](./algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp)|Hard|\n|75|[Sort Colors](https://leetcode.com/problems/sort-colors/)| [C++](./algorithms/cpp/sortColors/sortColors.cpp)|Medium|\n|74|[Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)| [C++](./algorithms/cpp/search2DMatrix/search2DMatrix.cpp), [Java](./algorithms/java/src/search2DMatrix/search2DMatrix.java)|Medium|\n|73|[Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)| [C++](./algorithms/cpp/setMatrixZeroes/setMatrixZeroes.cpp)|Medium|\n|72|[Edit Distance](https://leetcode.com/problems/edit-distance/)| [C++](./algorithms/cpp/editDistance/editDistance.cpp)|Hard|\n|71|[Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./algorithms/cpp/simplifyPath/simplifyPath.cpp)|Medium|\n|70|[Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [C++](./algorithms/cpp/climbStairs/climbStairs.cpp), [Java](./algorithms/java/src/dynamicProgramming/climbStairs/climbStairs.java)|Easy|\n|69|[Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [C++](./algorithms/cpp/sqrt/sqrt.cpp)|Medium|\n|68|[Text Justification](https://leetcode.com/problems/text-justification/)| [C++](./algorithms/cpp/textJustification/textJustification.cpp)|Hard|\n|67|[Add Binary](https://leetcode.com/problems/add-binary/)| [C++](./algorithms/cpp/addBinary/addBinary.cpp)|Easy|\n|66|[Plus One](https://leetcode.com/problems/plus-one/)| [C++](./algorithms/cpp/plusOne/plusOne.cpp)|Easy|\n|65|[Valid Number](https://leetcode.com/problems/valid-number/)| [C++](./algorithms/cpp/validNumber/validNumber.cpp)|Easy|\n|64|[Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)| [C++](./algorithms/cpp/minimumPathSum/minimumPathSum.cpp), [Java](./algorithms/java/src/dynamicProgramming/minimumPathSum/minimumPathSum.java)|Medium|\n|63|[Unique Paths II](https://leetcode.com/problems/unique-paths-ii/)| [C++](./algorithms/cpp/uniquePaths/uniquePaths.II.cpp), [Java](./algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsII.java)|Medium|\n|62|[Unique Paths](https://leetcode.com/problems/unique-paths/)| [C++](./algorithms/cpp/uniquePaths/uniquePaths.cpp), [Java](./algorithms/java/src/dynamicProgramming/uniquePaths/uniquePaths.java)|Medium|\n|61|[Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./algorithms/cpp/rotateList/rotateList.cpp)|Medium|\n|60|[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)| [C++](./algorithms/cpp/permutationSequence/permutationSequence.cpp)|Medium|\n|59|[Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)| [C++](./algorithms/cpp/spiralMatrix/spiralMatrix.II.cpp)|Medium|\n|58|[Length of Last Word](https://leetcode.com/problems/length-of-last-word/)| [C++](./algorithms/cpp/lengthOfLastWord/lengthOfLastWord.cpp), [Java](./algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java)|Easy|\n|57|[Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./algorithms/cpp/insertInterval/insertInterval.cpp)|Hard|\n|56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./algorithms/cpp/mergeIntervals/mergeIntervals.cpp)|Hard|\n|55|[Jump Game](https://leetcode.com/problems/jump-game/)| [C++](./algorithms/cpp/jumpGame/jumpGame.cpp), [Python](./algorithms/python/jumpGame/jumpGame.py)|Medium|\n|54|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)| [C++](./algorithms/cpp/spiralMatrix/spiralMatrix.cpp)|Medium|\n|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)| [C++](./algorithms/cpp/maximumSubArray/maximumSubArray.cpp), [Java](./algorithms/java/src/MaxSubArray/MaxSubarray.java)|Medium|\n|52|[N-Queens II](https://leetcode.com/problems/n-queens-ii/)| [C++](./algorithms/cpp/nQueens/nQueuens.II.cpp)|Hard|\n|51|[N-Queens](https://leetcode.com/problems/n-queens/)| [C++](./algorithms/cpp/nQueens/nQueuens.cpp)|Hard|\n|50|[\"Pow(x, n)\"](https://leetcode.com/problems/powx-n/)| [C++](./algorithms/cpp/pow/pow.cpp), [Java](./algorithms/java/src/powXn/PowXn.java)|Medium|\n|49|[Group Anagrams](https://leetcode.com/problems/anagrams/)| [C++](./algorithms/cpp/anagrams/GroupAnagrams.cpp)|Medium|\n|48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [C++](./algorithms/cpp/rotateImage/rotateImage.cpp), [Java](./algorithms/java/src/RotateImage/rotateImage.java)|Medium|\n|47|[Permutations II](https://leetcode.com/problems/permutations-ii/)| [C++](./algorithms/cpp/permutations/permutations.II.cpp)|Hard|\n|46|[Permutations](https://leetcode.com/problems/permutations/)| [C++](./algorithms/cpp/permutations/permutations.cpp)|Medium|\n|45|[Jump Game II](https://leetcode.com/problems/jump-game-ii/)| [C++](./algorithms/cpp/jumpGame/jumpGame.II.cpp)|Hard|\n|44|[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)| [C++](./algorithms/cpp/wildcardMatching/wildcardMatching.cpp)|Hard|\n|43|[Multiply Strings](https://leetcode.com/problems/multiply-strings/)| [C++](./algorithms/cpp/multiplyStrings/multiplyStrings.cpp)|Medium|\n|42|[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)| [C++](./algorithms/cpp/trappingRainWater/trappingRainWater.cpp)|Hard|\n|41|[First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./algorithms/cpp/firstMissingPositive/firstMissingPositive.cpp), [Python](././algorithms/python/firstMissingPositive/firstMissingPositive.py)|Hard|\n|40|[Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [C++](./algorithms/cpp/combinationSum/combinationSum.II.cpp)|Medium|\n|39|[Combination Sum](https://leetcode.com/problems/combination-sum/)| [C++](./algorithms/cpp/combinationSum/combinationSum.cpp)|Medium|\n|38|[Count and Say](https://leetcode.com/problems/count-and-say/)| [C++](./algorithms/cpp/countAndSay/countAndSay.cpp), [Java](./algorithms/java/src/countAndSay/CountAndSay.java)|Easy|\n|37|[Sudoku Solver](https://leetcode.com/problems/sudoku-solver/)| [C++](./algorithms/cpp/sudokuSolver/sudokuSolver.cpp)|Hard|\n|36|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/)| [C++](./algorithms/cpp/validSudoku/validSudoku.cpp)|Easy|\n|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [C++](./algorithms/cpp/searchInsertPosition/searchInsertPosition.cpp), [Java](./algorithms/java/src/searchInsertPosition/searchInsertPosition.java)|Medium|\n|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)| [C++](./algorithms/cpp/searchForRange/searchForRange.cpp), [Java](./algorithms/java/src/searchForRange/searchForRange.java)|Medium|\n|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)| [C++](./algorithms/cpp/searchInRotatedSortedArray/searchInRotatedSortedArray.cpp), [Java](./algorithms/java/src/searchInRotatedSortedArray/searchInRotatedSortedArray.java)|Hard|\n|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./algorithms/cpp/longestValidParentheses/longestValidParentheses.cpp)|Hard|\n|31|[Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./algorithms/cpp/nextPermutation/nextPermutation.cpp)|Medium|\n|30|[Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/)| [C++](./algorithms/cpp/substringWithConcatenationOfAllWords/substringWithConcatenationOfAllWords.cpp)|Hard|\n|29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/)| [C++](./algorithms/cpp/divideTwoInt/divideTwoInt.cpp)|Medium|\n|28|[Implement strStr()](https://leetcode.com/problems/implement-strstr/)| [C++](./algorithms/cpp/strStr/strStr.cpp), [Java](./algorithms/java/src/strStr/strStr.java)|Easy|\n|27|[Remove Element](https://leetcode.com/problems/remove-element/)| [C++](./algorithms/cpp/removeElement/removeElement.cpp)|Easy|\n|26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp), [Java](./algorithms/java/src/removeDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArray.java)|Easy|\n|25|[Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./algorithms/cpp/reverseNodesInKGroup/reverseNodesInKGroup.cpp)|Hard|\n|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./algorithms/cpp/swapNodesInPairs/swapNodesInPairs.cpp)|Medium|\n|23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)| [C++](./algorithms/cpp/mergeKSortedLists/mergeKSortedLists.cpp)|Hard|\n|22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [C++](./algorithms/cpp/generateParentheses/generateParentheses.cpp)|Medium|\n|21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./algorithms/cpp/mergeTwoSortedList/mergeTwoSortedList.cpp)|Easy|\n|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./algorithms/cpp/validParentheses/validParentheses.cpp)|Easy|\n|19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp), [Python](./algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py)|Easy|\n|18|[4Sum](https://leetcode.com/problems/4sum/)| [C++](./algorithms/cpp/4Sum/4Sum.cpp)|Medium|\n|17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|Medium|\n|16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [C++](./algorithms/cpp/3SumClosest/3SumClosest.cpp)|Medium|\n|15|[3Sum](https://leetcode.com/problems/3sum/)| [C++](./algorithms/cpp/3Sum/3Sum.cpp)|Medium|\n|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp)|Easy|\n|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp)|Easy|\n|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp)|Medium|\n|11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp), [Java](./algorithms/java/src/containerwithmostwater.java)|Medium|\n|10|[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/)| [C++](./algorithms/cpp/regularExpressionMatching/regularExpressionMatching.cpp)|Hard|\n|9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [C++](./algorithms/cpp/palindromeNumber/palindromeNumber.cpp), [Java](./algorithms/java/src/palindromeNumber/PalindromeNumber.java)|Easy|\n|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)| [C++](./algorithms/cpp/stringToIntegerAtoi/stringToIntegerAtoi.cpp)|Easy|\n|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [C++](./algorithms/cpp/reverseInteger/reverseInteger.cpp)|Easy|\n|6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [C++](./algorithms/cpp/zigZagConversion/zigZagConversion.cpp)|Easy|\n|5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [C++](./algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp)|Medium|\n|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp)|Hard|\n|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [C++](./algorithms/cpp/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp)|Medium|\n|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [C++](./algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp)|Medium|\n|1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./algorithms/cpp/twoSum/twoSum.cpp), [Go](./algorithms/golang/twoSum/twoSum.go)|Easy|\n\n### LeetCode Shell\n\n\n| # | Title | Solution | Difficulty |\n|---| ----- | -------- | ---------- |\n|4|[Tenth Line](https://leetcode.com/problems/tenth-line/)| [Bash](./shell/TenthLine.sh)|Easy|\n|3|[Transpose File](https://leetcode.com/problems/transpose-file/)| [Bash](./shell/TransposeFile.sh)|Medium|\n|2|[Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/)| [Bash](./shell/ValidPhoneNumbers.sh)|Easy|\n|1|[Word Frequency](https://leetcode.com/problems/word-frequency/)| [Bash](./shell/WordFrequency.sh)|Medium|\n\n### LintCode    \n\n| # | Title | Solution | Difficulty |\n|---| ----- | -------- | ---------- |\n|1|[Search in a big sorted array](http://www.lintcode.com/en/problem/search-in-a-big-sorted-array/)|[Java](./algorithms/java/src/searchInABigSortedArray/searchInABigSortedArray.java)|Medium|\n|2|[Search Range in Binary Search Tree](http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/) | [Java](./algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTree.java)|Medium|\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/3Sum/3Sum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/3sum/\n// Author : Hao Chen\n// Date   : 2014-07-22\n\n/********************************************************************************** \n* \n* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? \n* Find all unique triplets in the array which gives the sum of zero.\n* \n* Note:\n* \n* Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)\n* The solution set must not contain duplicate triplets.\n* \n*     For example, given array S = {-1 0 1 2 -1 -4},\n* \n*     A solution set is:\n*     (-1, 0, 1)\n*     (-1, -1, 2)\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\nusing namespace std;\n\n\n/*\n *   Similar like \"Two Number\" problem, we can have the simlar solution.\n *\n *   Suppose the input array is S[0..n-1], 3SUM can be solved in O(n^2) time on average by \n *   inserting each number S[i] into a hash table, and then for each index i and j,  \n *   checking whether the hash table contains the integer - (s[i]+s[j])\n *\n *   Alternatively, the algorithm below first sorts the input array and then tests all \n *   possible pairs in a careful order that avoids the need to binary search for the pairs \n *   in the sorted list, achieving worst-case O(n^n)\n *\n *   Solution:  Quadratic algorithm\n *   http://en.wikipedia.org/wiki/3SUM\n *\n */\nvector<vector<int> > threeSum(vector<int> &num) {\n\n    vector< vector<int> > result;\n    if(num.size() == 0 || num.size() == 1 || num.size() == 2) return result;\n\n    //sort the array, this is the key\n    sort(num.begin(), num.end());\n\n    int n = num.size();\n\n    for (int i=0; i<n-2; i++) {\n        //skip the duplication\n        if (i > 0 && num[i - 1] == num[i]) continue;\n        int a = num[i];\n        int low = i + 1;\n        int high = n - 1;\n        while (low < high) {\n            int b = num[low];\n            int c = num[high];\n            if (a + b + c == 0) {\n                //got the soultion\n                vector<int> v;\n                v.push_back(a);\n                v.push_back(b);\n                v.push_back(c);\n                result.push_back(v);\n                // Continue search for all triplet combinations summing to zero.\n                //skip the duplication\n                while(low < n - 1 && num[low] == num[low + 1]) low++; \n                while(high > 0 && num[high] == num[high - 1]) high--; \n                low++;\n                high--;\n            } else if (a+b+c > 0) {\n                //skip the duplication\n                while(high > 0 && num[high] == num[high - 1]) high--;\n                high--;\n            } else {\n                //skip the duplication\n                while(low < n - 1 && num[low] == num[low + 1]) low++;\n                low++;\n            } \n        }\n    }\n    return result;\n}\n\n//using combination method could meet <<Time Limit Exceeded>> error\nvector<vector<int> > combination(vector<int> &v, int k);\nbool isSumZero(vector<int>& v);\nint sum(vector<int>& v);\n\nvector<vector<int> > threeSum2(vector<int> &num) {\n    vector< vector<int> > result;\n    vector< vector<int> > r = combination(num, 3);\n    for (int i = 0; i < r.size(); i++) {\n        if (isSumZero(r[i])) {\n            result.push_back(r[i]);\n        }\n    }\n    return result;\n}\n\nbool isSumZero(vector < int>& v) {\n    return sum(v) == 0;\n}\n\nint sum(vector<int>& v) {\n    int s = 0;\n    for(int i = 0; i < v.size(); i++) {\n        s += v[i];\n    }\n    return s;\n}\n\nvector<vector<int> > combination(vector<int> &v, int k) {\n\n    vector<vector<int> > result;\n    vector<int> d;\n    int n = v.size();\n    for (int i = 0; i < n; i++) {\n        d.push_back( (i < k) ? 1 : 0 );\n    }\n\n    //1) from the left, find the [1,0] pattern, change it to [0,1]\n    //2) move all of the 1 before the pattern to the most left side\n    //3) check all of 1 move to the right\n    while(1) {\n        vector<int> tmp;\n        for(int x = 0; x < n; x++) {\n            if (d[x]) tmp.push_back(v[x]);\n        }\n        sort(tmp.begin(), tmp.end());\n        result.push_back(tmp);\n        //step 1), find [1,0] pattern\n        int i;\n        bool found = false;\n        int ones = 0;\n        for(i = 0; i < n - 1; i++) {\n\n            if (d[i] == 1 && d[i + 1] == 0) {\n                d[i] = 0; d[i + 1] = 1;\n                found = true;\n                //step 2) move all of right 1 to the most left side\n                for (int j = 0; j < i; j++) {\n                    d[j] = ( ones > 0 ) ? 1 : 0;\n                    ones--;\n                }\n                break;\n            }\n            if (d[i] == 1) ones++;\n        }\n        if (!found) {\n            break;\n        }\n\n    }\n    return result;\n}\n\n\nvoid printMatrix(vector<vector<int> > &matrix)\n{\n    for(int i = 0; i < matrix.size(); i++) {\n        printf(\"{\");\n        for(int j = 0; j < matrix[i].size(); j++) {\n            printf(\"%3d \", matrix[i][j]) ;\n        }\n        printf(\"}\\n\");\n    }\n    cout << endl;\n}\n\n\nint main()\n{\n    //int a[] = { -1, 0, 1, 2, -1, 1, -4 };\n    int a[] = { -1, 1, 1, 1, -1, -1, 0,0,0 };\n    vector<int> n(a, a + sizeof(a)/sizeof(int));\n    vector< vector<int> > result = threeSum(n);\n    printMatrix(result);    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/3SumClosest/3SumClosest.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/3sum-closest/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given an array S of n integers, find three integers in S such that the sum is \n* closest to a given number, target. Return the sum of the three integers. \n* You may assume that each input would have exactly one solution.\n* \n*     For example, given array S = {-1 2 1 -4}, and target = 1.\n* \n*     The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\nusing namespace std;\n\n#define INT_MAX 2147483647\n//solution:  http://en.wikipedia.org/wiki/3SUM\n//the idea as blow:\n//  1) sort the array.\n//  2) take the element one by one, calculate the two numbers in reset array.\n//\n//notes: be careful the duplication number.\n//\n// for example:\n//    [-4,-1,-1,1,2]    target=1\n// \n//    take -4, can cacluate the \"two number problem\" of the reset array [-1,-1,1,2] while target=5\n//    [(-4),-1,-1,1,2]  target=5  distance=4\n//           ^      ^ \n//    because the -1+2 = 1 which < 5, then move the `low` pointer(skip the duplication)\n//    [(-4),-1,-1,1,2]  target=5  distance=2\n//                ^ ^ \n//    take -1(skip the duplication), can cacluate the \"two number problem\" of the reset array [1,2] while target=2\n//    [-4,-1,(-1),1,2]  target=2  distance=1\n//                ^ ^ \nint threeSumClosest(vector<int> &num, int target) {\n    //sort the array\n    sort(num.begin(), num.end());\n\n    int n = num.size();\n    int distance = INT_MAX;\n    int result;\n\n    for (int i=0; i<n-2; i++) {\n        //skip the duplication\n        if (i > 0 && num[i - 1] == num[i]) continue;\n        int a = num[i];\n        int low = i + 1;\n        int high = n - 1;\n        //convert the 3sum to 2sum problem\n        while (low < high) {\n            int b = num[low];\n            int c = num[high];\n            int sum = a + b + c;\n            if (sum - target == 0) {\n                //got the final soultion\n                return target;\n            } else {\n                //tracking the minmal distance\n                if (abs(sum - target) < distance ) {\n                    distance = abs(sum - target);\n                    result = sum;\n                }\n\n                if (sum - target > 0) {\n                    //skip the duplication\n                    while(high > 0 && num[high] == num[high - 1]) high--;\n                    //move the `high` pointer\n                    high--;\n                } else {\n                    //skip the duplication\n                    while(low < n && num[low] == num[low + 1]) low++;\n                    //move the `low` pointer\n                    low++;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n\n\n\nint main()\n{\n    int a[] = { -1, 2, 1, -4 };\n    vector<int> n(a, a + sizeof(a)/sizeof(int));\n    int target = 1;\n    cout << threeSumClosest(n, target) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/4Sum/4Sum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/4sum/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? \n* Find all unique quadruplets in the array which gives the sum of target.\n* \n* Note:\n* \n* Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)\n* The solution set must not contain duplicate quadruplets.\n* \n*     For example, given array S = {1 0 -1 0 -2 2}, and target = 0.\n* \n*     A solution set is:\n*     (-1,  0, 0, 1)\n*     (-2, -1, 1, 2)\n*     (-2,  0, 0, 2)\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvector<vector<int> > threeSum(vector<int> num, int target); \n\n/*\n * 1) Sort the array,\n * 2) traverse the array, and solve the problem by using \"3Sum\" soultion.\n */\n\nvector<vector<int> > fourSum(vector<int> &num, int target) {\n    vector< vector<int> > result;\n    if (num.size() < 4) return result;\n    sort( num.begin(), num.end() );\n\n    for(int i = 0; i < num.size() - 3; i++) {\n        //skip the duplication\n        if (i > 0 && num[i - 1] == num[i]) continue;\n        vector<int> n(num.begin()+i+1, num.end());\n        vector<vector<int> > ret = threeSum(n, target-num[i]);\n        for(int j = 0; j < ret.size(); j++) {\n            ret[j].insert(ret[j].begin(), num[i]);\n            result.push_back(ret[j]);\n        }\n    }\n\n    return result; \n}\n\nvector<vector<int> > threeSum(vector<int> num, int target) {\n\n    vector< vector<int> > result;\n    //sort the array (if the qrray is sorted already, it won't waste any time)\n    sort(num.begin(), num.end());\n\n    int n = num.size();\n\n    for (int i = 0; i < n - 2; i++) {\n        //skip the duplication\n        if (i > 0 && num[i - 1] == num[i]) continue;\n        int a = num[i];\n        int low = i + 1;\n        int high = n - 1;\n        while (low < high) {\n            int b = num[low];\n            int c = num[high];\n            if (a + b + c == target) {\n                //got the soultion\n                vector<int> v;\n                v.push_back(a);\n                v.push_back(b);\n                v.push_back(c);\n                result.push_back(v);\n                // Continue search for all triplet combinations summing to zero.\n                //skip the duplication\n                while(low < n && num[low] == num[low + 1]) low++;\n                while(high > 0 && num[high] == num[high - 1]) high--;\n                low++;\n                high--;\n            } else if (a + b + c > target) {\n                //skip the duplication\n                while(high > 0 && num[high] == num[high - 1]) high--;\n                high--;\n            } else {\n                //skip the duplication\n                while(low < n && num[low] == num[low + 1]) low++;\n                low++;\n            }\n        }\n    }\n    return result;\n}\n\n\nint printMatrix(vector< vector<int> > &vv)\n{\n    for(int i = 0; i < vv.size(); i++) {\n        cout << \"[\";\n        for(int j = 0; j < vv[i].size(); j++) {\n            cout << \" \" << vv[i][j];\n        }\n        cout << \"]\" << endl;;\n    }\n}\n\n\nint main()\n{\n    int a[] = { 1, 0, -1, 0, -2, 2 };\n    vector<int> n(a, a+6);\n    int t = 0;\n    vector< vector<int> > v = fourSum(n, t);\n    printMatrix(v);\n\n    n.clear();\n    int b[] = { -1, -5, -5, -3, 2, 5, 0, 4 };\n    n.insert(n.begin(), b, b+8);\n    t = -7;\n    v = fourSum(n, t);\n    printMatrix(v);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/FindValidMatrixGivenRowAndColumnSums/FindValidMatrixGivenRowAndColumnSums.cpp",
    "content": "// Source : https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/\n// Author : Sudesh Chaudhary\n// Date   : 2020-10-03\n/*******************************************************************************\n* You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum\n* of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix.\n* In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.\n*\n* Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and\n* colSum requirements.\n*\n* Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at\n* least one matrix that fulfills the requirements exists.\n* Example 1:\n*\n* Input: rowSum = [3,8], colSum = [4,7]\n* Output: [[3,0],\n*          [1,7]]\n* Explanation:\n* 0th row: 3 + 0 = 0 == rowSum[0]\n* 1st row: 1 + 7 = 8 == rowSum[1]\n* 0th column: 3 + 1 = 4 == colSum[0]\n* 1st column: 0 + 7 = 7 == colSum[1]\n* The row and column sums match, and all matrix elements are non-negative.\n* Another possible matrix is: [[1,2],\n*                             [3,5]]\n* Example 2:\n*\n* Input: rowSum = [5,7,10], colSum = [8,6,8]\n* Output: [[0,5,0],\n*         [6,1,0],\n*         [2,0,8]]\n* Example 3:\n*\n* Input: rowSum = [14,9], colSum = [6,9,8]\n* Output: [[0,9,5],\n*          [6,0,3]]\n* Example 4:\n*\n* Input: rowSum = [1,0], colSum = [1]\n* Output: [[1],\n*         [0]]\n* Example 5:\n*\n* Input: rowSum = [0], colSum = [0]\n* Output: [[0]]\n*********************************************************************************/\nclass Solution {\npublic:\n    vector<vector<int>> restoreMatrix(vector<int>& row, vector<int>& col) {\n        int n = row.size();\n        int m = col.size();\n        if(n==0 ||m==0)\n            return {};\n        vector<vector<int>> res(n,vector<int>(m,0));\n        priority_queue<pair<int,int>> p,q;\n        for(int i=0;i<n;i++){\n            p.push({row[i],i});\n        }\n        for(int j=0;j<m;j++){\n            q.push({col[j],j});\n        }\n\n        while(!q.empty() && !p.empty()){\n            auto a = p.top();\n            auto b = q.top();\n            p.pop();\n            q.pop();\n            int t = min(a.first,b.first);\n            res[a.second][b.second]=t;\n            a.first-=t;\n            b.first-=t;\n            if(a.first>0)\n                p.push(a);\n            if(b.first>0)\n                q.push(b);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/LRUCache/LRUCache.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/lru-cache/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* Design and implement a data structure for Least Recently Used (LRU) cache. \n* It should support the following operations: get and set.\n* \n*    get(key) - Get the value (will always be positive) of the key if the key exists \n*               in the cache, otherwise return -1.\n*\n*    set(key, value) - Set or insert the value if the key is not already present. \n*                      When the cache reached its capacity, it should invalidate \n*                      the least recently used item before inserting a new item.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <map>\nusing namespace std;\n\n// The idea here is quite simple:\n//    1) A Map to index the key.  O(1) key search time-complexity.\n//    2) A List to sort the cache data by accessed time.\n// \n//  Considering there are too many insert/delete opreations for the List, \n//  The ouble linked list is the good data structure to performance it.\n\nclass Node {\n    public:\n        int key;\n        int value;\n        Node *next, *prev;\n        Node(int k, int v) { key=k; value=v; next = prev = NULL; }\n        //Node(int k, int v, Node* n=NULL, Node* p=NULL): key(k), value(v), next(n), prev(p) {}\n};\n\n// the following double linked list seems a bit commplicated.\nclass DoubleLinkedList {\n\n    private:\n\n        Node *pHead, *pTail;\n        int size;\n\n\n    public:\n\n        DoubleLinkedList(){\n            pHead = pTail = NULL;\n            size = 0;\n        }\n        ~DoubleLinkedList() {\n            while(pHead!=NULL){\n                Node*p = pHead;\n                pHead = pHead->next;\n                delete p;\n            }\n        }\n\n        int Size() const {\n            return size;\n        }\n\n        Node* NewAtBegin(int key, int value) {\n            Node *n = new Node(key, value);\n            return AddAtBegin(n);\n        }\n\n        Node* NewAtEnd(int key, int value) {\n            Node *n = new Node(key, value);\n            return AddAtEnd(n);\n        }\n\n        Node* AddAtBegin(Node* n){\n            size++;\n\n            if (pHead==NULL) { \n                pHead = pTail = n; \n                return n; \n            }\n\n            n->next = pHead;\n            n->prev = NULL;\n            pHead->prev = n;\n            pHead = n;\n            return n;\n        }\n\n        Node* AddAtEnd(Node* n) {\n            size++;\n\n            if (pHead==NULL) { \n                pHead = pTail = n; \n                return n; \n            }\n\n            pTail->next = n;\n            n->prev = pTail;\n            n->next = NULL;\n            pTail = n;\n        }\n\n        void Unlink(Node* n){\n            Node* before = n->prev;\n            Node* after = n->next;\n\n            if (before){\n                before->next = after;  \n            }\n\n            if (after){ \n                after->prev = before;\n            }\n\n            if(pHead == n){\n                pHead = pHead->next;\n            }else if(pTail == n) {\n                pTail = pTail->prev;\n            }\n\n            size--;\n        }\n\n        void Delete(Node* n){\n            Unlink(n);\n            delete n;\n        }\n\n        void TakeToBegin(Node* n){\n            Unlink(n);\n            AddAtBegin(n);\n        } \n\n        Node* GetTailNode() {\n            return pTail;\n        } \n\n        void DeleteLast() {\n            Delete(pTail);\n        } \n\n        void Print(){\n            Node* p = pHead;\n            while(p!=NULL) {\n                cout << \"(\" << p->key << \",\" << p->value << \") \";\n                p = p->next;\n            }\n            cout << endl;\n        }\n};\n\n\n\nclass LRUCache{\n\n    private:\n        //cacheList - store the date\n        DoubleLinkedList cacheList;\n        //cacheMap - index the date for searching\n        map<int, Node*> cacheMap;\n        //the max capcity of cache\n        int capacity;\n\n    public:\n        LRUCache(int capacity) {\n            this->capacity = capacity;    \n        }\n        void print(){\n            cacheList.Print();\n        }\n\n        int get(int key) {\n            // The accessed node must be up-to-time -- take to the front \n            if (cacheMap.find(key) != cacheMap.end() ){\n                cacheList.TakeToBegin(cacheMap[key]);\n                return cacheMap[key]->value;\n            }\n            return -1;\n\n        }\n\n        void set(int key, int value) {\n            // key found, update the data, and take to the front \n            if (cacheMap.find(key) != cacheMap.end() ){\n                Node *p = cacheMap[key];\n                p->value = value;\n                cacheList.TakeToBegin(cacheMap[key]);\n            }else{\n                // key not found, new a node to store data\n                cacheMap[key] = cacheList.NewAtBegin(key, value);\n                // if the capacity exceed, remove the last one.\n                if( cacheList.Size() > capacity) {\n                    int key = cacheList.GetTailNode()->key; \n                    cacheMap.erase(key);\n                    cacheList.DeleteLast();\n                }\n            }\n        }\n};\n\n\nint main(int argc, char** argv) \n{\n\n    /*\n    LRUCache c(2);\n    c.set(2,1);\n    c.print();\n    c.set(2,2);\n    c.print();\n    c.get(2);\n    c.print();\n    c.set(1,1);\n    c.print();\n    c.set(4,1);\n    c.print();\n    c.get(2);\n    c.print();\n\n    cout << \"---------\" << endl;\n    */\n    srand(time(0));\n\n    int capacity = 5;\n    int test_loop_times = 10;\n    if (argc>1){\n        capacity = atoi(argv[1]);\n    }\n    if (argc>2){\n        test_loop_times = atoi(argv[1]);\n    }\n\n    LRUCache cache(capacity);\n\n    int v; \n    for(int i=0; i<test_loop_times; i++) {\n        v = i;//rand() % capacity;\n        cout << \"set \" << v << \": \";\n        cache.set(v, v);\n        cache.print();\n\n        v = rand() % capacity;\n        cout << \"get \" << v << \": \" << cache.get(v);\n        cache.print();\n\n        cout << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/NumberOfWaysToSplitString/NumberOfWaysToSplitString.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-ways-to-split-a-string/\n// Author : Sudesh Chaudhary\n// Date   : 2020-10-01\n\n/************************************************************************************************\n*     Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+   *      s2+ s3 = s).\n*\n*     Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.\n*\n*     Since the answer may be too large, return it modulo 10^9 + 7.\n*\n*     Example 1:\n*\n*     Input: s = \"10101\"\n*     Output: 4\n*     Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n*     \"1|010|1\"\n*     \"1|01|01\"\n*     \"10|10|1\"\n*     \"10|1|01\"\n*\n*\n*      Example 2:\n*\n*      Input: s = \"1001\"\n*      Output: 0\n*\n*      Example 3:\n*\n*      Input: s = \"0000\"\n*      Output: 3\n*      Explanation: There are three ways to split s in 3 parts.\n*      \"0|0|00\"\n*      \"0|00|0\"\n*      \"00|0|0\"\n*\n*      Example 4:\n*\n*      Input: s = \"100100010100110\"\n*      Output: 12\n***************************************************************************************************/\n\n// solution->\n\n// time O(n) space O(n)\n\n#define mod (long long)(1e9+7)\n#define ll long long\nclass Solution {\npublic:\n    int numWays(string s) {\n\n        int n = s.size();\n\n        vector<int> pre(n),suf(n),last(n);\n        int count=0;\n\n        for(int i=0;i<n;i++){\n            if(s[i]=='1'){\n                count++;\n            }\n            pre[i]=count;\n        }\n\n        // check if it can't be divided into three parts\n        if(count%3!=0)\n            return 0;\n\n        int k  = count/3;\n        count=0;\n        int t=0;\n\n        for(int i=n-1;i>=0;i--){\n            if(s[i]=='1')\n                count++;\n            suf[i]=count;\n        }\n\n        count=0;\n\n        for(int i=n-1;i>=0;i--){\n\n            if(suf[i]==k)\n                count++;\n            last[i]=count;\n        }\n\n        ll res=0;\n\n        for(int i=0;i<n-1;i++){\n\n            if(pre[i]==k){\n\n                if(k!=0)\n                    res= (res+last[i+1])%mod;\n                else\n                    res=(res+last[i+1]-1)%mod;\n            }\n        }\n\n        return res;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/UTF8Validation/UTF8Validation.cpp",
    "content": "// Source : https://leetcode.com/problems/utf-8-validation/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:\n * \n * For 1-byte character, the first bit is a 0, followed by its unicode code.\n * For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by \n * n-1 bytes with most significant 2 bits being 10.\n * \n * This is how the UTF-8 encoding would work:\n * \n *    Char. number range  |        UTF-8 octet sequence\n *    --------------------+---------------------------------------------\n *    0000 0000-0000 007F | 0xxxxxxx\n *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx\n *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx\n *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n * \n * Given an array of integers representing the data, return whether it is a valid utf-8 \n * encoding.\n * \n * Note:\n * The input is an array of integers. Only the least significant 8 bits of each integer \n * is used to store the data. This means each integer represents only 1 byte of data.\n * \n * Example 1:\n * \n * data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 \n * 00000001.\n * \n * Return true.\n * It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n * \n * Example 2:\n * \n * data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 \n * 00000100.\n * \n * Return false.\n * The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\n * The next byte is a continuation byte which starts with 10 and that's correct.\n * But the second continuation byte does not start with 10, so it is invalid.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    bool validUtf8(vector<int>& data) {\n        int i = 0;\n        while ( i < data.size() ) {\n            if ( (data[i] & 0x80) == 0 ){\n                i++;\n                continue;\n            }\n            \n            int len = 0;\n            if ( (data[i] & 0xE0) == 0xC0 ) { // checking 110xxxxx\n                len = 2;\n            }else if ( (data[i] & 0xF0) == 0xE0) { // checking 1110xxxx\n                len = 3;\n            }else if ( (data[i] & 0xF8) == 0xF0) { // checking 11110xxx\n                len = 4;\n            }else {\n                return false;\n            }\n            \n            // invalid utf-8 as it doesn't have enough 10xxxxxx\n            if (i + len > data.size()) {\n                return false;\n            }\n            \n            for (int j=i+1; j < i+len; j++) { //checking 10xxxxxx\n                if ( (data[j] & 0xC0) != 0x80 ) {\n                    return false;\n                }\n            }\n            \n            i += len ;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/accountsMerge/AccountsMerge.cpp",
    "content": "// Source : https://leetcode.com/problems/accounts-merge/\n// Author : Hao Chen\n// Date   : 2019-03-29\n\n/***************************************************************************************************** \n *\n * Given a list accounts, each element accounts[i] is a list of strings, where the first element \n * accounts[i][0] is a name, and the rest of the elements are emails representing emails of the \n * account.\n * \n * Now, we would like to merge these accounts.  Two accounts definitely belong to the same person if \n * there is some email that is common to both accounts.  Note that even if two accounts have the same \n * name, they may belong to different people as people could have the same name.  A person can have \n * any number of accounts initially, but all of their accounts definitely have the same name.\n * \n * After merging the accounts, return the accounts in the following format: the first element of each \n * account is the name, and the rest of the elements are emails in sorted order.  The accounts \n * themselves can be returned in any order.\n * \n * Example 1:\n * \n * Input: \n * accounts = [[\"John\", \"johnsmith@mail.com\", \"john00@mail.com\"], [\"John\", \"johnnybravo@mail.com\"], \n * [\"John\", \"johnsmith@mail.com\", \"john_newyork@mail.com\"], [\"Mary\", \"mary@mail.com\"]]\n * Output: [[\"John\", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  [\"John\", \n * \"johnnybravo@mail.com\"], [\"Mary\", \"mary@mail.com\"]]\n * \n * Explanation: \n * The first and third John's are the same person as they have the common email \"johnsmith@mail.com\".\n * The second John and Mary are different people as none of their email addresses are used by other \n * accounts.\n *\n * We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], \n * ['John', 'johnnybravo@mail.com'], \n * ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\n * \n * Note:\n * The length of accounts will be in the range [1, 1000].\n * The length of accounts[i] will be in the range [1, 10].\n * The length of accounts[i][j] will be in the range [1, 30].\n ******************************************************************************************************/\n\n\n//Bad Performance Solution\nclass Solution_Time_Limit_Exceeded {\npublic:\n    // We can orginze all relevant emails to a chain,\n    // then we can use Union Find algorithm\n    // Besides, we also need to map the relationship between name and email.\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        unordered_map<string, string> emails_chains; // email chains\n        unordered_map<string, string> names; // names to email chains' head\n\n        //initialization\n        for(int i = 0 ; i<accounts.size();i++) {\n            auto& account = accounts[i];\n            auto& name = account[0];\n            for (int j=1; j<account.size(); j++) {\n                auto& email = account[j];\n                if ( names.find(email) == names.end() ) {\n                    emails_chains[email] = email;\n                    names[email] = name;\n                }\n                join(emails_chains, account[1], email);\n            }\n        }\n\n        //reform the emails\n        unordered_map<string, set<string>> res;\n        for( auto& acc : accounts ) {\n            string e = find(emails_chains, acc[1]);\n            res[e].insert(acc.begin()+1, acc.end());\n        }\n\n        //output the result\n        vector<vector<string>> result;\n        for (auto pair : res) {\n            vector<string> emails(pair.second.begin(), pair.second.end());\n            emails.insert(emails.begin(), names[pair.first]);\n            result.push_back(emails);\n        }\n        return result;\n    }\n\n    string find(unordered_map<string, string>& emails_chains,\n                string email) {\n        while( email != emails_chains[email] ){\n            email = emails_chains[email];\n        }\n        return email;\n    }\n\n    bool join(unordered_map<string, string>& emails_chains,\n              string& email1, string& email2) {\n        string e1 = find(emails_chains, email1);\n        string e2 = find(emails_chains, email2);\n        if ( e1 != e2 )  emails_chains[e1] = email2;\n        return e1 == e2;\n    }\n};\n\n//\n// Performance Tunning\n// -----------------\n//\n// The above algorithm need to do string comparison, it causes lots of efforts\n// So, we allocated the ID for each email, and compare the ID would save the time.\n//\n// Furthermore, we can use the Group-Email-ID instead of email ID,\n// this would save more time.\n//\nclass Solution {\npublic:\n    // We can orginze all relevant emails to a chain,\n    // then we can use Union Find algorithm\n    // Besides, we also need to map the relationship between name and email.\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        unordered_map<string, int> emails_id; //using email ID for union find\n        unordered_map<int, int> emails_chains; // email chains\n        unordered_map<int, string> names; // email id & name\n\n        //initialization & join\n        for(int i = 0 ; i<accounts.size();i++) {\n\n            // using the account index as the emails group ID,\n            // this could simplify the emails chain.\n            emails_chains[i] = i;\n\n            auto& account = accounts[i];\n            auto& name = account[0];\n            for (int j=1; j<account.size(); j++) {\n                auto& email = account[j];\n                if ( emails_id.find(email) == emails_id.end() ) {\n                    emails_id[email] = i;\n                    names[i] = name;\n                }else {\n                    join( emails_chains, i, emails_id[email] );\n                }\n\n            }\n        }\n\n        //reform the emails\n        unordered_map<int, set<string>> res;\n        for(int i=0; i<accounts.size(); i++) {\n            int idx = find(emails_chains, i);\n            res[idx].insert(accounts[i].begin()+1, accounts[i].end());\n        }\n\n\n        //output the result\n        vector<vector<string>> result;\n        for (auto pair : res) {\n            vector<string> emails( pair.second.begin(), pair.second.end() );\n            emails.insert(emails.begin(), names[pair.first]);\n            result.push_back(emails);\n        }\n        return result;\n    }\n\n    int find(unordered_map<int, int>& emails_chains, int id) {\n        while( id != emails_chains[id] ){\n            id = emails_chains[id];\n        }\n        return id;\n    }\n\n    bool join(unordered_map<int, int>& emails_chains, int id1, int id2) {\n        int e1 = find(emails_chains, id1);\n        int e2 = find(emails_chains, id2);\n        if ( e1 != e2 )  emails_chains[e1] = e2;\n        return e1 == e2;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/addAndSearchWord/AddAndSearchWord.cpp",
    "content": "// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/\n// Author : Hao Chen\n// Date   : 2015-06-10\n\n/********************************************************************************** \n * \n * Design a data structure that supports the following two operations:\n * \n * void addWord(word)\n * bool search(word)\n * \n * search(word) can search a literal word or a regular expression string containing only letters `a-z` or `.`\n * A `.` means it can represent any one letter.\n * \n * For example:\n * \n *   addWord(\"bad\")\n *   addWord(\"dad\")\n *   addWord(\"mad\")\n *   search(\"pad\") -> false\n *   search(\"bad\") -> true\n *   search(\".ad\") -> true\n *   search(\"b..\") -> true\n * \n * Note:\n * You may assume that all words are consist of lowercase letters a-z.\n * \n * click to show hint.\n * \n * You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.\n * \n *               \n **********************************************************************************/\n#include <string.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\nconst int MAX_CHARS = 26;\n\n/*Trie Node*/\nclass TrieNode {\npublic:\n    TrieNode():isWord(false) {\n        memset(childern, 0, sizeof(childern));\n    }\n    TrieNode* & operator [] (char idx){\n        int i = (idx-'a') % MAX_CHARS;\n        return childern[i];\n    }\n    TrieNode* & operator [] (int idx){\n        int i = idx % MAX_CHARS;\n        return childern[i];\n    }\n    bool isWord;\nprivate:\n    TrieNode* childern[MAX_CHARS];\n};\n\n\n/*Trie Tree*/\nclass TrieTree {\npublic:\n    TrieTree():root(new TrieNode()){ }\n    ~TrieTree() { freeTree(root); }\n    \n    void put(string &s) {\n        TrieNode* node = root;\n        for (int i=0; i<s.size(); i++){\n            if ((*node)[s[i]] == NULL){\n                (*node)[s[i]] = new TrieNode();\n            }\n            node = (*node)[s[i]];\n        }\n        node->isWord = true;\n    }\n    bool search(string &s){\n        return get(s, this->root);\n    }\n\nprivate:\n\n    bool get(string &s, TrieNode* root, int idx=0){\n        TrieNode* node = root;\n        for (int i=idx; i<s.size(); i++){\n            if (s[i]!='.'){\n                node = (*node)[s[i]];\n                if (node == NULL) return false;\n            }else{\n                for (int j=0; j<MAX_CHARS; j++) {\n                    TrieNode *p = (*node)[j];\n                    if (p == NULL ) {\n                        continue;//try next\n                    }\n                    // p!=NULL\n                    if (i<s.size()-1) {\n                        if (this->get(s, p, i+1)) {\n                            return true;\n                        }\n                        continue; //try next\n                    }\n                    // p!=NULL && i == s.size()-1\n                    if (p->isWord) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n        }\n        return node->isWord; \n    }\n    \nprivate:\n    void freeTree(TrieNode* root){\n        for(int i=0; i<MAX_CHARS; i++){\n            if ((*root)[i]!=NULL){\n                freeTree((*root)[i]);\n            }\n        }\n        delete root;\n    }\n    TrieNode *root;\n};\n\nclass WordDictionary {\npublic:\n\n    // Adds a word into the data structure.\n    void addWord(string word) {\n        tree.put(word);\n    }\n\n    // Returns if the word is in the data structure. A word could\n    // contain the dot character '.' to represent any one letter.\n    bool search(string word) {\n        return tree.search(word);\n    }\nprivate:\n    TrieTree tree;\n};\n\n// Your WordDictionary object will be instantiated and called as such:\n// WordDictionary wordDictionary;\n// wordDictionary.addWord(\"word\");\n// wordDictionary.search(\"pattern\");\n\nint main()\n{\n    WordDictionary wd;\n    wd.addWord(\"a\");\n    cout << wd.search(\"a.\") <<endl;;\n    cout << wd.search(\".a\") << endl;;\n    wd.addWord(\"bad\");\n    cout << wd.search(\"bad\") <<endl;;\n    cout << wd.search(\"b..\") <<endl;;\n    return 0;\n}\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/addBinary/addBinary.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/add-binary/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Given two binary strings, return their sum (also a binary string).\n* \n* For example,\n* a = \"11\"\n* b = \"1\"\n* Return \"100\".\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nstring addBinary(string a, string b) {\n    int alen = a.size();\n    int blen = b.size();\n    bool carry = false;\n    string result;\n    while( alen>0 || blen>0) {\n        int abit = alen<=0 ? 0 : a[alen-1]-'0';\n        int bbit = blen<=0 ? 0 : b[blen-1]-'0';\n        int cbit = carry ? 1 : 0;\n        result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) );\n        carry = (abit+bbit+cbit>1);\n        alen--; blen--;\n    }\n    if (carry){\n        result.insert(result.begin(), '1');\n    }\n    return result;\n}\n\n\nint main(int argc, char** argv) \n{\n    string a = \"11\";\n    string b = \"1\";\n    if (argc>2){\n        a = argv[1];\n        b = argv[2];\n    }\n\n    cout << a << \"+\" << b << \"=\" << addBinary(a, b) << endl;\n    \n}\n"
  },
  {
    "path": "algorithms/cpp/addDigits/addDigits.cpp",
    "content": "// Source : https://leetcode.com/problems/add-digits/\n// Author : Timothy Lim, Hao Chen\n// Date   : 2015-10-1\n\n/********************************************************************************** \n * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.\n *\n * For example:\n * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.\n *\n * Follow up:\n * \tCould you do it without any loop/recursion in O(1) runtime?\n *\n **********************************************************************************/\n\nclass Solution {\n    public:\n\n        int addDigits(int num) {\n            switch(random()%5+1){\n                case 1: return addDigits01(num);\n                case 2: return addDigits02(num);\n                case 3: return addDigits03(num);\n                case 4: return addDigits04(num);\n                default: return addDigits05(num);\n            }\n\n        }\n\n        //regualr way\n        int addDigits01(int num) {\n            while(num > 9) {\n                int sum;\n                for(sum=0; num > 0; sum += num%10 , num/=10);\n                num = sum;\n            }\n            return num;\n\n        }\n\n        //This solution looks is very tricky, but acutally it is easy to understand.\n        //it just keep adding the last digital until the num < 10\n        int addDigits02(int num) {\n            while(num > 9) {\n                num = num / 10 + num % 10;\n            }\n            return num;\n\n        }\n\n        // Let's observe the pattern\n        //    1    1\n        //    2    2\n        //    ... ...\n        //    8    8    \n        //    9    9    \n        //    10    1\n        //    11    2\n        //    12    3    \n        //    ... ...\n        //    17    8\n        //    18    9\n        //    19    1\n        //    20    2\n        //    ...  ...\n        // It looks most of number just simply %9 is the answer, \n        // but there are some edge cases.\n        //    9%9=0 but we need 9. \n        //    18%9=0 but we need 9\n        // so we can find the solution is:\n        //    1) num <=9, return num\n        //    2) num > 9, reutrn num%9 if num%9>0\n        //                return 9 if num%9 ==0\n        int addDigits03(int num) {\n            return num >9 ? ((num %9)==0 ? 9:num%9) : num;\n        }\n\n        //But actually, we can use (num-1)%9 + 1 to make all cases right.\n        int addDigits04(int num){\n            return (num - 1) % 9 + 1;\n        }\n\n        //This solution is similar with pervious solution.\n        int addDigits05(int num){\n            return num - 9 * ((num - 1)/9);\n        }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/addStrings/AddStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/add-strings/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * Given two non-negative numbers num1 and num2 represented as string, return the sum \n * of num1 and num2.\n * \n * Note:\n * \n * The length of both num1 and num2 is \n * Both num1 and num2 contains only digits 0-9.\n * Both num1 and num2 does not contain any leading zero.\n * You must not use any built-in BigInteger library or convert the inputs to integer \n * directly.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    string addStrings(string num1, string num2) {\n        string& longstr  = ( num1.size() >= num2.size() ? num1 : num2 );\n        string& shortstr = ( num1.size() <  num2.size() ? num1 : num2 );\n        \n        int longlen = longstr.size();\n        int shortlen = shortstr.size();\n        \n        char carry = 0;\n        int i, j;\n        \n        string result;\n        for (i = longlen-1, j=shortlen-1; i>=0; i--, j--) {\n            int add = 0;\n            if (j>=0) {\n                add = longstr[i] + shortstr[j] - 2 * '0' + carry;\n            }else{\n                add = longstr[i] - '0' + carry;\n            }\n            carry = add/10;\n            result = char('0' + add % 10) + result;\n        }\n        \n        if (carry) {\n            result = '1' + result;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/addToArrayFormOfInteger/AddToArrayFormOfInteger.cpp",
    "content": "// Source : https://leetcode.com/problems/add-to-array-form-of-integer/\n// Author : Hao Chen\n// Date   : 2019-03-25\n\n/***************************************************************************************************** \n *\n * For a non-negative integer X, the array-form of X is an array of its digits in left to right order. \n *  For example, if X = 1231, then the array form is [1,2,3,1].\n * \n * Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.\n * \n * Example 1:\n * \n * Input: A = [1,2,0,0], K = 34\n * Output: [1,2,3,4]\n * Explanation: 1200 + 34 = 1234\n * \n * Example 2:\n * \n * Input: A = [2,7,4], K = 181\n * Output: [4,5,5]\n * Explanation: 274 + 181 = 455\n * \n * Example 3:\n * \n * Input: A = [2,1,5], K = 806\n * Output: [1,0,2,1]\n * Explanation: 215 + 806 = 1021\n * \n * Example 4:\n * \n * Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1\n * Output: [1,0,0,0,0,0,0,0,0,0,0]\n * Explanation: 9999999999 + 1 = 10000000000\n * \n * Note：\n * \n * \t1 <= A.length <= 10000\n * \t0 <= A[i] <= 9\n * \t0 <= K <= 10000\n * \tIf A.length > 1, then A[0] != 0\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> addToArrayForm(vector<int>& A, int K) {\n        int carry = K;\n        for (int i = A.size() - 1; i >= 0 && carry > 0; i--) {\n            int a = A[i] + carry;\n            A[i] = a % 10 ;\n            carry = a / 10;\n        }\n\n        while ( carry > 0 ) {\n            A.insert(A.begin(), carry%10);\n            carry /= 10;\n        }\n\n        return A;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/add-two-numbers/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* You are given two linked lists representing two non-negative numbers. \n* The digits are stored in reverse order and each of their nodes contain a single digit. \n* Add the two numbers and return it as a linked list.\n* \n* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\n* Output: 7 -> 0 -> 8\n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\n    \npublic:\n    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {\n        int x=0, y=0, carry=0, sum=0;\n        ListNode *h=NULL, **t=&h;\n        \n        while (l1!=NULL || l2!=NULL){\n            x = getValueAndMoveNext(l1);\n            y = getValueAndMoveNext(l2);\n            \n            sum = carry + x + y;\n            \n            ListNode *node = new ListNode(sum%10);\n            *t = node;\n            t = (&node->next);\n            \n            carry = sum/10;\n        }\n        \n        if (carry > 0) {\n            ListNode *node = new ListNode(carry%10);\n            *t = node;\n        }\n        \n        return h;\n    }\nprivate:\n    int getValueAndMoveNext(ListNode* &l){\n        int x = 0;\n        if (l != NULL){\n            x = l->val;\n            l = l->next;\n        }\n        return x;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/additiveNumber/AdditiveNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/additive-number/\n// Author : Hao Chen\n// Date   : 2015-11-22\n\n/*************************************************************************************** \n *\n * Additive number is a positive integer whose digits can form additive sequence.\n * \n * A valid additive sequence should contain at least three numbers. Except for the \n * first two numbers, each subsequent number in the sequence must be the sum of the \n * preceding two.\n * \n * For example:\n * \"112358\" is an additive number because the digits can form an additive sequence: 1, \n * 1, 2, 3, 5, 8.\n * 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n * \"199100199\" is also an additive number, the additive sequence is: 1, 99, 100, 199.\n * 1 + 99 = 100, 99 + 100 = 199\n * \n * Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, \n * 03 or 1, 02, 3 is invalid.\n * \n * Given a string represents an integer, write a function to determine if it's an \n * additive number.\n * \n * Follow up:\n * How would you handle overflow for very large input integers?\n * \n * Credits:Special thanks to @jeantimex for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    bool isAdditiveNumber(string num) {\n        int len = num.size();\n        \n        for(int i=1; i<len/2+1; i++) {\n            string n1 = num.substr(0, i);\n            if ( n1.size()>1 && n1[0] == '0') break;\n            for(int j=i+1; j<len; j++) {\n                string n2 = num.substr(i, j-i);\n                if ( n2.size()>1 && n2[0] == '0') break;\n                string n3 = num.substr(j);\n                if (isAdditiveNumberHelper(n1, n2, n3)) return true;\n            }\n        }\n        return false;\n    }\n    \nprivate:\n    bool isAdditiveNumberHelper(string& n1, string& n2, string& n3){\n        string add = StringAdd(n1, n2);\n        \n        if (add.size() > n3.size()) return false;\n        \n        if (add == n3 ) return true;\n        \n        //split the n3 to 2 parts, and keep going.\n        string cut = n3.substr(0, add.size());\n        if (add == cut) {\n            string rest = n3.substr(add.size());\n            return isAdditiveNumberHelper(n2, add, rest);\n        }\n        return false;\n    }\n\n\n    string StringAdd(string n1, string n2) {\n        \n        if (n1.size() < n2.size()) {\n            string tmp = n1;\n            n1 = n2;\n            n2 = tmp;\n        }\n        \n        int carry=0;\n        string result;\n        for (int i=n1.size()-1, j=n2.size()-1; i>=0; i--, j--) {\n\n            int n = n1[i] - '0' + carry;\n            if ( j >= 0) {\n                n += n2[j] - '0';\n            } \n            char ch = n % 10 + '0';\n            carry = n/10;\n            result = ch + result;\n        }\n        if (carry>0) result = (char)(carry+'0') + result;\n        return result;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/anagrams/GroupAnagrams.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/anagrams/\n// Author : Hao Chen\n// Date   : 2014-07-18\n\n/********************************************************************************** \n * \n * Given an array of strings, group anagrams together.\n * \n * For example, given: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"], \n * Return:\n * \n * [\n *   [\"ate\", \"eat\",\"tea\"],\n *   [\"nat\",\"tan\"],\n *   [\"bat\"]\n * ]\n * \n * Note:\n * \n * For the return value, each inner list's elements must follow the lexicographic order.\n * All inputs will be in lower-case.\n * \n * Update (2015-08-09):\n * The signature of the function had been updated to return list<list<string>> instead \n * of list<string>, as suggested here. If you still see your function signature return \n * a list<string>, please click the reload button  to reset your code definition.\n * \n **********************************************************************************/\n\nclass Solution {\npublic:\n    vector< vector<string> > groupAnagrams(vector<string> &strs) {\n        vector< vector<string> > result;\n        map<string, int> m;\n        for(int i=0; i<strs.size(); i++){\n            string word = strs[i];\n            sort(word.begin(), word.end());\n            if (m.find(word)==m.end()){\n                vector<string> v;\n                v.push_back(strs[i]);\n                result.push_back(v);\n                m[word] = result.size()-1;\n                \n            }else{\n                result[m[word]].push_back(strs[i]);\n            }\n        }\n        \n        for(int i=0; i<result.size(); i++){\n            sort(result[i].begin(), result[i].end());\n        }\n        return result;\n    }\n     \n    //using multiset \n    vector< vector<string> > groupAnagrams01(vector<string> &strs) {\n        vector< vector<string> > result;\n        map<string, multiset<string>> m;\n        for(int i=0; i<strs.size(); i++){\n            string word = strs[i];\n            sort(word.begin(), word.end());\n            m[word].insert(strs[i]);\n        }\n        \n        for(auto item : m){\n            vector<string> v(item.second.begin(), item.second.end());\n            result.push_back(v);\n        }\n        return result;\n    }\n\n\n    //NOTICE: the below solution has been depracated as the problem has been updated!\n    vector<string> anagrams(vector<string> &strs) {\n        vector<string> result;\n        map<string, int> m;\n        for(int i=0; i<strs.size(); i++){\n            string word = strs[i];\n            //sort it can easy to check they are anagrams or not\n            sort(word.begin(), word.end());  \n            if (m.find(word)==m.end()){\n                m[word] = i;\n            }else{\n                if (m[word]>=0){\n                    result.push_back(strs[m[word]]);\n                    m[word]=-1;\n                }\n                result.push_back(strs[i]);\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/anagrams/ValidAnagram.cpp",
    "content": "// Source : https://leetcode.com/problems/valid-anagram/\n// Author : Hao Chen\n// Date   : 2015-08-16\n\n/********************************************************************************** \n * \n * Given two strings s and t, write a function to determine if t is an anagram of s. \n * \n * For example,\n * s = \"anagram\", t = \"nagaram\", return true.\n * s = \"rat\", t = \"car\", return false.\n * \n * Note:\n * You may assume the string contains only lowercase alphabets.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n\n    //stupid way - but easy to understand  - 76ms\n    bool isAnagram01(string s, string t) {\n        sort(s.begin(), s.end());\n        sort(t.begin(), t.end());\n        return s == t;\n    }\n    \n    //using a map to count every chars in the string.\n    bool isAnagram02(string s, string t) {\n        int map[26] ={0} ; //only lowercase alphabets\n        //memset(map, 0, sizeof(map));\n        \n        // count each char for s\n        for (int i=0; i<s.size(); i++) {\n            map[s[i]-'a']++;\n        }\n        // decrease the count for t\n        for (int i=0; i<t.size(); i++) {\n            map[t[i]-'a']--;\n        }\n        \n        //if all alphabets is zero, then they are anagram \n        for (int i=0; i<sizeof(map)/sizeof(map[0]); i++) {\n            if (map[i]!=0) return false;\n        }\n        return true;\n    }\n    \n\n    \n    bool isAnagram(string s, string t) {\n        return isAnagram02(s,t); //12ms\n        return isAnagram01(s,t); //76ms\n    }\n    \n};\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp",
    "content": "// Source : https://leetcode.com/problems/arithmetic-slices/\n// Author : Hao Chen\n// Date   : 2016-11-13\n\n/*************************************************************************************** \n *\n * A sequence of number is called arithmetic if it consists of at least three elements \n * and if the difference between any two consecutive elements is the same.\n * \n * For example, these are arithmetic sequence:\n * 1, 3, 5, 7, 9\n * 7, 7, 7, 7\n * 3, -1, -5, -9\n * \n * The following sequence is not arithmetic. 1, 1, 2, 5, 7 \n * \n * A zero-indexed array A consisting of N numbers is given. A slice of that array is \n * any pair of integers (P, Q) such that 0 \n * \n * A slice (P, Q) of array A is called arithmetic if the sequence:\n *     A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means \n * that P + 1 \n * \n * The function should return the number of arithmetic slices in the array A. \n * \n * Example:\n * \n * A = [1, 2, 3, 4]\n * \n * return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] \n * itself.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    //\n    // It's easy to find out how many 3-length slices in an arithmetic array with N length.\n    //\n    //   len = 3, then  1 slices, sum(1)\n    //   len = 4, then  3 slices, sum(1,2) - TWO 3-length slices + ONE 4-length slice\n    //   len = 5, then  6 slices, sum(1,2,3) - THREE 3-length slices + TWO 4-length slices + ONE 5-length slice\n    //   len = 6, then 10 slices, sum(1,2,3,4) - ...\n    //   len = 7, then 15 slices, sum(1,2,3,4,5) - ..\n    //\n    // So, with N length arithmetic array, there are Sum[1, N-3+1] 3-length slices\n    //\n    // And, we know the formula sum from 1 to n is:\n    //\n    //                  n * ( n + 1 )\n    //    sum [1, n] = ---------------\n    //                       2\n    // Then, we could have the solution - O(n) Time with O(1) Space\n    //\n    \n    int sum1toN(int n) {\n        return n * (n+1) / 2;\n    }\n\n    int numberOfArithmeticSlices(vector<int>& A) {\n        int result = 0;\n        int len = 0; // the current length of arithmetic\n        for (int i=2; i<A.size(); i++) {\n            if (A[i] - A[i-1] == A[i-1] - A[i-2]) {\n                len++;\n            }else{\n                result += sum1toN(len);\n                len=0;\n            }\n        }\n        return len==0 ? result : result + sum1toN(len);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/backspaceStringCompare/BackspaceStringCompare.cpp",
    "content": "// Source : https://leetcode.com/problems/backspace-string-compare/description/\n// Author : Hao Chen\n// Date   : 2018-06-29\n\n/*************************************************************************************** \n *\n * Given two strings S and T, return if they are equal when both are typed into empty \n * text editors. # means a backspace character.\n * \n * \n * Example 1:\n * \n * \n * Input: S = \"ab#c\", T = \"ad#c\"\n * Output: true\n * Explanation: Both S and T become \"ac\".\n * \n * \n * \n * Example 2:\n * \n * \n * Input: S = \"ab##\", T = \"c#d#\"\n * Output: true\n * Explanation: Both S and T become \"\".\n * \n * \n * \n * Example 3:\n * \n * \n * Input: S = \"a##c\", T = \"#a#c\"\n * Output: true\n * Explanation: Both S and T become \"c\".\n * \n * \n * \n * Example 4:\n * \n * \n * Input: S = \"a#c\", T = \"b\"\n * Output: false\n * Explanation: S becomes \"c\" while T becomes \"b\".\n * \n * \n * Note:\n * \n * \n * \t1 <= S.length <= 200\n * \t1 <= T.length <= 200\n * \tS and T only contain lowercase letters and '#' characters.\n * \n * \n * Follow up:\n * \n * \n * \tCan you solve it in O(N) time and O(1) space?\n * \n * \n * \n * \n ***************************************************************************************/\n\nclass Solution {\nprivate:    \n    void removeBackspaces(string &s) {\n        int i = 0;\n        for(int i=0; i<s.size(); i++) {\n            if (s[i] == '#') {\n                int backSteps = i>0 ? 2 : 1;\n                s.erase(i-backSteps + 1, backSteps);\n                i -= backSteps;\n            } \n        }\n    }\n    \npublic:\n    bool backspaceCompare(string S, string T) {\n        removeBackspaces(S);\n        removeBackspaces(T);\n        return S == T;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/balancedBinaryTree/balancedBinaryTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/balanced-binary-tree/\n// Author : Hao Chen\n// Date   : 2014-06-28\n\n/********************************************************************************** \n* \n* Given a binary tree, determine if it is height-balanced.\n* \n* For this problem, a height-balanced binary tree is defined as a binary tree in which \n* the depth of the two subtrees of every node never differ by more than 1.\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isBalanced(TreeNode *root) {\n        int height=0;\n        return isBalancedUtil(root, height);\n    }\n\n    bool isBalancedUtil(TreeNode* root, int& height){\n       if(root==NULL){\n          height=0;\n          return true;\n       }\n       int lh=0, rh=0;\n       bool isLeft = isBalancedUtil(root->left, lh);\n       bool isRight = isBalancedUtil(root->right, rh);\n       height = (lh > rh ? lh : rh) + 1;\n       return (abs(lh-rh)<=1 && isLeft && isRight);\n    }\n\n};\n\n//Notes: \n// I think the above solution should be more efficent than the below, \n//  but for leetcode, the below solution needs 60ms, the above needs 88ms\nclass Solution {\npublic:\n    bool isBalanced(TreeNode *root) {\n        if (root==NULL) return true;\n        \n        int left = treeDepth(root->left); \n        int right = treeDepth(root->right);\n        \n        if (left-right>1 || left-right < -1) {\n            return false;\n        }\n        return isBalanced(root->left) && isBalanced(root->right);\n    }\n    \n    int treeDepth(TreeNode *root) {\n        if (root==NULL){\n            return 0;\n        }\n\n        int left=1, right=1;\n        \n        left += treeDepth(root->left);\n        right += treeDepth(root->right);\n        \n        return left>right?left:right;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/basicCalculator/BasicCalculator.II.cpp",
    "content": "// Source : https://leetcode.com/problems/basic-calculator-ii/\n// Author : Hao Chen\n// Date   : 2015-06-24\n\n/********************************************************************************** \n * \n * Implement a basic calculator to evaluate a simple expression string.\n * \n * The expression string contains only non-negative integers, +, -, *, / operators and empty spaces  . \n * The integer division should truncate toward zero.\n * \n * You may assume that the given expression is always valid.\n * \n * Some examples:\n * \n * \"3+2*2\" = 7\n * \" 3/2 \" = 1\n * \" 3+5 / 2 \" = 5\n * \n * Note: Do not use the eval built-in library function.\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n **********************************************************************************/\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <stack>\nusing namespace std;\n\n/* \n * Acuatlly, everything I've already implemented in \"Basic Calculator\"(RPN way and Design pattern way).\n * So, here, I just use the quick-dirty way - just like the \"two stacks solution\" in \"Basic Calulator\".\n */\n\n\n//Quick & Dirty Solution\nbool isOperator(const char ch) {\n    return (ch=='+' || ch=='-' || ch=='*' || ch=='/');\n}\n\n\nint Priority(const char c) {\n    if (c == '*' || c == '/') {\n        return 2;\n    } else if (c== '+' || c == '-') {\n        return 1;\n    } else {\n        return 0;\n    }\n}\n\nlong long calculate_exp(long long x, long long y, char op) {\n    switch(op) {\n        case '+': return x + y;\n        case '-': return x - y;\n        case '*': return x * y;\n        case '/': return x / y;\n    }\n    return -1;\n}\n\n\n//Two Stacks solution\nint calculate_two_stacks(string& s) {\n\n    s += \"+0\";\n    stack<long long> num_stack; //put the number\n    stack<char> op_stack; //put the operations\n\n    #define CALCULATE_IT { \\\n        long long y = num_stack.top(); num_stack.pop(); \\\n        long long x = num_stack.top(); num_stack.pop(); \\\n        char op = op_stack.top(); op_stack.pop(); \\\n        num_stack.push(calculate_exp(x, y, op));\\\n    }\n\n    for(int i = 0; i < s.size(); i++){\n        char ch = s[i];\n        if (isspace(ch)) continue;\n        if (isdigit(ch)) {\n            string num;\n            num += s[i];\n            while(isdigit(s[i+1])){\n                num += s[i+1];\n                i++;\n            }\n            num_stack.push(stoll(num));\n            continue;\n        }\n        if (isOperator(ch)) {\n            while (!op_stack.empty() && Priority(op_stack.top()) >= Priority(ch) ) {\n                CALCULATE_IT;\n            }\n\n            op_stack.push(ch);\n        }\n\n    }\n\n    while(!op_stack.empty()){\n        CALCULATE_IT;\n    }\n    \n    return num_stack.top();\n}\n\n\nint calculate(string s) {\n    return calculate_two_stacks(s);\n}\n\nint main(int argc, char**argv) \n{\n    string exp = \" 3+5 / 2 \";\n    if (argc>1) {\n        exp = argv[1];\n    }\n\n    cout << \"\\\"\" << exp << \"\\\" = \" << calculate(exp) << endl;\n\n}\n\n"
  },
  {
    "path": "algorithms/cpp/basicCalculator/BasicCalculator.cpp",
    "content": "// Source : https://leetcode.com/problems/basic-calculator/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Implement a basic calculator to evaluate a simple expression string.\n * \n * The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, \n * non-negative integers and empty spaces  .\n * \n * You may assume that the given expression is always valid.\n * \n * Some examples:\n * \n * \"1 + 1\" = 2\n * \" 2-1 + 2 \" = 3\n * \"(1+(4+5+2)-3)+(6+8)\" = 23\n * \n * Note: Do not use the eval built-in library function.\n * \n *               \n **********************************************************************************/\n#include <stdlib.h>\n#include <ctype.h>\n#include <iostream>\n#include <string>\n#include <stack>\n#include <vector>\nusing namespace std;\n\n/*\n * Sorry, I cannot help using Design Pattern  ;-)\n * (https://en.wikipedia.org/wiki/Interpreter_pattern)\n *\n * Two Stack is cheap, design pattern is powerful!   ;-)\n * \n * But WTF, Memory Limit Exceeded!! Shit!!\n */\n\nclass Expression \n{\n    public:\n        virtual int interpret() = 0;\n        virtual ~Expression() {};\n};\n\nclass Number: public Expression \n{\n\n    public:\n        Number(string num) { this->number = atoi(num.c_str()); }\n        ~Number() { }\n        int interpret() { return number; }\n    private:\n        int number;\n};\n\nclass Plus : public Expression \n{\n    public:\n        Plus(Expression* left, Expression* right) :leftOperand(left), rightOperand(right) { } \n        ~Plus() { delete leftOperand; delete rightOperand; }\n        int interpret() { return leftOperand->interpret() + rightOperand->interpret(); }\n    private:\n        Expression* leftOperand;\n        Expression* rightOperand;\n};\n\nclass Minus : public Expression \n{\n    public:\n        Minus(Expression* left, Expression* right) :leftOperand(left), rightOperand(right) { } \n        ~Minus() { delete leftOperand; delete rightOperand; }\n        int interpret() { return leftOperand->interpret() - rightOperand->interpret(); }\n    private:\n        Expression* leftOperand;\n        Expression* rightOperand;\n};\n\nclass Multiply : public Expression\n{\n    public:\n        Multiply(Expression* left, Expression* right) :leftOperand(left), rightOperand(right) { }\n        ~Multiply() { delete leftOperand; delete rightOperand; }\n        int interpret() { return leftOperand->interpret() * rightOperand->interpret(); }\n    private:\n        Expression* leftOperand;\n        Expression* rightOperand;\n};\n\nclass Divide : public Expression\n{\n    public:\n        Divide(Expression* left, Expression* right) :leftOperand(left), rightOperand(right) { }\n        ~Divide() { delete leftOperand; delete rightOperand; }\n        int interpret() { return leftOperand->interpret() / rightOperand->interpret(); }\n    private:\n        Expression* leftOperand;\n        Expression* rightOperand;\n};\n\nbool isOperator(const string &c) {\n    return (c == \"+\" || c == \"-\" || c == \"*\" || c == \"/\" );\n}\nbool isOperator(const char &c) {\n    return (c == '+' || c == '-' || c == '*' || c == '/'); \n}\n\nclass Evaluator : public Expression \n{\n    private:\n        Expression* syntaxTree;\n\n    public: \n        Evaluator(vector<string>& s) \n        {\n            vector<Expression*> stack;\n            for (unsigned int i=0; i < s.size(); i++) {\n                if (isOperator(s[i])) {\n                    Expression* left  = stack.back(); stack.pop_back();\n                    Expression* right = stack.back(); stack.pop_back();\n                    switch(s[i][0]) { \n                        case '+' : \n                            stack.push_back(new Plus(right, left)); break;\n                        case '-' :\n                            stack.push_back(new Minus(right, left)); break;\n                        case '*' :\n                            stack.push_back(new Multiply(right, left)); break;\n                        case '/' :\n                            stack.push_back(new Divide(right, left)); break;\n                    }\n\n                }else{                        \n                    stack.push_back(new Number(s[i]));\n                }\n            }\n            syntaxTree = stack.back();\n        }\n        ~Evaluator() {\n            delete syntaxTree; \n        }\n\n        int interpret() {\n            return syntaxTree->interpret();\n        }\n};\n\n\n\n\nvector<string> Parse(string& s){\n    vector<string> exp;\n    for(int i=0; i<s.size(); ){\n        char c = s[i];\n        string token;\n        if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' ) {\n            exp.push_back(token+c);\n            i++;\n            continue;\n        }\n        if ( isdigit(c) ) {\n            while( isdigit(s[i]) ) {\n                token.push_back(s[i++]);\n            }\n            exp.push_back(token);\n            continue;\n        }\n        i++;\n    }\n    return exp;\n}\n\n\nint Priority(const string &c) {\n    if (c == \"*\" || c == \"/\") {\n        return 2;\n    } else if (c== \"+\" || c == \"-\") {\n        return 1;\n    } else {\n        return 0;\n    }\n}\n\nvector<string> Infix2RPN(vector<string>& infix) {\n    vector<string> rpn;\n    stack<string> s;\n\n    for(int i = 0; i < infix.size(); i++) {\n        if(isdigit(infix[i][0])) { //number\n            rpn.push_back(infix[i]);\n        } else if (infix[i] == \"(\") {\n            s.push(infix[i]);\n        } else if (infix[i] == \")\") {\n            while(!s.empty() && s.top() != \"(\") {\n                rpn.push_back(s.top());\n                s.pop();\n            }\n            s.pop();\n        }else if(isOperator(infix[i]) ){\n            while(!s.empty() && Priority(s.top()) >= Priority(infix[i])) {\n                rpn.push_back(s.top());\n                s.pop();\n            }\n            s.push(infix[i]);\n        }\n    }\n    while(!s.empty()) {\n        rpn.push_back(s.top());\n        s.pop();\n    }\n\n\n    return rpn;\n}\n\n//Design Pattern for RPN - Memory Limit Exceeded!!\nint calculate_RPN_design_pattern(string& s) {\n    vector<string> exp = Parse(s);\n    //for (int i=0; i<exp.size(); i++){\n    //    cout << exp[i] << \" \";\n    //}\n    //cout << endl;\n    exp = Infix2RPN(exp);\n    for (int i=0; i<exp.size(); i++){\n        cout << exp[i] << \" \";\n    }\n    cout << endl;\n    Evaluator sentence(exp);\n    return sentence.interpret();\n}\n\n\n/*\n *  RPN - Reverse Polish Notation\n *  see:  https://en.wikipedia.org/wiki/Reverse_Polish_notation\n */\n\n//RPN evluation - Memory Limit Exceeded!!\nint calculate_RPN_evluation(string& s) {\n    vector<string> exp = Parse(s);\n    exp = Infix2RPN(exp);\n\n    stack<int> ss;\n    for(int i=0; i<exp.size(); i++) {\n        if (isdigit(exp[i][0])) { \n            ss.push(atoi(exp[i].c_str()));\n        }\n        if (exp[i]==\"+\" || exp[i]==\"-\") {\n            int rhs = ss.top(); ss.pop();\n            int lhs = ss.top(); ss.pop();\n            if (exp[i]==\"-\") rhs = -rhs;\n            ss.push(lhs + rhs);\n        }\n    }\n    return ss.top();\n}\n\n\n\n//Two stack solution - quick & dirty solution\ninline void calculate_two_stacks(stack<int>& num_stack, stack<char>& op_stack) {\n    int lhs = num_stack.top(); num_stack.pop();\n    int rhs = num_stack.top(); num_stack.pop();\n    char op = op_stack.top(); op_stack.pop();\n    if (op=='-') rhs = -rhs;\n    num_stack.push(lhs + rhs);\n}\nint calculate_two_stacks(string& s) {\n    stack<int> num_stack; //put the number\n    stack<char> op_stack; //put the operations\n\n    for(int i = s.size() - 1; i >= 0; i--){\n        if(s[i] == ')' || s[i] == '+' || s[i] == '-') {\n            op_stack.push(s[i]);\n        } else if(isdigit(s[i])){\n            string num;\n            num += s[i];\n            while(isdigit(s[i-1])){\n                num.insert(num.begin(), s[i-1]);\n                i--;\n            }\n            num_stack.push(atoi(num.c_str())); \n        } else if(s[i] == '('){\n            while(op_stack.top() != ')') {\n                calculate_two_stacks(num_stack, op_stack);\n            }\n            op_stack.pop();\n        }\n    }\n    while(!op_stack.empty()){ \n        calculate_two_stacks(num_stack, op_stack);\n    }\n    return num_stack.top();\n}\n\n\nint calculate(string s) {\n    return calculate_two_stacks(s);\n    return calculate_RPN_evluation(s);\n    return calculate_RPN_design_pattern(s);\n}\n\nint main(int argc, char** argv) {\n    string s = \" 15-(1+3)+(2+1) \";\n    if (argc >1){\n        s = argv[1];\n    } \n    cout << s << \" = \" << calculate(s) << endl;\n    cout << \"---------------\" << endl;\n    s = \"(2+4)-(6+(1+5))\";\n    cout << s << \" = \" << calculate(s) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/BestTimeToBuyAndSellStockWithCooldown.cpp",
    "content": "// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/\n// Author : Hao Chen\n// Date   : 2019-02-01\n\n/***************************************************************************************************** \n *\n * Say you have an array for which the ith element is the price of a given stock on day i.\n * \n * Design an algorithm to find the maximum profit. You may complete as many transactions as you like \n * (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\n * \n * \tYou may not engage in multiple transactions at the same time (ie, you must sell the stock \n * before you buy again).\n * \tAfter you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\n * \n * Example:\n * \n * Input: [1,2,3,0,2]\n * Output: 3 \n * Explanation: transactions = [buy, sell, cooldown, buy, sell]\n ******************************************************************************************************/\nclass Solution {\npublic:\n    //\n    //Define \n    //\n    //  - buy[i] as the max profit when you buy the stock at day i. \n    //  - sell[i] as the max profit when you sell the stock at day i. \n    //\n    // Therefore set buy[0] = -prices[0], because spend the money, the profit is -prices[0].\n    // Also set sell[0] = 0, that you do nothing in the first day.\n    //\n    // So,\n    //     buy[i] = max(buy[i-1],                // do nothing - keep holding\n    //                  sell[i-2] - prices[i] )  // sell previous day, buy today\n    //                                           // i-1 is cooldown day\n    //     sell[i] = max(sell[i-1],              // do nothing \n    //                   buy[i-1] + prices[i] )  // buy previous day, sell today.\n    //  \n    \n    int maxProfit(vector<int>& prices) {\n        int len = prices.size();\n        if ( len < 2 ) return 0;\n        \n        vector<int> buy(len, 0);\n        vector<int> sell(len, 0);\n        \n        //day 0\n        buy[0] = -prices[0];\n        sell[0] = 0;\n        \n        //day 1\n        buy[1] = max(buy[0], 0 - prices[1]);\n        sell[1] = max(sell[0], buy[0] + prices[1]);\n        \n        for (int i=2; i<len; i++) {\n            buy[i]  = max( buy[i - 1], sell[i - 2] - prices[i]);   \n            sell[i] = max(sell[i - 1],  buy[i - 1] + prices[i]);\n        }\n        \n        return sell[len-1];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/BestTimeToBuyAndSellStockWithTransactionFee.cpp",
    "content": "// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee\n// Author : Hao Chen\n// Date   : 2019-02-01\n\n/***************************************************************************************************** \n *\n * Your are given an array of integers prices, for which the i-th element is the price of a given \n * stock on day i; and a non-negative integer fee representing a transaction fee.\n *\n * You may complete as many transactions as you like, but you need to pay the transaction fee for each \n * transaction.  You may not buy more than 1 share of a stock at a time (ie. you must sell the stock \n * share before you buy again.)\n *\n * Return the maximum profit you can make.\n * \n * Example 1:\n * \n * Input: prices = [1, 3, 2, 8, 4, 9], fee = 2\n * Output: 8\n *\n * Explanation: The maximum profit can be achieved by:\n * Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The \n * total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n * \n * Note:\n * 0 < prices.length <= 50000.\n * 0 < prices[i] < 50000.\n * 0 <= fee < 50000.\n ******************************************************************************************************/\n\n\n\nclass Solution {\nprivate:\n    int max(int x, int y) {\n        return x > y ? x: y;\n    }\n    int max(int x, int y, int z) {\n        return max(x, max(y,z));\n    }\n\npublic:\n\n    int maxProfit(vector<int>& prices, int fee) {\n        return maxProfit_dp03(prices, fee); // 100ms\n        return maxProfit_dp02(prices, fee); // 100ms\n        return maxProfit_dp01(prices, fee); // 2700ms\n    }\n\n    // find the [buy-low, sell-high] prices pairs,\n    // and remove the unnecessary prices.\n    void genPricesPairs(vector<int> &prices, vector< pair<int, int> > &prices_pairs, int fee){\n\n        int low = -1;\n        for (int i=0; i<prices.size()-1; i++){\n            //meet the valley, then goes up\n            if (prices[i] < prices[i+1] && low < 0 ) {\n                low = i;\n            }\n            //meet the peak, then goes down\n            if (prices[i] > prices[i+1] && low >= 0) {\n                prices_pairs.push_back( make_pair( prices[low], prices[i]) );\n                low = -1; // reset the `low` & `high`\n            }\n        }\n\n        // edge case\n        if ( low >= 0 ) {\n            prices_pairs.push_back( make_pair( prices[low], prices[prices.size()-1] ) );\n        }\n\n    }\n\n    int maxProfit_dp01(vector<int> &prices, int &fee) {\n\n        vector< pair<int, int> > prices_pairs;\n        genPricesPairs(prices, prices_pairs, fee);\n\n        vector<int> dp(prices_pairs.size()+1, 0);\n\n        for (int i=0; i<prices_pairs.size(); i++) {\n            for ( int j=0; j<=i; j++ ) {\n                int profit = prices_pairs[i].second - prices_pairs[j].first - fee;\n                // if the profit is negative, skip the transaction\n                if ( profit < 0 ) profit = 0;\n                dp[i+1] = max ( dp[i+1], dp[j] + profit);\n            }\n        }\n\n        return dp[dp.size()-1];\n    }\n\n    int maxProfit_dp02(vector<int> &prices, int &fee) {\n\n        vector< pair<int, int> > prices_pairs;\n        genPricesPairs(prices, prices_pairs, fee);\n\n        if ( prices_pairs.size() < 1 ) return 0;\n\n\n        // first - represent  the max profit if we buy.\n        // second - represent the max profit if we sell.\n        vector< pair<int,int> > dp(prices_pairs.size() , make_pair(0,0) );\n\n        //buy profit - if we buy it in day 0, then we got negtive profit.\n        dp[0].first = - prices_pairs[0].first;\n\n        //sell profit - if we sell it in day 0, then we have the profits\n        //              if the profit is negtive, then won't sell it.\n        dp[0].second = max(0, prices_pairs[0].second - prices_pairs[0].first - fee);\n\n        for (int i=1; i<prices_pairs.size(); i++) {\n            // BUY - we could have three options\n            //   1) hold the stock do nothing.  profit = previous day's buy profit\n            //   2) sell & buy. profit = previous sell profit - spent money to buy.\n            //   3) fresh buy, give up the pervious buy, just buy it today.\n            // find the max profit of these 3 options.\n\n            dp[i].first = max (dp[i-1].first,                          // option 1) do nothing\n                               dp[i-1].second - prices_pairs[i].first, // option 2) sell & buy\n                               - prices_pairs[i].first );              // option 3) fresh buy\n\n            // SELL - we could have three options\n            //   1) hold the stock do nothing. profit = previous day's sell profit\n            //   2) sell it. profit = previous day's buy + today's sell.\n            //   3) sell previous and sell today. profit = previous's sell + today's sell\n            // Find the max profit of these 3 options\n            dp[i].second = max(dp[i-1].second,\n                               dp[i-1].first + prices_pairs[i].second - fee,\n                               dp[i-1].second + prices_pairs[i].second - prices_pairs[i].first - fee );\n        }\n\n        return max( dp[dp.size()-1].second, 0 );\n\n    }\n\n    //\n    // Actually, by given any day, we can have two status:\n    // 1) BUY status - we can have two options at Day X.\n    //     i) buy stock - need previous sell status.(you cannot buy if you haven't sold)\n    //    ii) do nothing - need previous buy status.\n    //\n    // 2) SELL status - we can have two options at Day X.\n    //     i) sell stock - need previous buy status.(you cannot sell if you haven't bought)\n    //    ii) do nothing - keep the previous sell status.\n    //\n    // For example:\n    //\n    //    if we have [1,3,2,8,4,9], fee = 2\n    //    then we could have the following BUY & SELL status\n    //\n    //    Day One\n    //        1 - BUY: the profit is -1 ,becuase we spent 1 money\n    //            SELL: you cannot sell, the profit is 0.\n    //    Day Two\n    //        3 - BUY : pre-SELL - 3 = -3, but do nothing has max profit pre-BUY: -1\n    //            SELL: pre-BUY + 3 -2 = -1+3-2 = 0 , the max profit: 0\n    //    Day Three\n    //        2 - BUY : pre-SELL - 2 = 0 - 2 = -2, do nothing has max profit: -1\n    //            SELL: pre-BUY + 2 -2 = -1 + 2 -2 = -1, do nothing has max profit: 0\n    //    Day Four\n    //        8 - BUY : pre-SELL - 8 =  0 - 8 = -8, so, just hold, the max buy profit: -1\n    //            SELL: pre-BUY + 8 - 2 = -1+8-2 =5, the max profit is 5\n    //    Day Five\n    //        4 - BUY : pre-SELL - 4 = 5-4 = 1, do nothing profit is -1, so should buy it.\n    //                  so, the max buy profit is 1.\n    //            SELL: pre-BUY + 4 -2 = -1 + 4 -2= 1, it's has lower profit than previous,\n    //                  so, we won't sell, the max sell profit is 5.\n    //    Day Six\n    //        9 - BUY : pre-SELL - 9 = 5-9= -4, so won't buy, the max buy profit is 1.\n    //            SELL: pre-BUY + 9 -2 = 1 + 9 -2 = 8, it's has higher profit. so we sell\n    //\n    //   Let's use an table\n    //\n    //            prices =   1,  3,  2,  8,  4,  9\n    //    max buy profit =  -1, -1, -1, -1,  1,  5\n    //   max sell profit =   0,  0,  0,  5,  5,  8\n    //\n    //   We can see we keep tracking the max buy and sell profit for everyday.\n    //\n    //       buy[i] = max( buy[i-1],                // do nothing\n    //                     sell[i-1] - prices[i] ); // sell in previous day can buy today\n    //\n    //       sell[i] = max( sell[i-1],                    // do nothing\n    //                      buy[i-1] + prices[i] - fee ); // sell today\n    //\n    int maxProfit_dp03(vector<int> &prices, int &fee) {\n        int buy=-prices[0], sell=0;\n        int pre_buy=0, pre_sell=0;\n\n        for(auto price: prices) {\n            pre_buy = buy;\n            buy = max (sell - price, pre_buy);\n\n            pre_sell = sell;\n            sell = max( pre_buy + price - fee, pre_sell);\n        }\n\n        return sell;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/***************************************************************************************************** \n *\n * Say you have an array for which the ith element is the price of a given stock on day i.\n * \n * Design an algorithm to find the maximum profit. You may complete as many transactions as you like \n * (i.e., buy one and sell one share of the stock multiple times).\n * \n * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock \n * before you buy again).\n * \n * Example 1:\n * \n * Input: [7,1,5,3,6,4]\n * Output: 7\n * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\n *              Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\n * \n * Example 2:\n * \n * Input: [1,2,3,4,5]\n * Output: 4\n * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n *              Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are\n *              engaging multiple transactions at the same time. You must sell before buying again.\n * \n * Example 3:\n * \n * Input: [7,6,4,3,1]\n * Output: 0\n * Explanation: In this case, no transaction is done, i.e. max profit = 0.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        return maxProfit02(prices);\n        return maxProfit01(prices);\n    }\n    // Solution 1 \n    // find all of ranges: which start a valley with the nearest peak after\n    // add their delta together \n    //\n    int maxProfit01(vector<int> &prices) {\n\n        int max = 0;\n        int low = -1;\n\tint len = prices.size();\n        for (int i=0; i < len - 1; i++){\n            //meet the valley, then goes up\n            if (prices[i] < prices[i+1] && low < 0 ) {\n                low = i;\n            }\n            //meet the peak, then goes down\n            if (prices[i] > prices[i+1] && low >= 0) {\n                max += ( prices[i] - prices[low] ) ;\n                low = -1; // reset the `low`\n            }\n        }\n\n        // edge case\n        if ( low >= 0 ) {\n            max += ( prices[prices.size()-1] - prices[low] );\n        }\n\n        return max;\n    }\n\n    // Solution 2 \n    // if we find we can earn money, we just sell\n    int maxProfit02(vector<int>& prices) {\n        int profit = 0 ;\n        for(int i=1; i< prices.size(); i++) {\n            profit += max(0, prices[i] - prices[i-1]);\n        }\n        return profit;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.III.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/\n// Author : Hao Chen\n// Date   : 2014-08-22\n\n/***************************************************************************************************** \n *\n * Say you have an array for which the ith element is the price of a given stock on day i.\n * \n * Design an algorithm to find the maximum profit. You may complete at most two transactions.\n * \n * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock \n * before you buy again).\n * \n * Example 1:\n * \n * Input: [3,3,5,0,0,3,1,4]\n * Output: 6\n * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n *              Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n * \n * Example 2:\n * \n * Input: [1,2,3,4,5]\n * Output: 4\n * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n *              Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are\n *              engaging multiple transactions at the same time. You must sell before buying again.\n * \n * Example 3:\n * \n * Input: [7,6,4,3,1]\n * Output: 0\n * Explanation: In this case, no transaction is done, i.e. max profit = 0.\n ******************************************************************************************************/\n\n\nclass Solution {\npublic:\n    // Dynamic Programming\n    //\n    //     Considering prices[n], and we have a position \"i\", we could have\n    //       1) the maxProfit1 for prices[0..i]  \n    //       2) the maxProfit2 for proices[i..n]\n    //\n    //    So, \n    //      for 1) we can go through the prices[n] forwardly.\n    //          forward[i] = max( forward[i-1], price[i] - lowestPrice[0..i] ) \n    //      for 2) we can go through the prices[n] backwoardly.\n    //          backward[i] = max( backward[i+1], highestPrice[i..n] - price[i]) \n    //\n    int maxProfit(vector<int> &prices) {\n        if (prices.size()<=1) return 0;\n        \n        int n = prices.size();\n        \n        vector<int> forward(n);\n        forward[0] = 0;\n        int lowestBuyInPrice = prices[0];\n        for(int i=1; i<n; i++){\n            forward[i] = max(forward[i-1], prices[i] - lowestBuyInPrice);\n            lowestBuyInPrice = min(lowestBuyInPrice, prices[i]);\n        }\n        \n        vector<int> backward(n);\n        backward[n-1] = 0;\n        int highestSellOutPrice = prices[n-1];\n        for(int i=n-2; i>=0; i--){\n            backward[i] = max(backward[i+1], highestSellOutPrice - prices[i]);\n            highestSellOutPrice = max(highestSellOutPrice, prices[i]);\n        }\n        \n        int max_profit = 0;\n        for(int i=0; i<n; i++){\n            max_profit = max(max_profit, forward[i]+backward[i]);\n        }\n        \n        return max_profit;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.IV.cpp",
    "content": "// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/\n// Author : Hao Chen\n// Date   : 2015-03-31\n\n/***************************************************************************************************** \n *\n * Say you have an array for which the ith element is the price of a given stock on day i.\n * \n * Design an algorithm to find the maximum profit. You may complete at most k transactions.\n * \n * Note:\n * You may not engage in multiple transactions at the same time (ie, you must sell the stock before \n * you buy again).\n * \n * Example 1:\n * \n * Input: [2,4,1], k = 2\n * Output: 2\n * Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n * \n * Example 2:\n * \n * Input: [3,2,6,5,0,3], k = 2\n * Output: 7\n * Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.\n *              Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n ******************************************************************************************************/\n\nclass Solution {\n    public:\n        /*\n         *  profits[trans, day]\n         *  - `trans` represents the number of transactions we've done so far. ( 0 <= trans <= k )\n         *  - `day` represents the number of days so far. ( 0 <= day <= prices.size() )\n         *\n         *  So, we have the initialization as below:\n         *\n         *  profits[0, day] = 0; // 0 <= day <= prices.size()\n         *  profits[trans, 0] = 0; // 0 <= trans <= k\n         *\n         *  And the iteration logic as below:\n         *\n         *  profits[trans, day] = max (\n         *                              profits[trans, day-1], // same times transactions, but one days before.\n         *                              profits[trans-1, i-1] + (prices[day] - prices[i]) // for all of (0 <= i < day )\n         *                                                                                // this means find max profit from\n         *                                                                                // previous any of days\n         *                            )\n         *\n         */\n\n        int maxProfit(int k, vector<int> &prices) {\n            int ndays = prices.size();\n\n            // error case\n            if (ndays<=1) return 0;\n\n            // Edge case\n            // ---------\n            // if the number of transactions is too many, it means we can make\n            // as many transactions as we can, that brings us the problem back to\n            // Best-Time-To-Buy-And-Sell-Stock-II which can be simply solve in O(n)\n            // by using a greedy approach.\n            if(k > ndays/2){\n                int sum = 0;\n                for (int i=1; i<ndays; i++) {\n                    sum += max(prices[i] - prices[i-1], 0);\n                }\n                return sum;\n            }\n\n            return maxProfit_DP03(k, prices);//8ms\n            return maxProfit_DP02(k, prices);//8ms\n            return maxProfit_DP01(k, prices);//492ms\n        }\n\n\n        //DP solution - O(kn^2) complexity\n        int maxProfit_DP01 (int k, vector<int> &prices) {\n            int ndays = prices.size();\n            vector< vector<int> > profits(k+1, vector<int>( ndays+1, 0));\n            for(int trans=1; trans<=k; trans++) {\n                for (int day=1; day<=ndays; day++) {\n                    int m=0;\n                    for (int i=1; i<=day; i++) {\n                        m = max(m, profits[trans-1][i-1]+ prices[day-1] - prices[i-1]);\n                    }\n                    profits[trans][day] =  max( profits[trans][day-1], m);\n                }\n            }\n            return profits[k][ndays];\n        }\n\n        //DP solution - O(kn) complexity\n        //Actually, we could save the loop in above- for(int i=1; i<=day; i++)\n        //Becasue there are so many dupliations\n\n        int maxProfit_DP02 (int k, vector<int> &prices) {\n\n            int ndays = prices.size();\n\n            vector< vector<int> > profits(k+1, vector<int>( ndays+1, 0));\n            vector<int> m(ndays+1, 0); // tracking the max profits of previous days\n\n            for(int trans=1; trans<=k; trans++) {\n                m[0] = profits[trans-1][0] - prices[0];\n                for (int day=1; day<=ndays; day++) {\n                    profits[trans][day] =  max( profits[trans][day-1], m[day-1]+prices[day-1]);\n                    if (day < ndays) {\n                        m[day] = max(m[day-1], profits[trans-1][day] - prices[day]);\n                    }\n                }\n            }\n            return profits[k][ndays];\n        }\n\n\n        // save the memory, remove the m[ ] array\n        int maxProfit_DP03 (int k, vector<int> &prices) {\n            int ndays = prices.size();\n            vector< vector<int> > profits(k+1, vector<int>( ndays+1, 0));\n\n            for(int trans=1; trans<=k; trans++) {\n                int m = profits[trans-1][0] - prices[0];\n                for (int day=1; day <= ndays; day++) {\n                    profits[trans][day] = max(profits[trans][day-1], m + prices[day-1]);\n                    if ( day < ndays ) {\n                        m = max(m, profits[trans-1][day] - prices[day]);\n                    }\n                }\n            }\n\n            return profits[k][ndays];\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/***************************************************************************************************** \n *\n * Say you have an array for which the ith element is the price of a given stock on day i.\n * \n * If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of \n * the stock), design an algorithm to find the maximum profit.\n * \n * Note that you cannot sell a stock before you buy one.\n * \n * Example 1:\n * \n * Input: [7,1,5,3,6,4]\n * Output: 5\n * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n *              Not 7-1 = 6, as selling price needs to be larger than buying price.\n * \n * Example 2:\n * \n * Input: [7,6,4,3,1]\n * Output: 0\n * Explanation: In this case, no transaction is done, i.e. max profit = 0.\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    //\n    // This solution is O(1) space dynamic programming \n    //\n    // We can make sure the max profit at least be ZERO. So,\n    //    1) we have two pointers (begin & end ) \n    //    2) if prices[end] - prices[begin] >  0, then move the \"end\" pointer to next\n    //    3) if prices[end] - prices[begin] <= 0, then move the \"begin\" pointer to current posstion.\n    //    4) tracking the max profit\n    //\n    // Notes:\n    //    Some people think find the highest-price & lowest-price, this is wrong. \n    //    Because the highest-price must be after lowest-price\n    //\n    int maxProfit(vector<int> &prices) {\n        \n        int max=0, begin=0, end=0, delta=0;\n        \n        for (int i=0; i<prices.size(); i++) {\n            \n            end = i;\n            \n            delta = prices[end] - prices[begin];\n            \n            if (delta <= 0){\n                begin = i;\n            }\n            \n            if ( delta > max ){\n                max = delta;\n            }\n            \n        }\n        \n        return max;\n        \n    }\n};\n\n\nclass Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int buy = INT_MAX;\n        int profit = 0;\n        for (auto p : prices) {\n    \t    // Keep tracking the previous lowest price\n            buy = min (buy, p);\n\t    // Keep tacking the current max profit\n            profit = max(profit, p - buy);\n        }\n        return profit;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binarySearchTreeIterator/binarySearchTreeIterator.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-search-tree-iterator/\n// Author : Hao Chen\n// Date   : 2014-12-31\n\n/********************************************************************************** \n * \n * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.\n * \n * Calling next() will return the next smallest number in the BST.\n * \n * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. \n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\nclass BSTIterator {\n    private:\n        vector<int> v; \n        int pos;\n    public:\n        //Travse the Tree in-order and covert it to an array\n        BSTIterator(TreeNode *root) {\n            pos = 0;\n            vector<TreeNode*> stack;\n            while(stack.size()>0 || root !=NULL) {\n                if (root){\n                    stack.push_back(root);\n                    root = root->left;\n                }else{\n                    root = stack.back();\n                    stack.pop_back();\n                    v.push_back(root->val);\n                    root = root->right;\n                }\n            }\n        }\n\n        /** @return whether we have a next smallest number */\n        bool hasNext() {\n            return pos < v.size();\n        }\n\n        /** @return the next smallest number */\n        int next() {\n            return v[pos++];\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeInorderTraversal/binaryTreeInorderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-inorder-traversal/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* Given a binary tree, return the inorder traversal of its nodes' values.\n* \n* For example:\n* Given binary tree {1,#,2,3},\n* \n*    1\n*     \\\n*      2\n*     /\n*    3\n* \n* return [1,3,2].\n* \n* Note: Recursive solution is trivial, could you do it iteratively?\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> inorderTraversal(TreeNode *root) {\n        vector<TreeNode*> stack;\n        vector<int> v;\n        \n        while(stack.size()>0 || root!=NULL){\n            if (root!=NULL){\n                stack.push_back(root);\n                root = root->left;\n            }else{\n                if (stack.size()>0) {\n                    root = stack.back();\n                    stack.pop_back();\n                    v.push_back(root->val);\n                    root = root->right;\n                }\n            }\n        }\n        return v;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* Given a binary tree, return the bottom-up level order traversal of its nodes' values. \n* (ie, from left to right, level by level from leaf to root).\n* \n* For example:\n* Given binary tree {3,9,20,#,#,15,7},\n* \n*     3\n*    / \\\n*   9  20\n*     /  \\\n*    15   7\n* \n* return its bottom-up level order traversal as:\n* \n* [\n*   [15,7],\n*   [9,20],\n*   [3]\n* ]\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int> > levelOrderBottom(TreeNode *root) {\n        queue<TreeNode*> q;\n        vector< vector<int> > vv;\n        vector<int> v;\n        if (root){\n            v.push_back(root->val);\n            vv.push_back(v);\n        }\n        q.push(root);\n        int i=0;\n        vector<TreeNode*> vt;\n        while(q.size()>0){\n            TreeNode *p = q.front();\n            q.pop();\n            vt.push_back(p);\n            if ( p==NULL ) {\n                continue;\n            }\n            q.push(p->left);\n            q.push(p->right);\n        }\n    \n    \n        int step = 2;\n        int j;\n        for (int i=1; i<vt.size(); i=j ){\n            v.clear();\n    \n            int cnt=0;\n            for (j=i; j<i+step && j<vt.size(); j++){\n                if (vt[j]) {\n                    v.push_back(vt[j]->val);\n                    cnt += 2;\n                }\n            }\n            step = cnt;\n            if (v.size()>0) {\n                vv.push_back(v);\n            }\n        }\n        //reverse the order\n        reverse(vv.begin(), vv.end());\n        return vv;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-level-order-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Given a binary tree, return the level order traversal of its nodes' values. \n* (ie, from left to right, level by level).\n* \n* For example:\n* Given binary tree {3,9,20,#,#,15,7},\n* \n*     3\n*    / \\\n*   9  20\n*     /  \\\n*    15   7\n* \n* return its level order traversal as:\n* \n* [\n*   [3],\n*   [9,20],\n*   [15,7]\n* ]\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nvector<vector<int> > levelOrder1(TreeNode *root);\nvector<vector<int> > levelOrder2(TreeNode *root);\nvector<vector<int> > levelOrder3(TreeNode *root);\n\n\nvector<vector<int> > levelOrder(TreeNode *root) {\n    if (random()%2){\n        return levelOrder1(root);\n    }\n    if (random()%2){\n        return levelOrder3(root);\n    }\n    return levelOrder2(root);\n}\n\nvector<vector<int> > levelOrder1(TreeNode *root) {\n    queue<TreeNode*> q;\n    vector< vector<int> > vv;\n    vector<int> v;\n    if (root){\n        v.push_back(root->val);\n        vv.push_back(v);\n    }\n    q.push(root);\n    int i=0;\n    vector<TreeNode*> vt; \n    while(q.size()>0){\n        TreeNode *p = q.front();\n        q.pop();\n        vt.push_back(p); \n        if ( p==NULL ) {\n            continue;\n        }\n        q.push(p->left);\n        q.push(p->right);\n    }\n    \n    \n    int step = 2;\n    int j; \n    for (int i=1; i<vt.size(); i=j ){\n        v.clear();\n        \n        int cnt=0;\n        for (j=i; j<i+step && j<vt.size(); j++){\n            if (vt[j]) {\n                v.push_back(vt[j]->val);\n                cnt += 2; \n            }\n        } \n        step = cnt;\n        if (v.size()>0) {\n            vv.push_back(v);\n        }\n    }\n\n    return vv;\n}\n\nvector<vector<int> > levelOrder2(TreeNode *root) {\n    vector< vector<int> > vv;\n    vector<int> v;\n    if (root){\n        v.push_back(root->val);\n        vv.push_back(v);\n    }\n\n    vector< vector<int> > vv_left, vv_right;\n    if(root && root->left) {\n        vv_left = levelOrder2(root->left);\n    }\n    if(root && root->right) {\n        vv_right = levelOrder2(root->right);\n    }\n\n    //merge\n    for(int i=0; i<vv_left.size() || i < vv_right.size(); i++){\n        if (i<vv_left.size() && i<vv_right.size()){\n            vv_left[i].insert(vv_left[i].end(), vv_right[i].begin(), vv_right[i].end());\n            vv.push_back(vv_left[i]);\n        }else if (i<vv_left.size()) {\n            vv.push_back(vv_left[i]);\n        }else {\n            vv.push_back(vv_right[i]);\n        }\n    }\n\n    return vv;\n}\n\nvector<vector<int> > levelOrder3(TreeNode *root) {\n    vector< vector<int> > vv;\n    if(root == NULL) return vv;\n\n    int level = 0; // current level.\n    TreeNode *last = root; // last node of currrent level.\n    queue<TreeNode*> q;\n\n    q.push(root);\n    vv.push_back(vector<int>());\n    while(!q.empty()) {\n        TreeNode *p = q.front();\n        q.pop();\n\n        vv[level].push_back(p->val);\n        if(p->left ) q.push(p->left);\n        if(p->right) q.push(p->right);\n\n        if(p == last) {\n            level++;\n            last = q.back();\n            vv.push_back(vector<int>()); // new buffer for next row.\n        }\n    }\n    vv.pop_back();\n\n    return vv;\n}\n\nvoid printTree(TreeNode *root)\n{\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n    printf(\"%d \", root->val );\n\n    printTree(root->left);\n    printTree(root->right);\n}\n\nvoid printTree_level_order(TreeNode *root)\n{\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0){\n        TreeNode* n = q.front();\n        q.pop();\n        if (n==NULL){\n            cout << \"# \";\n            continue;\n        }\n        cout << n->val << \" \";\n        q.push(n->left);\n        q.push(n->right);\n    } \n    cout << endl;\n}\n\nTreeNode* createTree(int a[], int n)\n{\n    if (n<=0) return NULL;\n\n    TreeNode **tree = new TreeNode*[n];\n\n    for(int i=0; i<n; i++) {\n        if (a[i]==0 ){\n            tree[i] = NULL;\n            continue;\n        }\n        tree[i] = new TreeNode(a[i]);\n    } \n    int pos=1;\n    for(int i=0; i<n && pos<n; i++) {    \n        if (tree[i]){\n            tree[i]->left = tree[pos++];\n            if (pos<n){\n                tree[i]->right = tree[pos++];\n            }\n        }\n    }\n    return tree[0];\n}\n\nint printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        cout << \"[\";\n        for(int j=0; j<vv[i].size(); j++) {\n            cout << \" \" << vv[i][j];\n        }\n        cout << \"]\" << endl;;\n    }\n}\n\nint main()\n{\n    TreeNode *p;\n    vector< vector<int> > vv;\n\n    int a[] = {1,2,3,4,5,0,0};\n    p = createTree(a, sizeof(a)/sizeof(int));\n    printTree_level_order(p);\n    vv = levelOrder(p);\n    printMatrix(vv);\n    cout << endl;\n    \n    int b[] = {1,0,2};\n    p = createTree(b, sizeof(b)/sizeof(int));\n    printTree_level_order(p);\n    vv = levelOrder(p);\n    printMatrix(vv);\n    cout << endl;\n\n    int c[] = {1,2,0,3,0,4,0,5};\n    p = createTree(c, sizeof(c)/sizeof(int));\n    printTree_level_order(p);\n    vv = levelOrder(p);\n    printMatrix(vv);\n    cout << endl;\n\n    int d[] = {1,2,3,4,0,0,5};\n    p = createTree(d, sizeof(d)/sizeof(int));\n    printTree_level_order(p);\n    vv = levelOrder(p);\n    printMatrix(vv);\n    cout << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeMaximumPathSum/binaryTreeMaximumPathSum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/\n// Author : Hao Chen\n// Date   : 2014-10-10\n\n/********************************************************************************** \n* \n* Given a binary tree, find the maximum path sum.\n* \n* The path may start and end at any node in the tree.\n* \n* For example:\n* Given the below binary tree,\n* \n*        1\n*       / \\\n*      2   3\n* \n* Return 6.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\n//The solution is quite simple can be explained by itself\nint maxPathSum(TreeNode *root, int& maxSum ) {\n\n    if (NULL == root) return 0;\n\n    //get the maxPathSum for both left and right branch\n    int left  = maxPathSum(root->left,  maxSum);\n    int right = maxPathSum(root->right, maxSum);\n\n    // The max sum could be one of the following situations:\n    //    1) root + left\n    //    2) root + right\n    //    3) root\n    //    4) root + left + right   \n    //\n    // And the whole function need to return the the max of 1) 2) 3) \n    int val = root->val;\n    int maxBranch = left > right ? max(left + val, val) : max(right + val, val);\n    int m = max(left + right + val, maxBranch);\n\n    maxSum = max(maxSum, m);\n\n    return maxBranch;\n}\n\nint maxPathSum(TreeNode *root) {\n    #define INT_MIN     (-2147483647 - 1)\n    int maxSum = INT_MIN;\n    maxPathSum(root, maxSum);\n    return maxSum;\n}\n\nint main()\n{\n    TreeNode root(1);\n    TreeNode left(2);\n    TreeNode right(3);\n    root.left = &left;\n    root.right = &right;\n    cout << maxPathSum(&root) << endl; \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp",
    "content": "// Source : https://leetcode.com/problems/binary-tree-paths/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-10-23\n\n/*************************************************************************************** \n *\n * Given a binary tree, return all root-to-leaf paths.\n * \n * For example, given the following binary tree:\n * \n *    1\n *  /   \\\n * 2     3\n *  \\\n *   5\n * \n * All root-to-leaf paths are:\n * [\"1->2->5\", \"1->3\"]\n * \n * Credits:\n * Special thanks to @jianchao.li.fighter for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<string> TreePaths;\n    void DFS(TreeNode* node, string answer)\n    {\n        answer += \"->\" + to_string(node->val);\n        if(node->left == NULL && node->right == NULL)\n            TreePaths.push_back(answer);\n        else\n        {\n            if(node->left != NULL)\n                DFS(node->left, answer);\n            if(node->right != NULL)\n                DFS(node->right, answer);\n        }\n    }\n    vector<string> binaryTreePaths(TreeNode* root) {\n        if(root != NULL)\n        {\n            DFS(root, \"\");\n            for(int i = 0; i < TreePaths.size(); i++)\n                TreePaths[i].erase(TreePaths[i].begin(), TreePaths[i].begin() + 2);\n        }\n        return TreePaths;\n    }\n};\n\n\n\n\n// Another more clear DFS implementation\n\nclass Solution {\npublic:\n    void binaryTreePathsHelper(TreeNode* root, vector<int> solution, vector<string>& result ) {\n        if (!root) return;\n        \n        solution.push_back(root->val);\n        \n        //meet the leaf node, shape a path into the result\n        if (root->left==NULL && root->right==NULL){\n            if(solution.size()>0){\n                stringstream ss;\n                for(int i=0; i<solution.size(); i++){\n                    ss << solution[i] << (i<solution.size()-1 ? \"->\":\"\");\n                }\n                result.push_back(ss.str());\n            }\n            return;\n        }\n        \n        binaryTreePathsHelper(root->left, solution, result);\n        binaryTreePathsHelper(root->right, solution, result);\n        \n    }\n    vector<string> binaryTreePaths(TreeNode* root) {\n        vector<string> result;\n        vector<int> solution;\n        binaryTreePathsHelper(root, solution, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreePostorderTraversal/binaryTreePostorderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-postorder-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-21\n\n/********************************************************************************** \n* \n* Given a binary tree, return the postorder traversal of its nodes' values.\n* \n* For example:\n* Given binary tree {1,#,2,3},\n* \n*    1\n*     \\\n*      2\n*     /\n*    3\n* \n* return [3,2,1].\n* \n* Note: Recursive solution is trivial, could you do it iteratively?\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nvector<int> postorderTraversal1(TreeNode *root);\nvector<int> postorderTraversal2(TreeNode *root);\n\n\n// We have two methods here.\n//   1) the first one acutally is pre-order but reversed the access order.\n//   2) the second one is the traditional one \n\nvector<int> postorderTraversal(TreeNode *root) {\n    if (random()%2){\n        cout << \"---method one---\" << endl;\n        return postorderTraversal1(root);\n    }\n    cout << \"---method two---\" << endl;\n    return postorderTraversal2(root);\n}\n\n\nvector<int> postorderTraversal1(TreeNode *root) {\n    vector<int> v;\n    vector<TreeNode*> stack;\n    if (root) {\n        stack.push_back(root);\n    }\n    while (stack.size()>0){\n        TreeNode *n = stack.back();\n        stack.pop_back();\n        v.push_back(n->val);\n        if (n->left){\n            stack.push_back(n->left);\n        } \n        if (n->right) {\n            stack.push_back(n->right);\n        }\n    }\n    std::reverse(v.begin(), v.end());  // the trick\n    return v;\n}\n\n// traditional and standard way.\n// using the stack to simulate the recursive function stack.\nvector<int> postorderTraversal2(TreeNode *root) {\n    vector<int> v;\n    vector<TreeNode*> stack;\n    TreeNode *node = root;\n    TreeNode *lastVisitNode = NULL;\n    while(stack.size()>0 || node!=NULL){\n\n        if (node != NULL){\n            // keep going the left\n            stack.push_back(node);\n            node = node->left;\n        }else{\n            TreeNode *n = stack.back();\n            // left way is finsised, keep going to the right way\n            if (n->right != NULL && lastVisitNode != n->right){\n                node = n->right;\n            }else{\n                // both left and right has been accessed.\n                stack.pop_back();\n                v.push_back(n->val);\n                lastVisitNode = n;\n            }\n        }\n    }\n    return v;\n}\n\n\nTreeNode* createTree(int a[], int n)\n{\n    if (n<=0) return NULL;\n\n    TreeNode **tree = new TreeNode*[n];\n\n    for(int i=0; i<n; i++) {\n        if (a[i]==0 ){\n            tree[i] = NULL;\n            continue;\n        }\n        tree[i] = new TreeNode(a[i]);\n    }\n    int pos=1;\n    for(int i=0; i<n && pos<n; i++) {\n        if (tree[i]){\n            tree[i]->left = tree[pos++];\n            if (pos<n){\n                tree[i]->right = tree[pos++];\n            }\n        }\n    }\n    return tree[0];\n}\n\nvoid printTree_post_order(TreeNode *root)\n{\n    if (root == NULL){\n        //cout << \"# \";\n        return ;\n    }\n    printTree_post_order(root->left);\n    printTree_post_order(root->right);\n    cout << root->val << \" \";\n}\n\n\nvoid printArray(vector<int> v)\n{\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] << \" \";\n    }\n    cout << endl;\n}\n\nint main()\n{\n    srand(time(0));\n    int a[] = {1,2,3,4,5,0,6,0,0,7,8,9,0};\n    TreeNode* p = createTree(a, sizeof(a)/sizeof(int));\n    printTree_post_order(p);\n    cout << endl;\n    vector<int> v = postorderTraversal(p);\n    printArray(v);\n    cout << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/binaryTreePreorderTraversal/binaryTreePreorderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-preorder-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-21\n\n/********************************************************************************** \n* \n* Given a binary tree, return the preorder traversal of its nodes' values.\n* \n* For example:\n* Given binary tree {1,#,2,3},\n* \n*    1\n*     \\\n*      2\n*     /\n*    3\n* \n* return [1,2,3].\n* \n* Note: Recursive solution is trivial, could you do it iteratively?\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nvector<int> preorderTraversal1(TreeNode *root);\nvector<int> preorderTraversal2(TreeNode *root);\n\nvector<int> preorderTraversal(TreeNode *root) {\n    if (random()%2){\n        cout << \"---method one---\" << endl;\n        return preorderTraversal1(root);\n    }\n    cout << \"---method two---\" << endl;\n    return preorderTraversal2(root);\n}\n\nvector<int> preorderTraversal1(TreeNode *root) {\n    vector<int> v;\n    vector<TreeNode*> stack;\n    if (root) {\n        stack.push_back(root);\n    }\n    while (stack.size()>0){\n        TreeNode* n = stack.back();\n        v.push_back(n->val);\n        stack.pop_back();\n        if (n->right){\n            stack.push_back(n->right);\n        }\n        if (n->left){\n            stack.push_back(n->left);\n        }\n    }\n    return v;\n}\n\nvector<int> preorderTraversal2(TreeNode *root) {\n    vector<int> v;\n    vector<TreeNode*> stack;\n    stack.push_back((TreeNode*)NULL);\n    TreeNode *top = root;\n    while(top!=NULL){\n        v.push_back(top->val);\n        if (top->right !=NULL){\n            stack.push_back(top->right);\n        }\n\n        if (top->left != NULL){\n            stack.push_back(top->left);\n        }\n\n        top = stack.back();\n        stack.pop_back();\n    }\n    return v;\n}\n\nTreeNode* createTree(int a[], int n)\n{\n    if (n<=0) return NULL;\n\n    TreeNode **tree = new TreeNode*[n];\n\n    for(int i=0; i<n; i++) {\n        if (a[i]==0 ){\n            tree[i] = NULL;\n            continue;\n        }\n        tree[i] = new TreeNode(a[i]);\n    }\n    int pos=1;\n    for(int i=0; i<n && pos<n; i++) {\n        if (tree[i]){\n            tree[i]->left = tree[pos++];\n            if (pos<n){\n                tree[i]->right = tree[pos++];\n            }\n        }\n    }\n    return tree[0];\n}\n\nvoid printTree_pre_order(TreeNode *root)\n{\n    if (root == NULL){\n        //cout << \"# \";\n        return ;\n    }\n    cout << root->val << \" \";\n    printTree_pre_order(root->left);\n    printTree_pre_order(root->right);\n}\n\n\nvoid printArray(vector<int> v)\n{\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] << \" \";\n    }\n    cout << endl;\n}\n\nint main()\n{\n    srand(time(0));\n    int a[] = {1,2,3,4,5,0,6,0,0,7,8,9,0};\n    TreeNode* p = createTree(a, sizeof(a)/sizeof(int));\n    printTree_pre_order(p);\n    cout << endl;\n    vector<int> v = preorderTraversal(p);\n    printArray(v);\n    cout << endl;\n\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeRightSideView/binaryTreeRightSideView.cpp",
    "content": "// Source : https://leetcode.com/problems/binary-tree-right-side-view/\n// Author : Hao Chen\n// Date   : 2015-04-07\n\n/********************************************************************************** \n * \n * Given a binary tree, imagine yourself standing on the right side of it, return \n * the values of the nodes you can see ordered from top to bottom.\n * \n * For example:\n * Given the following binary tree,\n * \n *      1            <---\n *    /   \\\n *   2     3         <---\n *    \\     \\\n *     5     4       <---\n * \n * You should return [1, 3, 4].\n * \n * Credits:Special thanks to @amrsaqr for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void rightSideViewHelper(TreeNode* root, int level, vector<int>& result) {\n        if (root == NULL) return;\n        if ( result.size() < level ) result.push_back(root->val);\n        rightSideViewHelper(root->right, level+1, result);\n        rightSideViewHelper(root->left, level+1, result);\n    }\n    \n    void rightSideViewHelper(TreeNode* root, vector<int>& result) {\n        if (root==NULL) return;\n\n        vector<TreeNode*> stack;\n        vector<int> level;\n        stack.push_back(root);\n        level.push_back(1);\n        \n        while (stack.size()>0) {\n            TreeNode* r = stack.back(); stack.pop_back();\n            int l = level.back(); level.pop_back();\n            if ( result.size() < l ) {\n                result.push_back(r->val);\n            }\n            if (r->left) {\n                stack.push_back(r->left);\n                level.push_back(l+1);\n            }\n            if (r->right) {\n                stack.push_back(r->right);\n                level.push_back(l+1);\n            }\n        }\n    }\n    vector<int> rightSideView(TreeNode *root) {\n        vector<int> result;\n        if (rand()%2){\n            rightSideViewHelper(root, 1, result);\n        }else{\n            rightSideViewHelper(root, result);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeUpsideDown/binaryTreeUpsideDown.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-upside-down/\n// Author : Hao Chen\n// Date   : 2014-11-17\n\n/********************************************************************************** \n* Given a binary tree where all the right nodes are either leaf nodes with \n* a sibling (a left node that shares the same parent node) or empty, \n* \n* Flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. \n* Return the new root.\n* \n* For example:\n* Given a binary tree {1,2,3,4,5},\n*     1\n*    / \\\n*   2   3\n*  / \\\n* 4   5\n* return the root of the binary tree [4,5,2,#,#,3,1].\n*    4\n*   / \\\n*  5   2\n*     / \\\n*    3   1  \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ. \n* \n**********************************************************************************/\n\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode *upsideDownBinaryTree(TreeNode *root) {\n        //using a dummy node to help to store the new tree      \n        TreeNode dummy(0);\n        TreeNode *head =  &dummy, *left=NULL, *right=NULL;\n\n        while ( root!=NULL ) {\n            //find the right & left\n            left = root->right;\n            right = root;\n            \n            //move root the next\n            root = root->left;\n            \n            //replace the right with current root\n            right->left = head->left;\n            right->right = head->right;\n            \n            //move the dummy to the root\n            dummy.right = right;\n            dummy.left = left;\n            \n            //reset the head to the root\n            head = &dummy;\n    \n        }\n        \n        return head->right;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/binaryTreeZigzagLevelOrderTraversal/binaryTreeZigzagLevelOrderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Given a binary tree, return the zigzag level order traversal of its nodes' values. \n* (ie, from left to right, then right to left for the next level and alternate between).\n* \n* For example:\n* Given binary tree {3,9,20,#,#,15,7},\n* \n*     3\n*    / \\\n*   9  20\n*     /  \\\n*    15   7\n* \n* return its zigzag level order traversal as:\n* \n* [\n*   [3],\n*   [20,9],\n*   [15,7]\n* ]\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, \n* where '#' signifies a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nvector<TreeNode*> TreeToArray_level_order(TreeNode* root);\n\nvector<vector<int> > zigzagLevelOrder(TreeNode *root) {\n    if (random()%2){\n        return zigzagLevelOrder1(root);\n    }\n    return zigzagLevelOrder2(root);\n}\n\nvector<vector<int> > zigzagLevelOrder1(TreeNode *root) {\n    vector<vector<int> > result;\n    vector<TreeNode*> tree = TreeToArray_level_order(root);\n\n    int curLevelCnt = 1;\n    int nextLevelCnt = 1;\n    int level=0;\n\n    for (int i=0; i<tree.size(); i+=curLevelCnt ){\n        int cnt=0;\n        level++;\n        vector<int> v;\n        if (level%2==0){\n            for(int j=i+nextLevelCnt-1; j>=i; j--){\n                if (tree[j]){\n                    cnt += 2;\n                    v.push_back(tree[j]->val);\n                }\n            }\n        }else{\n            for(int j=i; j<i+nextLevelCnt; j++){\n                if (tree[j]){\n                    cnt += 2;\n                    v.push_back(tree[j]->val);\n                }\n            }\n        }\n        curLevelCnt = nextLevelCnt;\n        nextLevelCnt = cnt;\n        if (v.size()>0){\n            result.push_back(v);\n        }\n    }\n    return result;\n}\n\nvector<TreeNode*> TreeToArray_level_order(TreeNode* root){\n    vector <TreeNode*> result;\n\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0) {\n        TreeNode* n = q.front();\n        q.pop();\n        result.push_back(n);\n        if (n==NULL){\n            //cout << \"# \";\n            continue;\n        }\n        //cout << n->val << \" \";\n        q.push(n->left);\n        q.push(n->right);\n    }\n    //cout << endl;\n    return result;\n}\n\nvector<vector<int> > zigzagLevelOrder2(TreeNode *root) {\n    vector<vector<int> > vv;\n    if(root == NULL) return vv;\n\n    int level = 0;\n    TreeNode *last = root;\n    queue<TreeNode*> q;\n\n    q.push(root);\n    vv.push_back(vector<int>());\n    while(!q.empty()) {\n        TreeNode *p = q.front();\n        q.pop();\n\n        vv[level].insert(level%2 ? vv[level].begin() : vv[level].end(), p->val);\n        if(p->left) q.push(p->left);\n        if(p->right) q.push(p->right);\n\n        if(p == last) {\n            level++;\n            last = q.back();\n            vv.push_back(vector<int>());\n        }\n    }\n    vv.pop_back();\n\n    return vv;\n}\n\nvoid printTree_level_order(TreeNode *root)\n{\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0){\n        TreeNode* n = q.front();\n        q.pop();\n        if (n==NULL){\n            cout << \"# \";\n            continue;\n        }\n        cout << n->val << \" \";\n        q.push(n->left);\n        q.push(n->right);\n    }\n    cout << endl;\n}\n\nTreeNode* createTree(int a[], int n)\n{\n    if (n<=0) return NULL;\n\n    TreeNode **tree = new TreeNode*[n];\n\n    for(int i=0; i<n; i++) {\n        if (a[i]==0 ){\n            tree[i] = NULL;\n            continue;\n        }\n        tree[i] = new TreeNode(a[i]);\n    }\n    int pos=1;\n    for(int i=0; i<n && pos<n; i++) {\n        if (tree[i]){\n            tree[i]->left = tree[pos++];\n            if (pos<n){\n                tree[i]->right = tree[pos++];\n            }\n        }\n    }\n    return tree[0];\n}\n\nint printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        cout << \"[\";\n        for(int j=0; j<vv[i].size(); j++) {\n            cout << \" \" << vv[i][j];\n        }\n        cout << \" ]\" << endl;;\n    }\n}\n\n\nint main(int argc, char** argv)\n{\n    TreeNode *p;\n    vector< vector<int> > vv;\n\n    int a[] = {3,9,20,0,0,15,7};\n    p = createTree(a, sizeof(a)/sizeof(int));\n    printTree_level_order(p);\n    vv = zigzagLevelOrder(p);\n    printMatrix(vv);\n    cout << endl;\n\n\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/binaryWatch/BinaryWatch.cpp",
    "content": "// Source : https://leetcode.com/problems/binary-watch/\n// Author : Hao Chen\n// Date   : 2016-11-05\n\n/*************************************************************************************** \n *\n * A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 \n * LEDs on the bottom represent the minutes (0-59).\n * Each LED represents a zero or one, with the least significant bit on the right.\n * \n * For example, the above binary watch reads \"3:25\".\n * \n * Given a non-negative integer n which represents the number of LEDs that are \n * currently on, return all possible times the watch could represent.\n * \n * Example:\n * Input: n = 1Return: [\"1:00\", \"2:00\", \"4:00\", \"8:00\", \"0:01\", \"0:02\", \"0:04\", \"0:08\", \n * \"0:16\", \"0:32\"]\n * \n * Note:\n * \n * The order of output does not matter.\n * The hour must not contain a leading zero, for example \"01:00\" is not valid, it \n * should be \"1:00\".\n * The minute must be consist of two digits and may contain a leading zero, for example \n * \"10:2\" is not valid, it should be \"10:02\".\n ***************************************************************************************/\n\nclass Solution {\nprivate:\n    void combination(int nLED, int nLight, int max, bool zero,\n                     int start, int k, int solution, \n                     vector<vector<string>>& result) {\n        if (solution > max){\n            return;\n        }\n        if (k == 0) {\n            char tmp[5] = \"\";\n            if (zero) {\n                sprintf(tmp, \"%02d\", solution);\n            }else{\n                sprintf(tmp, \"%d\", solution);\n            }\n            result[nLight].push_back(tmp);\n            return;\n        }\n        for (int i=start; i<=nLED-k; i++) {\n            solution += pow(2, i);\n            combination(nLED, nLight, max, zero, i+1, k-1, solution, result);\n            solution -= pow(2, i);\n        }\n    }\n    \n    void generate_combination(int nLED, int max, bool zero, vector<vector<string>>& result) {\n        for (int i=0; i<nLED; i++) {\n            combination(nLED, i, max, zero, 0, i, 0, result);\n        }\n    }\n    \n    void print(vector<vector<string>>&  vv) {\n        for(auto v : vv) {\n            cout << \"[ \";\n            for (auto i : v) {\n                cout << i << \" \";\n            }\n            cout << \"]\" << endl;\n        }\n    }\n    \nprivate:\n    vector<vector<string>> hour;\n    vector<vector<string>> mins;\n\npublic:\n\n    Solution():hour(4, vector<string>()), mins(6, vector<string>()){\n        generate_combination(4, 11, false, hour);\n        //print(hour);\n        //[ 0 ]\n        //[ 1 2 4 8 ]\n        //[ 3 5 9 6 10 ]\n        //[ 7 11 ]\n        \n        \n        generate_combination(6, 59, true, mins);\n        //print(mins);\n        //[ 00 ]\n        //[ 01 02 04 08 16 32 ]\n        //[ 03 05 09 17 33 06 10 18 34 12 20 36 24 40 48 ]\n        //[ 07 11 19 35 13 21 37 25 41 49 14 22 38 26 42 50 28 44 52 56 ]\n        //[ 15 23 39 27 43 51 29 45 53 57 30 46 54 58 ]\n        //[ 31 47 55 59 ]        \n    }\n    \n    vector<string> readBinaryWatch(int num) {\n        \n        vector<string> result;\n        for (int i = 0; i <= 3 && i <= num; i++) {\n            if (num - i > 5) {\n                continue;\n            }\n            for (auto h : hour[i]) {\n                for (auto m : mins[num - i]) {\n                    result.push_back( h + \":\" + m );\n                }\n            }\n            \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bitwiseANDOfNumbersRange/BitwiseAndOfNumbersRange.cpp",
    "content": "// Source : https://leetcode.com/problems/bitwise-and-of-numbers-range/\n// Author : Hao Chen\n// Date   : 2015-06-08\n\n/********************************************************************************** \n * \n * Given a range [m, n] where 0 \n * \n * For example, given the range [5, 7], you should return 4.\n * \n * Credits:Special thanks to @amrsaqr for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\n/*\n    Idea: \n    1) we know when a number add one, some of the right bit changes from 0 to 1 or  from 1 to 0\n    2) if a bit is 0, then AND will cause this bit to 0 eventually.\n    So, we can just simply check how many left bits are same for m and n. \n\n    for example: \n        5 is 101\n        6 is 110\n        when 5 adds 1, then the right two bits are changed.  the result is 100\n\n        6 is 110\n        7 is 111\n        when 6 adds 1, then the right one bit is changed. the result is 110.\n\n\n         9 is 1001\n        10 is 1010\n        11 is 1011\n        12 is 1100\n        Comparing from 9 to 12, we can see the first left bit is same, that's result.\n*/\nint rangeBitwiseAnd(int m, int n) {\n    int mask = 0xffffffff;\n\n    /* find out the same bits in left side*/\n    while (mask != 0) {\n        if ((m & mask) == (n & mask)) {\n            break;\n        }\n        mask <<= 1;\n    }\n\n    return m & mask;\n\n}\n\nint main(int argc, char**argv) {\n    int m=5, n=7;\n    if (argc>2){\n        m = atoi(argv[1]);\n        n = atoi(argv[2]);\n    }\n    cout << \"range( \" << m << \", \" << n << \" ) = \" <<  rangeBitwiseAnd(m, n) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/brokenCalculator/BrokenCalculator.cpp",
    "content": "// Source : https://leetcode.com/problems/broken-calculator/\n// Author : Hao Chen\n// Date   : 2019-05-01\n\n/***************************************************************************************************** \n *\n * On a broken calculator that has a number showing on its display, we can perform two operations:\n * \n * \tDouble: Multiply the number on the display by 2, or;\n * \tDecrement: Subtract 1 from the number on the display.\n * \n * Initially, the calculator is displaying the number X.\n * \n * Return the minimum number of operations needed to display the number Y.\n * \n * Example 1:\n * \n * Input: X = 2, Y = 3\n * Output: 2\n * Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n * \n * Example 2:\n * \n * Input: X = 5, Y = 8\n * Output: 2\n * Explanation: Use decrement and then double {5 -> 4 -> 8}.\n * \n * Example 3:\n * \n * Input: X = 3, Y = 10\n * Output: 3\n * Explanation:  Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n * \n * Example 4:\n * \n * Input: X = 1024, Y = 1\n * Output: 1023\n * Explanation: Use decrement operations 1023 times.\n * \n * Note:\n * \n * \t1 <= X <= 10^9\n * \t1 <= Y <= 10^9\n ******************************************************************************************************/\n\n\nclass Solution {\npublic:\n    int brokenCalc(int X, int Y) {\n        if (X >= Y) return X-Y ;\n        if ( Y%2 ==0 ) return brokenCalc(X, Y/2) + 1;\n        return brokenCalc(X, Y+1) + 1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/buddyStrings/BuddyStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/buddy-strings/description/\n// Author : Hao Chen\n// Date   : 2018-06-27\n\n/*************************************************************************************** \n *\n * Given two strings A and B of lowercase letters, return true if and only if we can \n * swap two letters in A so that the result equals B.\n * \n *  \n * \n * Example 1:\n * \n * \n * \n * Input: A = \"ab\", B = \"ba\"\n * Output: true\n * \n * \n * \n * Example 2:\n * \n * \n * Input: A = \"ab\", B = \"ab\"\n * Output: false\n * \n * \n * \n * Example 3:\n * \n * \n * Input: A = \"aa\", B = \"aa\"\n * Output: true\n * \n * \n * \n * Example 4:\n * \n * \n * Input: A = \"aaaaaaabc\", B = \"aaaaaaacb\"\n * Output: true\n * \n * \n * \n * Example 5:\n * \n * \n * Input: A = \"\", B = \"aa\"\n * Output: false\n * \n * \n *  \n * \n * Note:\n * \n * \n * \t0 <= A.length <= 20000\n * \t0 <= B.length <= 20000\n * \tA and B consist only of lowercase letters.\n * \n * \n * \n * \n * \n ***************************************************************************************/\n\n\n\nclass Solution {\npublic:\n    bool buddyStrings(string A, string B) {\n        if (A.size() != B.size()) return false;\n        if (A.size()<2) return false;\n        \n        bool bRepeat = false;\n        bool map[26] = {false};\n        int idx[2], diffCnt=0;\n        \n        for (int i=0; i<A.size(); i++){\n            if (map[A[i]-'a']) { bRepeat = true;}\n            map[A[i]-'a']=true;\n            if ( A[i] != B[i] ) {\n                if (diffCnt>=2) return false;\n                idx[diffCnt++] = i;\n                \n            }\n        }\n        //if A == B and there has repeated chars , then return true\n        if (diffCnt==0 && bRepeat) return true;\n        \n        return (A[idx[0]] == B[idx[1]] && A[idx[1]] == B[idx[0]]);\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/buildingBoxes/BuildingBoxes.cpp",
    "content": "// Source : https://leetcode.com/problems/building-boxes/\n// Author : Hao Chen\n// Date   : 2021-04-09\n\n/***************************************************************************************************** \n *\n * You have a cubic storeroom where the width, length, and height of the room are all equal to n \n * units. You are asked to place n boxes in this room where each box is a cube of unit side length. \n * There are however some rules to placing the boxes:\n * \n * \tYou can place the boxes anywhere on the floor.\n * \tIf box x is placed on top of the box y, then each side of the four vertical sides of the \n * box y must either be adjacent to another box or to a wall.\n * \n * Given an integer n, return the minimum possible number of boxes touching the floor.\n * \n * Example 1:\n * \n * Input: n = 3\n * Output: 3\n * Explanation: The figure above is for the placement of the three boxes.\n * These boxes are placed in the corner of the room, where the corner is on the left side.\n * \n * Example 2:\n * \n * Input: n = 4\n * Output: 3\n * Explanation: The figure above is for the placement of the four boxes.\n * These boxes are placed in the corner of the room, where the corner is on the left side.\n * \n * Example 3:\n * \n * Input: n = 10\n * Output: 6\n * Explanation: The figure above is for the placement of the ten boxes.\n * These boxes are placed in the corner of the room, where the corner is on the back side.\n * \n * Constraints:\n * \n * \t1 <= n <= 10^9\n ******************************************************************************************************/\n\n/*\n\n    At first, let's  build the perfect pyramid at the corner.\n\n    we can find the following sequence:\n\n        height    cubes\n        1         1\n        2         1 + 2 = 3\n        3         1 + 2 + 3 = 6\n        4         1 + 2 + 3 + 4 = 10\n        5         1 + 2 + 3 + 4 + 5 = 15\n\n    total(height) = total(height - 1) + sum( from 1 to height )\n    \n    sum ( from 1 to height) = (height * (height+1)) / 2\n                            = height^2/2 + height/2\n    So,\n    \n    total(height) =  (1+2+...+height)/2 + ( 1^2 + 2^2 +...+ height^2 ) / 2\n    \n    we know,  Σn^2 = [n(n+1)(2n+1)]/6  (ref: https://brilliant.org/wiki/sum-of-n-n2-or-n3/)\n    \n    So, \n    \n    total(height) = (height * (height+1)) / 4 + (height(height+1)(2height+1))/12\n                  = height * (height + 1) * (height + 2) / 6\n    \n\n    for the rest cubes, we can place them like this\n\n             (10) \n            (6) (9) \n          (3) (5) (8) \n        (1) (2) (4) (7) \n        \n    sum ( for 1 to n ) = n(n+1)/2\n    \n\n*/\n\n\nclass Solution {\nprivate:\n    int total(long h){\n        return h * (h+1) * (h+2) / 6;\n    }\npublic:\n    int minimumBoxes(int n) {\n        //find the maxiumn height which total(height) <= n\n        //binary search\n        int left = 1, right = pow(6l*n, 1.0/3) ;\n        while(left <= right){\n            int mid = left + (right - left) / 2;\n            int t = total(mid);\n            if ( t == n ) return mid*(mid+1l)/2;\n            if ( t < n) left = mid + 1;\n            else right = mid - 1;\n        }\n        int height = right;\n        int remind = n - total(height);\n        int bottom = height * (height+1l)/2 ;\n        //cout << \"n=\" << n << \", height=\" << height << \n        //    \", bottom = \" << bottom << \", remind=\" << remind << endl;\n        \n        //find teh maxium h which sum(1..h) <= remind\n        //binary search\n        left = 1; right = sqrt(2*remind);\n        while ( left <= right) {\n            int mid = left + (right - left)/2;\n            int h = mid*(mid+1)/2;\n            if ( h == remind) return bottom + mid;\n            if ( h < remind) left = mid + 1;\n            else right = mid -1;\n        }\n        //cout << \"left=\" << left << \", right=\" << right << endl;\n        return bottom + left;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bulbSwitcher/BulbSwitcher.II.cpp",
    "content": "// Source : https://leetcode.com/problems/bulb-switcher-ii/\n// Author : Hao Chen\n// Date   : 2021-03-29\n\n/***************************************************************************************************** \n *\n * There is a room with n lights which are turned on initially and 4 buttons on the wall. After \n * performing exactly m unknown operations towards buttons, you need to return how many different \n * kinds of status of the n lights could be.\n * \n * Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given \n * below:\n * \n * \tFlip all the lights.\n * \tFlip lights with even numbers.\n * \tFlip lights with odd numbers.\n * \tFlip lights with (3k + 1) numbers, k = 0, 1, 2, ...\n * \n * Example 1:\n * \n * Input: n = 1, m = 1.\n * Output: 2\n * Explanation: Status can be: [on], [off]\n * \n * Example 2:\n * \n * Input: n = 2, m = 1.\n * Output: 3\n * Explanation: Status can be: [on, off], [off, on], [off, off]\n * \n * Example 3:\n * \n * Input: n = 3, m = 1.\n * Output: 4\n * Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].\n * \n * Note: n and m both fit in range [0, 1000].\n ******************************************************************************************************/\n\n/*\n\nWe have 4 operations:\n\n    1) Flip all the lights.\n    2) Flip lights with even numbers.\n    3) Flip lights with odd numbers.\n    4) Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...\n\nif we do 1) + 2), it's same as 3)\nif we do 1) + 3), it's same as 2)\nif we do 2) + 3), it's same as 1)\nif we do 1) + 2) + 3), it's same as do nothing\n\nSo, we can manaully calculate how many different state we could have:\n\n  m = 1, then 1), 2), 3), 4)   \n  \n  m = 2, then 1)+2), 1)+3), 1)+4), 2)+3), 2)+4), 3)+4) and  1)+1) => inital state\n  \n  m = 3, then 1), 2), 3), 4), 1)+4), 2+4), 3)+4),  and  1)+2)+3) => inital state\n\nnotice: \n\n    if m == 1,  we could only have 4 states at most.\n    if m == 2,  we could only have 7 states at most. (no the 4) state) \n    if  m > 2,  we could only have 8 states at most. (has the 4) state)\n\nBut for some edge cases, we need to take care specially. For example:\n\n - m = 0 or n = 0, only 1 state.\n - n = 1, then 2 states.\n - n = 2, then it could have 3(when m=1), or 4 states (whem m>1)\n - n > 2 && m = 1, then it only could have 4 states.\n\n*/\n\nclass Solution {\npublic:\n    int flipLights(int n, int m) {\n        if (m == 0 || n == 0) return 1;\n        if (n == 1) return 2;\n        if (n == 2) return m == 1? 3:4;\n        if (m == 1) return 4;\n        return m==2 ? 7 :8;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bulbSwitcher/BulbSwitcher.III.cpp",
    "content": "// Source : https://leetcode.com/problems/bulb-switcher-iii\n// Author : Hao Chen\n// Date   : 2021-03-29\n\n/***************************************************************************************************** \n *\n * There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. \n * Initially, all the bulbs are turned off.\n * \n * At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only \n * if it is on and all the previous bulbs (to the left) are turned on too.\n * \n * Return the number of moments in which all turned on bulbs are blue.\n * \n * Example 1:\n * \n * Input: light = [2,1,3,5,4]\n * Output: 3\n * Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4.\n * \n * Example 2:\n * \n * Input: light = [3,2,4,1,5]\n * Output: 2\n * Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0).\n * \n * Example 3:\n * \n * Input: light = [4,1,2,3]\n * Output: 1\n * Explanation: All bulbs turned on, are blue at the moment 3 (index-0).\n * Bulb 4th changes to blue at the moment 3.\n * \n * Example 4:\n * \n * Input: light = [2,1,4,3,6,5]\n * Output: 3\n * \n * Example 5:\n * \n * Input: light = [1,2,3,4,5,6]\n * Output: 6\n * \n * Constraints:\n * \n * \tn == light.length\n * \t1 <= n <= 5 * 10^4\n * \tlight is a permutation of  [1, 2, ..., n]\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int numTimesAllBlue(vector<int>& light) {\n        int n = light.size();\n        vector<bool> on(n, false);\n        int left = 0; //tracking the most left place that all bubls are truned on.\n        int result = 0;\n        for(int i=0; i<light.size(); i++){\n            on[light[i]-1] = true;\n            while (left < n && on[left]) left++;\n            //if the bulbs are on left is equal to current bulbs we trun on.\n            //then they all are blue.\n            if (left == i+1) result++; \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bulbSwitcher/BulbSwitcher.IV.cpp",
    "content": "// Source : https://leetcode.com/problems/bulb-switcher-iv/\n// Author : Hao Chen\n// Date   : 2021-03-29\n\n/***************************************************************************************************** \n *\n * There is a room with n bulbs, numbered from 0 to n-1, arranged in a row from left to right. \n * Initially all the bulbs are turned off.\n * \n * Your task is to obtain the configuration represented by target where target[i] is '1' if the i-th \n * bulb is turned on and is '0' if it is turned off.\n * \n * You have a switch to flip the state of the bulb, a flip operation is defined as follows:\n * \n * \tChoose any bulb (index i) of your current configuration.\n * \tFlip each bulb from index i to n-1.\n * \n * When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0.\n * \n * Return the minimum number of flips required to form target.\n * \n * Example 1:\n * \n * Input: target = \"10111\"\n * Output: 3\n * Explanation: Initial configuration \"00000\".\n * flip from the third bulb:  \"00000\" -> \"00111\"\n * flip from the first bulb:  \"00111\" -> \"11000\"\n * flip from the second bulb:  \"11000\" -> \"10111\"\n * We need at least 3 flip operations to form target.\n * \n * Example 2:\n * \n * Input: target = \"101\"\n * Output: 3\n * Explanation: \"000\" -> \"111\" -> \"100\" -> \"101\".\n * \n * Example 3:\n * \n * Input: target = \"00000\"\n * Output: 0\n * \n * Example 4:\n * \n * Input: target = \"001011101\"\n * Output: 5\n * \n * Constraints:\n * \n * \t1 <= target.length <= 10^5\n * \ttarget[i] == '0' or target[i] == '1'\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minFlips(string target) {\n        //flip the target to initalization\n        int flip = 0;\n        for(auto state : target) {\n            if (state == '0' && flip % 2 == 1 ) flip++;\n            if (state == '1' && flip % 2 == 0 ) flip++;\n        }\n        return flip;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp",
    "content": "// Source : https://leetcode.com/problems/bulb-switcher/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-12-28\n\n/*************************************************************************************** \n *\n * There are n bulbs that are initially off. You first turn on all the bulbs. Then, you\n * turn off every second bulb. On the third round, you toggle every third bulb (turning\n * on if it's off or turning off if it's on). For the nth round, you only toggle the\n * last bulb. Find how many bulbs are on after n rounds.\n * \n * Example:\n * \n * Given n = 3. \n * \n * At first, the three bulbs are [off, off, off].\n * After first round, the three bulbs are [on, on, on].\n * After second round, the three bulbs are [on, off, on].\n * After third round, the three bulbs are [on, off, off]. \n * \n * So you should return 1, because there is only one bulb is on.\n * \n ***************************************************************************************/\n\n /* Solution\n  * --------\n  *\n  * We know, \n  *   - if a bulb can be switched to ON eventually, it must be switched by ODD times\n  *   - Otherwise, if a bulb has been switched by EVEN times, it will be OFF eventually.\n  * So, \n  *   - If bulb `i` ends up ON if and only if `i` has an ODD numbers of divisors.\n  * And we know, \n  *   - the divisors come in pairs. for example: \n  *     12 - [1,12] [2,6] [3,4] [6,2] [12,1] (the 12th bulb would be switched by 1,2,3,4,6,12)\n  *   - the pairs means almost all of the numbers are switched by EVEN times.\n  *\n  * But we have a special case - square numbers\n  *   - A square number must have a divisors pair with same number. such as 4 - [2,2], 9 - [3,3]\n  *   - So, a square number has a ODD numbers of divisors.\n  *\n  * At last, we figure out the solution is: \n  *    \n  *    Count the number of the squre numbers!! \n  */\n\nclass Solution {\npublic:\n    int bulbSwitch(int n) {\n        int cnt = 0;\n        for (int i=1; i*i<=n; i++) { \n            cnt++;\n        }\n        return cnt;\n    }\n};\n\n\n\n /* \n * Solution 1 - O(1)\n * =========\n *\n * We notice that for every light bulb on position i there will be one toggle for every\n * one of its divisors, given that you toggle all of the multiples of one number. The \n * total number of toggles is irrelevant, because there are only 2 possible positions(on, \n * off). We quickly find that 2 toggles cancel each other so given that the start position\n * is always off a light bulb will be in if it has been toggled an odd number of times.\n * The only integers with an odd number of divisors are perfect squares(because the square\n * root only appears once, not like the other divisors that form pairs). The problem comes\n * down to finding the number of perfect squares <= n. That number is the integer part of\n * the square root of n.\n * \n */\nclass Solution {\npublic:\n    int bulbSwitch(int n) {\n        return (int)sqrt(n);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/bullsAndCows/bullsAndCows.cpp",
    "content": "// Source : https://leetcode.com/problems/bulls-and-cows/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-11-04\n\n/*************************************************************************************** \n *\n * You are playing the following Bulls and Cows game with your friend: You write a \n * 4-digit secret number and ask your friend to guess it. Each time your friend guesses\n * a number, you give a hint. The hint tells your friend how many digits are in the\n * correct positions (called \"bulls\") and how many digits are in the wrong positions\n * (called \"cows\"). Your friend will use those hints to find out the secret number.\n * \n * For example:\n * \n * Secret number:  \"1807\"\n * Friend's guess: \"7810\"\n * Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)\n * Write a function to return a hint according to the secret number and friend's guess,\n * use A to indicate the bulls and B to indicate the cows. In the above example, your\n * function should return \"1A3B\".\n * \n * Please note that both secret number and friend's guess may contain duplicate digits,\n * for example:\n * \n * Secret number:  \"1123\"\n * Friend's guess: \"0111\"\n * In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and\n * your function should return \"1A1B\".\n * You may assume that the secret number and your friend's guess only contain digits,\n * and their lengths are always equal.\n * \n * Credits:\n * Special thanks to @jeantimex for adding this problem and creating all test cases.\n *               \n ***************************************************************************************/\n \nclass Solution {\npublic:\n    string getHint(string secret, string guess) {\n        return getHint02(secret, guess);\n        return getHint01(secret, guess);\n    }\n\n    string getHint01(string secret, string guess) {\n        int appears_in_secret[10] = {0}, appears_in_guess[10] = {0}, bulls[10] = {0};\n        int total_bulls = 0, total_cows = 0;\n        for(int i = 0; i < secret.size(); i++)\n            appears_in_secret[secret[i] - '0']++;\n        for(int i = 0; i < guess.size(); i++)\n        {\n             if(secret[i] == guess[i])\n                 bulls[secret[i] - '0']++;\n             appears_in_guess[guess[i] - '0']++;\n        }\n        for(int i = 0; i <= 9; i++)\n        {\n            total_bulls += bulls[i];\n            total_cows += min(appears_in_secret[i], appears_in_guess[i]) - bulls[i];\n        }\n        return to_string(total_bulls) + \"A\" + to_string(total_cows) + \"B\";\n    }\n\n    // Another implemntation - to save more space\n    string getHint02(string secret, string guess) {\n        \n        const int digital_num = 10;\n        int secret_stat[digital_num]={0};\n        \n        int bull = 0;\n        for(int i=0; i<secret.size(); i++) {\n            //both number & location are matched, count bull\n            if ( secret[i] == guess[i] ) {\n                bull++;\n                continue;\n            }\n            //otherwise, count the unmatched digits.\n            secret_stat[secret[i]-'0']++;\n        }\n        \n        int cow = 0;\n        for(int i=0; i<guess.size(); i++) {\n            //deal with duplication - decrease the digits count if cow is found.\n            if ( secret[i] != guess[i] && secret_stat[guess[i]-'0']-- > 0 ) {\n                cow++;\n            }\n        }\n        \n        return to_string(bull) + \"A\" + to_string(cow) + \"B\";\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/burstBalloons/BurstBalloons.cpp",
    "content": "// Source : https://leetcode.com/problems/burst-balloons/\n// Author : Hao Chen\n// Date   : 2016-01-17\n\n/*************************************************************************************** \n *\n * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a\n *     number on it represented by array nums.\n * \n *     You are asked to burst all the balloons. If the you burst\n *     balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left\n *     and right are adjacent indices of i. After the burst, the left and right\n *     then becomes adjacent.\n * \n *     Find the maximum coins you can collect by bursting the balloons wisely.\n * \n *     Note: \n *     (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can \n * not burst them.\n *     (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100\n * \n *     Example:\n * \n *     Given [3, 1, 5, 8]\n * \n *     Return 167\n * \n *     nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []\n *    coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\n\nclass Solution {\npublic:\n    int maxCoins(vector<int>& nums) {\n        //remove all of zero item\n        nums.erase(remove_if(nums.begin(), nums.end(), [](int n){return n==0;}), nums.end());\n        \n        //add 1 for head and tail\n        nums.insert(nums.begin(),1);\n        nums.push_back(1);\n        \n        int n = nums.size();\n        vector< vector<int> > matrix(n, vector<int>(n,0));\n        \n        return maxCoins_DP(nums, matrix);\n        return maxCoins_DC(nums, matrix, 0, n-1);\n    }\n    \n    \n    //Divide and Conquer\n    //\n    //  If we seprate the array to two part, left part and right part.\n    //\n    //  Then, we will find in this problem the left and right become adjacent \n    //  and have effects on the maxCoins in the future.\n    //\n    //  So, if we think reversely, if the balloon i is the last balloon of all to burst, \n    //  the left and right section now has well defined boundary and do not affect each other! \n    //  Therefore we can do either recursive method with memoization\n    //\n    int maxCoins_DC(vector<int>& nums, vector<vector<int>>& matrix, int low, int high) {\n        if (low + 1 == high) return 0;\n        if (matrix[low][high] > 0) return matrix[low][high];\n        int result = 0;\n        for (int i = low + 1; i < high; ++i){\n            result = max(result,  nums[low] * nums[i] * nums[high] \n                                    + maxCoins_DC(nums, matrix, low, i) \n                                    + maxCoins_DC(nums, matrix, i, high));\n        }\n        matrix[low][high] = result;\n        return result;\n    }\n    \n    //Dynamic Programming\n    // \n    //  using the same idea of above \n    //\n    int maxCoins_DP(vector<int>& nums, vector<vector<int>>& dp) {\n        int n = nums.size();\n        for (int k = 2; k < n; ++k) {\n            for (int low = 0; low < n - k; low++){\n                int high = low + k;\n                for (int i = low + 1; i < high; ++i)\n                    dp[low][high] = max( dp[low][high],\n                         nums[low] * nums[i] * nums[high] + dp[low][i] + dp[i][high]);\n            }\n        }\n        return dp[0][n - 1];\n    }\n    \nprivate:\n    void printVector(vector<int>& nums) {\n        cout << \"nums: \";\n        for (auto n: nums) {\n            cout << n << ' ';\n        }\n        cout << '\\n';\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/calculateMoneyInLeetcodeBank/CalculateMoneyInLeetcodeBank.cpp",
    "content": "// Source : https://leetcode.com/problems/calculate-money-in-leetcode-bank/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.\n * \n * He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put \n * in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the \n * previous Monday. \n * \n * Given n, return the total amount of money he will have in the Leetcode bank at the end of the n^th \n * day.\n * \n * Example 1:\n * \n * Input: n = 4\n * Output: 10\n * Explanation: After the 4^th day, the total is 1 + 2 + 3 + 4 = 10.\n * \n * Example 2:\n * \n * Input: n = 10\n * Output: 37\n * Explanation: After the 10^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. \n * Notice that on the 2^nd Monday, Hercy only puts in $2.\n * \n * Example 3:\n * \n * Input: n = 20\n * Output: 96\n * Explanation: After the 20^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 \n * + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n * \n * Constraints:\n * \n * \t1 <= n <= 1000\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int totalMoney(int n) {\n        int weeks = n / 7;\n        int days = n % 7;\n        \n        int m = 1 + 2 + 3 + 4 + 5 + 6 + 7;\n        // we know\n        //     week1 = 0*7 + m\n        //     week2 = 1*7 + m \n        //     week3 = 2*7 + m \n        //     weekn = (n-1)*7 + m\n        // So, \n        //     week1 + week2 + week3 + ....+ weekn \n        //   = n*m + 7*(0+1+2+..n-1)\n        //   = n*m + 7*(n-1)*n/2\n        \n        int money = weeks*m + 7 * (weeks-1) * weeks / 2;\n        \n        // for the rest days\n        // every day needs to add  previous `weeks * 1`, it is  days* weeks\n        // then add from 1 to days\n        money += (days*weeks + days*(days+1)/2);\n        \n        return money;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/candy/candy.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/candy/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* There are N children standing in a line. Each child is assigned a rating value. \n* \n* You are giving candies to these children subjected to the following requirements:\n* \n* Each child must have at least one candy.\n* Children with a higher rating get more candies than their neighbors.\n* \n* What is the minimum candies you must give?\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\nvoid print(vector<int> &v);\n\n/*\n *    The soluiton is O(2n) run-time complexity\n *\n *    For example:\n *\n *        ratings[] = { 5, 6, 7, 4, 1, 2, 3, 2, 1, 7 } \n *\n *    1) Go through the ratings from left to right.\n *\n *       Find the each increasing sub-array, giving the minimal candy     \n *\n *        ratings[] = { 5, 6, 7,   4,   1, 2, 3,   2,   1, 7 } \n *                      ------>    ->   ------>    ->   --->\n *          candy[] = { 1, 2, 3,   1,   1, 2, 3,   1,   1, 2 }\n *\n *    2) Go through the raings from right to left.\n *\n *             ratings[] = { 5,   6,   7, 4, 1,   2,   3, 2, 1,   7 } \n *                           <-   <-   <------    <-   <------    <-\n *          prev_candy[] = { 1,   2,   3, 1, 1,   2,   3, 1, 1,   2 }\n *                                        +1              +1\n *               candy[] = { 1,   2,   3, 2, 1,   2,   3, 2, 1,   2 }\n *\n *    3) total candy is 19\n *\n */\nint candy(vector<int> &ratings) {\n\n    vector<int> candyCnt(ratings.size()) ;\n    //allocate candies, considering the minimal rating on the left\n    candyCnt[0] = 1;\n    for(int i = 1; i < ratings.size(); i++){\n        candyCnt[i] = ratings[i] > ratings[i-1] ? candyCnt[i-1]+1 : 1;\n    }\n    print(candyCnt); \n    //modify the allocation, considering the minimal rating on the right\n    int totalCandy = candyCnt[ratings.size()-1];\n    for(int i = ratings.size()-2; i >= 0; i--){\n        candyCnt[i] = (ratings[i] > ratings[i+1] && candyCnt[i+1]+1 > candyCnt[i]) ? candyCnt[i+1]+1 : candyCnt[i];\n        //count total candies by the way\n        totalCandy += candyCnt[i];\n    }\n    print(candyCnt);\n    return totalCandy;\n}\n\nvoid generateRatings(vector<int> &ratings, int n) {\n    srand(time(0));\n    for (int i=0; i<n; i++) {\n        ratings.push_back(rand()%10);\n    }\n}\n\nvoid print(vector<int> &v) {\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] << \" \";\n    }\n    cout << endl;\n}\n\nint main(int argc, char**argv)\n{\n    int n = 10;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }   \n    vector<int> ratings;\n    generateRatings(ratings, n);\n    print(ratings);\n\n    cout << candy(ratings) << endl;\n\n    cout << \"--------------------\" << endl;\n    int r[] = { 5, 6, 7, 4, 1, 2, 3, 2, 1, 7 };\n    vector<int> ra(r, r+sizeof(r)/sizeof(r[0]));\n    print(ra);\n    cout << candy(ra) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/checkIfArrayIsSortedAndRotated/CheckIfArrayIsSortedAndRotated.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/\n// Author : Hao Chen\n// Date   : 2021-02-11\n\n/***************************************************************************************************** \n *\n * Given an array nums, return true if the array was originally sorted in non-decreasing order, then \n * rotated some number of positions (including zero). Otherwise, return false.\n * \n * There may be duplicates in the original array.\n * \n * Note: An array A rotated by x positions results in an array B of the same length such that A[i] == \n * B[(i+x) % A.length], where % is the modulo operation.\n * \n * Example 1:\n * \n * Input: nums = [3,4,5,1,2]\n * Output: true\n * Explanation: [1,2,3,4,5] is the original sorted array.\n * You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].\n * \n * Example 2:\n * \n * Input: nums = [2,1,3,4]\n * Output: false\n * Explanation: There is no sorted array once rotated that can make nums.\n * \n * Example 3:\n * \n * Input: nums = [1,2,3]\n * Output: true\n * Explanation: [1,2,3] is the original sorted array.\n * You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n * \n * Example 4:\n * \n * Input: nums = [1,1,1]\n * Output: true\n * Explanation: [1,1,1] is the original sorted array.\n * You can rotate any number of positions to make nums.\n * \n * Example 5:\n * \n * Input: nums = [2,1]\n * Output: true\n * Explanation: [1,2] is the original sorted array.\n * You can rotate the array by x = 5 positions to begin on the element of value 2: [2,1].\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 100\n * \t1 <= nums[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool check(vector<int>& nums) {\n        int len = nums.size();\n        \n        //deal with the rotated case - the first element is greater than last one\n        bool rotate = (nums[0] >= nums[len-1]);\n        \n        for (int i = 0; i < len-1; i++) {\n            if ( nums[i] <= nums[i+1] ) continue;\n            \n            if (rotate) {\n                rotate = false;\n                continue;\n            }\n            return false;\n            \n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/checkIfBinaryStringHasAtMostOneSegmentOfOnes/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/\n// Author : Hao Chen\n// Date   : 2021-03-07\n\n/***************************************************************************************************** \n *\n * Given a binary string s without leading zeros, return true if s contains at most one \n * contiguous segment of ones. Otherwise, return false.\n * \n * Example 1:\n * \n * Input: s = \"1001\"\n * Output: false\n * Explanation: The ones do not form a contiguous segment.\n * \n * Example 2:\n * \n * Input: s = \"110\"\n * Output: true\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \ts[i] is either '0' or '1'.\n * \ts[0] is '1'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool checkOnesSegment(string s) {\n        int i=0;\n        while(i<s.size() && s[i]=='1') i++; \n        while(i<s.size() && s[i]=='0') i++;\n        if(i<s.size() && s[i]=='1') return false;\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/checkIfNumberIsASumOfPowersOfThree/CheckIfNumberIsASumOfPowersOfThree.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/\n// Author : Hao Chen\n// Date   : 2021-03-13\n\n/***************************************************************************************************** \n *\n * Given an integer n, return true if it is possible to represent n as the sum of distinct powers of \n * three. Otherwise, return false.\n * \n * An integer y is a power of three if there exists an integer x such that y == 3x.\n * \n * Example 1:\n * \n * Input: n = 12\n * Output: true\n * Explanation: 12 = 31 + 32\n * \n * Example 2:\n * \n * Input: n = 91\n * Output: true\n * Explanation: 91 = 30 + 32 + 34\n * \n * Example 3:\n * \n * Input: n = 21\n * Output: false\n * \n * Constraints:\n * \n * \t1 <= n <= 107\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool checkPowersOfThree(int n) {\n        return checkPowersOfThree_Base3(n);\n        return checkPowersOfThree_DFS(n, 1);\n    }\n    \n    bool checkPowersOfThree_DFS(int n, int p) { \n        if (n == p ) return true;\n        if (n < p ) return false;\n        \n        return (checkPowersOfThree_DFS(n-p, p*3) || checkPowersOfThree_DFS(n, p*3));\n    }\n    /*\n     * convert base-10 number to base-3 number\n     * for example: \n     *    12 ->  110 = 1*3^2 + 1*3^1 + 0*3^0\n     *    16 ->  121 = 1*3^2 + 2*3^1 + 1*3^0\n     *    21 ->  210 = 2*3^2 + 1*3^1 + 0*3^0\n     *    \n     *    91 -> 1011 = 1*3^4 + 0*3^2 + 1*3^1 + 1*3^0\n     *    \n     * so, we can see, if a base3 number only has 1 or 0, then it's valid.\n     * if `2` appeas, then it's invalid.\n     */\n    bool checkPowersOfThree_Base3(int n) { \n        for (; n>0; n/=3) {\n            if (n%3 == 2) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/checkIfOneStringSwapCanMakeStringsEqual/CheckIfOneStringSwapCanMakeStringsEqual.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/\n// Author : Hao Chen\n// Date   : 2021-03-19\n\n/***************************************************************************************************** \n *\n * You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose \n * two indices in a string (not necessarily different) and swap the characters at these indices.\n * \n * Return true if it is possible to make both strings equal by performing at most one string swap on \n * exactly one of the strings. Otherwise, return false.\n * \n * Example 1:\n * \n * Input: s1 = \"bank\", s2 = \"kanb\"\n * Output: true\n * Explanation: For example, swap the first character with the last character of s2 to make \"bank\".\n * \n * Example 2:\n * \n * Input: s1 = \"attack\", s2 = \"defend\"\n * Output: false\n * Explanation: It is impossible to make them equal with one string swap.\n * \n * Example 3:\n * \n * Input: s1 = \"kelb\", s2 = \"kelb\"\n * Output: true\n * Explanation: The two strings are already equal, so no string swap operation is required.\n * \n * Example 4:\n * \n * Input: s1 = \"abcd\", s2 = \"dcba\"\n * Output: false\n * \n * Constraints:\n * \n * \t1 <= s1.length, s2.length <= 100\n * \ts1.length == s2.length\n * \ts1 and s2 consist of only lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool areAlmostEqual(string s1, string s2) {\n        int p[2]={0};\n        int diff=0;\n        for(int i=0; i<s1.size(); i++){\n            if (s1[i] ==s2[i]) continue;\n            if (diff < 2) p[diff] = i;\n            diff++;\n        }\n        \n        return (diff==0) || ( (diff == 2) && s1[p[0]] == s2[p[1]] && s1[p[1]] == s2[p[0]]);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/checkIfTheSentenceIsPangram/CheckIfTheSentenceIsPangram.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-the-sentence-is-pangram/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * A pangram is a sentence where every letter of the English alphabet appears at least once.\n * \n * Given a string sentence containing only lowercase English letters, return true if sentence is a \n * pangram, or false otherwise.\n * \n * Example 1:\n * \n * Input: sentence = \"thequickbrownfoxjumpsoverthelazydog\"\n * Output: true\n * Explanation: sentence contains at least one of every letter of the English alphabet.\n * \n * Example 2:\n * \n * Input: sentence = \"leetcode\"\n * Output: false\n * \n * Constraints:\n * \n * \t1 <= sentence.length <= 1000\n * \tsentence consists of lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool checkIfPangram(string sentence) {\n        bool stat[26] = {false};\n        for(auto& c: sentence) {\n            stat[c - 'a'] = true;\n        }\n        for(auto& s : stat) {\n            if (!s) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/checkIfWordEqualsSummationOfTwoWords/CheckIfWordEqualsSummationOfTwoWords.cpp",
    "content": "// Source : https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> \n * 1, 'c' -> 2, etc.).\n * \n * The numerical value of some string of lowercase English letters s is the concatenation of the \n * letter values of each letter in s, which is then converted into an integer.\n * \n * \tFor example, if s = \"acb\", we concatenate each letter's letter value, resulting in \"021\". \n * After converting it, we get 21.\n * \n * You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase \n * English letters 'a' through 'j' inclusive.\n * \n * Return true if the summation of the numerical values of firstWord and secondWord equals the \n * numerical value of targetWord, or false otherwise.\n * \n * Example 1:\n * \n * Input: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\n * Output: true\n * Explanation:\n * The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\n * The numerical value of secondWord is \"cba\" -> \"210\" -> 210.\n * The numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\n * We return true because 21 + 210 == 231.\n * \n * Example 2:\n * \n * Input: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\n * Output: false\n * Explanation: \n * The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\n * The numerical value of secondWord is \"a\" -> \"0\" -> 0.\n * The numerical value of targetWord is \"aab\" -> \"001\" -> 1.\n * We return false because 0 + 0 != 1.\n * \n * Example 3:\n * \n * Input: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\n * Output: true\n * Explanation: \n * The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\n * The numerical value of secondWord is \"a\" -> \"0\" -> 0.\n * The numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\n * We return true because 0 + 0 == 0.\n * \n * Constraints:\n * \n * \t1 <= firstWord.length, secondWord.length, targetWord.length <= 8\n * \tfirstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' \n * inclusive.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int strToInt(string& str) {\n        int n = 0;\n        for(auto& c :str) {\n            n = n*10 + c - 'a';\n        }\n        return n;\n    }\n    bool isSumEqual(string firstWord, string secondWord, string targetWord) {\n        return strToInt(firstWord) + strToInt(secondWord) == strToInt(targetWord);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/climbStairs/climbStairs.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/climbing-stairs/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* You are climbing a stair case. It takes n steps to reach to the top.\n* \n* Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    \n    int climbStairs(int n) {\n       if (n<=3) return n;\n       int a[2]={2,3};\n       for(int i=4; i<=n; i++){\n           int t = a[0] + a[1];\n           a[0] = a[1];\n           a[1] = t;\n       }\n       return a[1];\n    }\n    //Time too long\n    int climbStairs2(int n) {\n        if (n<=3) return n;\n        return climbStairs(n-1) + climbStairs(n-2);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/cloneGraph/cloneGraph.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/clone-graph/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.\n* \n* OJ's undirected graph serialization:\n* \n* Nodes are labeled uniquely.\n* \n* We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.\n* \n* As an example, consider the serialized graph {0,1,2#1,2#2,2}.\n* \n* The graph has a total of three nodes, and therefore contains three parts as separated by #.\n* \n* First node is labeled as 0. Connect node 0 to both nodes 1 and 2.\n* Second node is labeled as 1. Connect node 1 to node 2.\n* Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.\n* \n* Visually, the graph looks like the following:\n* \n*        1\n*       / \\\n*      /   \\\n*     0 --- 2\n*          / \\\n*          \\_/\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for undirected graph.\n * struct UndirectedGraphNode {\n *     int label;\n *     vector<UndirectedGraphNode *> neighbors;\n *     UndirectedGraphNode(int x) : label(x) {};\n * };\n */\nclass Solution {\npublic:\n    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {\n        if (node == NULL) return NULL;\n        \n        //create a map, key is source node, value is clone node.\n        map<UndirectedGraphNode*, UndirectedGraphNode*> cloneMap;\n        \n        //using queue for breadth first search\n        queue<UndirectedGraphNode*> q;\n        q.push(node);\n        \n        //clone the root\n        UndirectedGraphNode* cloneNode = new UndirectedGraphNode(node->label);\n        cloneMap[node] = cloneNode;\n        \n        //breadth first search\n        while(!q.empty()){\n            UndirectedGraphNode* n = q.front();\n            q.pop();\n            //for each neighbors\n            for(int i=0; i<n->neighbors.size(); i++){\n                UndirectedGraphNode* neighbor= n->neighbors[i];\n                //not existed in cloneMap\n                if (cloneMap.find(neighbor)==cloneMap.end()){\n                    //clone a node\n                    UndirectedGraphNode* newNode = new UndirectedGraphNode(neighbor->label);\n                    cloneMap[n]->neighbors.push_back(newNode);\n                    cloneMap[neighbor] = newNode;\n                    \n                    //put the neighbors into the queue\n                    q.push(neighbor);\n                }else{\n                    cloneMap[n]->neighbors.push_back(cloneMap[neighbor]);\n                }\n            }\n        }\n        \n        return cloneNode;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/closestDessertCost/ClosestDessertCost.cpp",
    "content": "// Source : https://leetcode.com/problems/closest-dessert-cost/\n// Author : Hao Chen\n// Date   : 2021-03-14\n\n/***************************************************************************************************** \n *\n * You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base \n * flavors and m types of toppings to choose from. You must follow these rules when making your \n * dessert:\n * \n * \tThere must be exactly one ice cream base.\n * \tYou can add one or more types of topping or have no toppings at all.\n * \tThere are at most two of each type of topping.\n * \n * You are given three inputs:\n * \n * \tbaseCosts, an integer array of length n, where each baseCosts[i] represents the price of \n * the ith ice cream base flavor.\n * \ttoppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one \n * of the ith topping.\n * \ttarget, an integer representing your target price for dessert.\n * \n * You want to make a dessert with a total cost as close to target as possible.\n * \n * Return the closest possible cost of the dessert to target. If there are multiple, return the lower \n * one.\n * \n * Example 1:\n * \n * Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10\n * Output: 10\n * Explanation: Consider the following combination (all 0-indexed):\n * - Choose base 1: cost 7\n * - Take 1 of topping 0: cost 1 x 3 = 3\n * - Take 0 of topping 1: cost 0 x 4 = 0\n * Total: 7 + 3 + 0 = 10.\n * \n * Example 2:\n * \n * Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\n * Output: 17\n * Explanation: Consider the following combination (all 0-indexed):\n * - Choose base 1: cost 3\n * - Take 1 of topping 0: cost 1 x 4 = 4\n * - Take 2 of topping 1: cost 2 x 5 = 10\n * - Take 0 of topping 2: cost 0 x 100 = 0\n * Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.\n * \n * Example 3:\n * \n * Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9\n * Output: 8\n * Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.\n * \n * Example 4:\n * \n * Input: baseCosts = [10], toppingCosts = [1], target = 1\n * Output: 10\n * Explanation: Notice that you don't have to have any toppings, but you must have exactly one base.\n * \n * Constraints:\n * \n * \tn == baseCosts.length\n * \tm == toppingCosts.length\n * \t1 <= n, m <= 10\n * \t1 <= baseCosts[i], toppingCosts[i] <= 104\n * \t1 <= target <= 104\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int abs_min (int x, int y, int z) {\n        return  abs_min(x, abs_min(y, z));\n    }\n    // compare the absolute value and return the min one\n    // if their absolute value are equal, return the positive one.\n    int abs_min(int x, int y) {\n        int ax = abs(x);\n        int ay = abs(y);\n        if (ax == ay) return max(x, y);\n        return ax < ay ? x : y;\n    }\npublic:\n    int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {\n\n        int min_gap = INT_MAX;\n        for (auto& base : baseCosts) {\n            int gap = closetToppingCost(toppingCosts, target - base, 0);\n            min_gap = abs_min(min_gap, gap);\n        }\n        \n        return target - min_gap;\n    }\n    \n    int closetToppingCost(vector<int>& costs, int target, int idx ){\n    \n        if (idx >= costs.size()) return target;\n\n        // three options: not slect, select once & select twice\n        int select_none  = closetToppingCost(costs, target, idx+1);\n        int select_once  = closetToppingCost(costs, target - costs[idx], idx+1);\n        int select_twice = closetToppingCost(costs, target - 2*costs[idx], idx+1);\n        \n        return abs_min(select_none, select_once, select_twice);\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/closestRoom/ClosestRoom.cpp",
    "content": "// Source : https://leetcode.com/problems/closest-room/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] \n * = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. \n * Each roomIdi is guaranteed to be unique.\n * \n * You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The \n * answer to the j^th query is the room number id of a room such that:\n * \n * \tThe room has a size of at least minSizej, and\n * \tabs(id - preferredj) is minimized, where abs(x) is the absolute value of x.\n * \n * If there is a tie in the absolute difference, then use the room with the smallest such id. If there \n * is no such room, the answer is -1.\n * \n * Return an array answer of length k where answer[j] contains the answer to the j^th query.\n * \n * Example 1:\n * \n * Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\n * Output: [3,-1,3]\n * Explanation: The answers to the queries are as follows:\n * Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The \n * answer is 3.\n * Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\n * Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The \n * answer is 3.\n * \n * Example 2:\n * \n * Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\n * Output: [2,1,3]\n * Explanation: The answers to the queries are as follows:\n * Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The \n * answer is 2.\n * Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is \n * smaller.\n * Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.\n * \n * Constraints:\n * \n * \tn == rooms.length\n * \t1 <= n <= 10^5\n * \tk == queries.length\n * \t1 <= k <= 10^4\n * \t1 <= roomIdi, preferredj <= 10^7\n * \t1 <= sizei, minSizej <= 10^7\n * \n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    void print(vector<vector<int>>& vv) {\n        cout << \"[\";\n        int i = 0;\n        for(; i<vv.size()-1; i++) {\n            cout << \"[\" << vv[i][0] << \",\" << vv[i][1] << \"],\";\n        }\n        cout << \"[\" << vv[i][0] << \",\" << vv[i][1] << \"]]\" << endl;\n    }\npublic:\n    vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {\n        \n\n        for(int i=0; i<queries.size(); i++) { \n            queries[i].push_back(i);\n        }\n        \n        // sorted the rooms by size by descending order, because query the minimal size.\n        auto sort_by_size_desc =  [&](vector<int>& lhs, vector<int>&rhs) {\n            if (lhs[1] != rhs[1] ) return lhs[1] > rhs[1];\n            return lhs[0] < rhs[0];\n        };\n        sort(rooms.begin(), rooms.end(), sort_by_size_desc);\n        sort(queries.begin(), queries.end(), sort_by_size_desc);\n        //print(rooms);\n        //print(queries);\n        \n        vector<int> result(queries.size(), -1);\n        set<int> ids;\n        int i = 0;\n        for( auto& q: queries) {\n            int preferId = q[0];\n            int minSize = q[1];\n            int idx = q[2];\n            for (;i < rooms.size() && rooms[i][1] >= minSize; i++) {\n                ids.insert(rooms[i][0]);\n            }\n            if (ids.size() <= 0 ) continue;\n            auto it = ids.lower_bound(preferId); \n            \n            int id1 = (it == ids.begin() ? -1 : *(prev(it)));\n            int id2 = (it == ids.end() ? -1 : *it);\n            \n            if (id1 == -1 || id2 == -1) {\n                result[idx] = max(id1, id2);\n            }else{\n                result[idx] = abs(preferId - id1) <= abs(preferId - id2) ? id1 : id2;\n            }\n            \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/closestSubsequenceSum/ClosestSubsequenceSum.cpp",
    "content": "// Source : https://leetcode.com/problems/closest-subsequence-sum/\n// Author : Hao Chen\n// Date   : 2021-02-15\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums and an integer goal.\n * \n * You want to choose a subsequence of nums such that the sum of its elements is the closest possible \n * to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the \n * absolute difference abs(sum - goal).\n * \n * Return the minimum possible value of abs(sum - goal).\n * \n * Note that a subsequence of an array is an array formed by removing some elements (possibly all or \n * none) of the original array.\n * \n * Example 1:\n * \n * Input: nums = [5,-7,3,5], goal = 6\n * Output: 0\n * Explanation: Choose the whole array as a subsequence, with a sum of 6.\n * This is equal to the goal, so the absolute difference is 0.\n * \n * Example 2:\n * \n * Input: nums = [7,-9,15,-2], goal = -5\n * Output: 1\n * Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.\n * The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n * \n * Example 3:\n * \n * Input: nums = [1,2,3], goal = -7\n * Output: 7\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 40\n * \t-107 <= nums[i] <= 107\n * \t-109 <= goal <= 109\n ******************************************************************************************************/\n\nclass Solution {\nprivate: \n    int abs(int n){\n        return n>0 ? n : -n;\n    }\n    \n    void printSet(set<int>& s){\n        cout << \"[\";\n        for(auto& n : s) {\n            cout << n << \", \";\n        }\n        cout << \"]\" << endl;\n    }\n    \n    int findClosetDiff(set<int>& sums, int goal) {\n        auto it = sums.lower_bound(goal);\n        \n        // find the first item >= goal\n        int high = (it == sums.end()) ? *(sums.rbegin()) : *it;\n        // find the first item < goal\n        int low = (it != sums.begin()) ? *(--it) : *it; \n        \n        return min(abs(low - goal), abs(high - goal));\n    }\n    \n    // walk through all of element, and each element could have two chioces:\n    // add itself into sum or not. So, the time complexity is O(2^n)\n    void getAllSums(int index, int end, vector<int>& nums, int sum, set<int>& sums) {\n        if (index > end ) { // the latest one\n            sums.insert(sum);\n            return;\n        }\n        getAllSums(index+1, end, nums, sum+nums[index], sums); // add it into sum\n        getAllSums(index+1, end, nums, sum, sums); // skip this item\n    }\n    \n    void getAllSums(int start, int end, vector<int>& nums, set<int>& sums) {\n        //sums.clear(); \n        sums.insert(0);\n        for (int i=start; i<=end; i++) {\n            vector<int> s(sums.begin(), sums.end());\n            for (auto n : s) {\n                sums.insert(n + nums[i]);\n            }\n        }\n    }\npublic:\n    int minAbsDifference(vector<int>& nums, int goal) {\n        set<int> sums_left, sums_right;\n        //seprate the arrage to two parts\n        int mid = nums.size() / 2;\n        // ---The recusive way cause the TLE problem---\n        //getAllSums(0, mid, nums, 0, sums_left);\n        //getAllSums(mid+1, nums.size()-1, nums, 0, sums_right);\n        getAllSums(0, mid, nums, sums_left);\n        getAllSums(mid+1, nums.size()-1, nums, sums_right);\n        \n        int minDiff = INT_MAX;\n        for (auto& sum : sums_left) {\n            // Two Sum problem:\n            //  - sum_left + sum_right = goal\n            //  - sum_right = goal = sum_left\n            minDiff = min(minDiff, findClosetDiff(sums_right, goal - sum));\n        }\n        return minDiff;\n    }\n    \n\n};\n"
  },
  {
    "path": "algorithms/cpp/coinChange/CoinChange2.cpp",
    "content": "// Source : https://leetcode.com/problems/coin-change-2/\n// Author : Hao Chen\n// Date   : 2019-03-18\n\n/***************************************************************************************************** \n *\n * You are given coins of different denominations and a total amount of money. Write a function to \n * compute the number of combinations that make up that amount. You may assume that you have infinite \n * number of each kind of coin.\n * \n * Example 1:\n * \n * Input: amount = 5, coins = [1, 2, 5]\n * Output: 4\n * Explanation: there are four ways to make up the amount:\n * 5=5\n * 5=2+2+1\n * 5=2+1+1+1\n * 5=1+1+1+1+1\n * \n * Example 2:\n * \n * Input: amount = 3, coins = [2]\n * Output: 0\n * Explanation: the amount of 3 cannot be made up just with coins of 2.\n * \n * Example 3:\n * \n * Input: amount = 10, coins = [10] \n * Output: 1\n * \n * Note:\n * \n * You can assume that\n * \n * \t0 <= amount <= 5000\n * \t1 <= coin <= 5000\n * \tthe number of coins is less than 500\n * \tthe answer is guaranteed to fit into signed 32-bit integer\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    int change(int amount, vector<int>& coins) {\n        return change_dp(amount, coins);\n        return change_recursive(amount, coins); // Time Limit Error\n    }\n    \n    \n    int change_recursive(int amount, vector<int>& coins) {\n        int result = 0;\n        change_recursive_helper(amount, coins, 0, result);\n        return result;\n    }\n    \n    // the `idx` is used for remove the duplicated solutions.\n    void change_recursive_helper(int amount, vector<int>& coins, int idx, int& result) {\n        if (amount == 0) { \n            result++; \n            return;\n        }\n    \n        for ( int i = idx; i < coins.size(); i++ ) {\n            if (amount < coins[i]) continue;\n            change_recursive_helper(amount - coins[i], coins, i, result);\n        }\n        return;\n    }\n    \n    int change_dp(int amount, vector<int>& coins) {\n        vector<int> dp(amount+1, 0);\n        dp[0] = 1;\n        for (int i=0; i<coins.size(); i++) {\n            for(int n=1; n<=amount; n++) {\n                if (n >= coins[i]) {\n                    dp[n] += dp[n-coins[i]];\n                }\n            }\n        }\n\n        return dp[amount];\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/coinChange/coinChange.cpp",
    "content": "// Source : https://leetcode.com/problems/coin-change/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-12-28\n\n/*************************************************************************************** \n *\n * You are given coins of different denominations and a total amount of money amount. \n * Write a function to compute the fewest number of coins that you need to make up that\n * amount. If that amount of money cannot be made up by any combination of the coins,\n * return -1.\n * \n * Example 1:\n * coins = [1, 2, 5], amount = 11\n * return 3 (11 = 5 + 5 + 1)\n * \n * Example 2:\n * coins = [2], amount = 3\n * return -1.\n * \n * Note:\n * You may assume that you have an infinite number of each kind of coin.\n * \n * Credits:\n * Special thanks to @jianchao.li.fighter for adding this problem and creating all test \n * cases.\n * \n ***************************************************************************************/\n\n\n/* Recursive solution - TIME LIMIT ERROR */\nclass Solution {\npublic:\n    int coinChange(vector<int>& coins, int amount) {  \n        int result = INT_MAX;\n        if ( amount == 0 ) return 0;\n        if ( amount < 0 ) return -1;\n        for (int i=0; i<coins.size(); i++) {\n            if ( amount - coins[i] < 0 ) continue;\n            int r = coinChange(coins, amount - coins[i]);\n            if ( r == -1 ) continue;\n            if (result > r )  result = r + 1;\n        }\n        return result == INT_MAX ? -1 : result;\n    }\n}\n\n\n /* \n * Solution 1 - O(N * amount)\n * =========\n *\n * This problem can be solved using dynamic programming, thus building the optimal\n * solution from previous smaller ones. For every coin of value t and every sum of money\n * i the sum can be traced back to a previous sum i - t that was already computed and uses\n * the smallest number of coins possible. This way we can construct every sum i as the\n * minimum of all these previous sums for every coin value. To be sure we'll find a minimum\n * we can populate the solution vector with an amount bigger than the maximum possible, \n * which is amount + 1(when the sum is made up of only coins of value 1). The only exception\n * is sol[0] which is 0 as we need 0 coins to have a sum of 0. In the end we need to look\n * if the program found a solution in sol[amount] or it remained the same, in which case we\n * can return -1.\n * \n */\nclass Solution {\npublic:\n    \n    int coinChange(vector<int>& coins, int amount) {\n        int sol[amount + 1];\n        sol[0] = 0;\n        for(int i = 1; i <= amount; i++)\n            sol[i] = amount + 1;\n        for(int i = 0; i < coins.size(); i++)\n        {\n            for(int j = coins[i]; j <= amount; j++)\n                sol[j] = min(sol[j], sol[j - coins[i]] + 1);\n        }\n        if(sol[amount] != amount + 1)\n            return sol[amount];\n        else\n            return -1;\n    }\n};\n\n\n//Another DP implmentation, same idea above \nclass Solution {\npublic:\n    int coinChange(vector<int>& coins, int amount) {\n        const int MAX = amount +1;\n        vector<int> dp(amount+1, MAX);\n        dp[0]=0;\n        \n        for(int i=1; i<=amount; i++) {\n            for (int j=0; j<coins.size(); j++){\n                if (i >= coins[j]) {\n                    dp[i] = min( dp[i], dp[i-coins[j]] + 1 );\n                }\n            }\n        }\n\n        return dp[amount]==MAX ? -1 : dp[amount];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/combinationSum/combinationSum.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/combination-sum-ii/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Given a collection of candidate numbers (C) and a target number (T), find all \n* unique combinations in C where the candidate numbers sums to T.\n* \n* Each number in C may only be used once in the combination.\n* \n* Note:\n* \n* > All numbers (including target) will be positive integers.\n* > Elements in a combination (a1, a2, … , ak) must be in non-descending order. \n*   (ie, a1 ≤ a2 ≤ … ≤ ak).\n* > The solution set must not contain duplicate combinations.\n* \n* For example, given candidate set 10,1,2,7,6,1,5 and target 8, \n* A solution set is: \n* [1, 7] \n* [1, 2, 5] \n* [2, 6] \n* [1, 1, 6] \n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\nvoid combinationSumHelper(vector<int> &candidates, int start, int target, vector<int> &solution, vector< vector<int> > &result) {\n    if (target<0){\n        return;\n    }\n    if (target==0){\n        result.push_back(solution);\n        return;\n    }\n    for(int i=start; i<candidates.size(); i++){\n        //skip duplicates\n        int n = candidates[i];\n        if (i>start && candidates[i] == candidates[i-1]) {\n            continue;\n        }\n        solution.push_back(n);\n        combinationSumHelper(candidates, i+1, target - n, solution, result);\n        solution.pop_back();\n    }\n}\n\nvector<vector<int> > combinationSum2(vector<int> &candidates, int target) {\n    vector< vector<int> > result;\n    if (candidates.size()<=0){\n        return result;\n    }\n    sort(candidates.begin(), candidates.end());\n    \n    vector<int> solution;\n    combinationSumHelper(candidates, 0, target, solution, result);\n\n    return result;\n}\n\nvoid printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        cout << \"[\";\n        for(int j=0; j<vv[i].size(); j++) {\n            cout << \" \" << vv[i][j];\n        }\n        cout << \"]\" << endl;;\n    }\n}\n\nvoid printArray(vector<int> &v)\n{\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \"}\" << endl;\n}\n\nvoid test(int a[], int len, int target)\n{\n    vector<int> v(a, a+len);\n    cout << \"array  = \";\n    printArray(v);\n    cout << \"target = \" << target << endl;\n\n    vector< vector<int> > vv = combinationSum2(v, target);\n    printMatrix(vv);\n}\n\nint main(int argc, char** argv)\n{\n    #define TEST(a, t) test(a, sizeof(a)/sizeof(int), target)\n    int a[] = {4,2,3,3,5,7};\n    int target = 7;\n    TEST(a, target);\n\n    int b[] = {10,1,2,7,6,1,5};\n    target = 8;\n    TEST(b, target);\n\n    int c[] = {2,2,2};\n    target = 2;\n    TEST(c, target);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/combinationSum/combinationSum.III.cpp",
    "content": "// Source : https://leetcode.com/problems/combination-sum-iii/\n// Author : Hao Chen\n// Date   : 2015-06-11\n\n/********************************************************************************** \n * \n * Find all possible combinations of k numbers that add up to a number n, \n * given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.\n * Ensure that numbers within the set are sorted in ascending order.\n * \n *  Example 1:\n * Input:  k = 3,  n = 7\n * Output: \n * \n * [[1,2,4]]\n * \n *  Example 2:\n * Input:  k = 3,  n = 9\n * Output: \n * \n * [[1,2,6], [1,3,5], [2,3,4]]\n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid combinationSumHelper(vector<int>& candidates, int start, int num, int target, \n                          vector<int>& solution, vector< vector<int> >& results) {\n    if (target < 0|| solution.size() > num){\n        return;\n    }\n    if (target == 0 && solution.size()==num){\n        results.push_back(solution);\n        return;\n    }\n    for (int i=start; i<candidates.size(); i++){\n        solution.push_back(candidates[i]);\n        combinationSumHelper(candidates, i+1, num, target-candidates[i], solution, results);\n        solution.pop_back();\n    }\n    \n}\n\nvector< vector<int> > combinationSum3(int k, int n) {\n    vector<int> v;\n    for (int i=1; i<=9; i++){\n        v.push_back(i);\n    }\n\n    vector< vector<int> > result;\n    vector<int> solution;\n\n    combinationSumHelper(v, 0, k, n, solution, result);    \n\n    return result;\n\n}\n\nvoid PrintResults(int k, int n, vector< vector<int> >& results) {\n    cout << \"k=\" << k << \", n=\" << n << \"\\t\";\n    for (int i=0; i<results.size(); i++){\n        cout << \"[\";\n        for (int j=0; j<results[i].size(); j++){\n            cout << results[i][j] << (j!=results[i].size()-1 ? \",\":\"]\") ;\n        }\n        cout << ( i!=results.size()-1 ? \", \" : \"\" );\n    } \n    cout << endl;\n}\n\nint main(int argc, char** argv) \n{\n    int k = 3, n =9;\n    if (argc > 2){\n        k = atoi(argv[1]);\n        n = atoi(argv[2]);\n    } \n\n    vector< vector<int> > results;\n    results = combinationSum3(k, n);\n\n    PrintResults(k,n, results);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/combinationSum/combinationSum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/combination-sum/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Given a set of candidate numbers (C) and a target number (T), find all unique combinations \n* in C where the candidate numbers sums to T. \n* \n* The same repeated number may be chosen from C unlimited number of times.\n* \n* Note:\n* \n* All numbers (including target) will be positive integers.\n* Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).\n* The solution set must not contain duplicate combinations.\n* \n* For example, given candidate set 2,3,6,7 and target 7, \n* A solution set is: \n* [7] \n* [2, 2, 3] \n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\nvoid combinationSumHelper(vector<int> &candidates, int start, int target, vector<int> &solution, vector< vector<int> > &result) {\n    if (target<0){\n        return;\n    }\n    if (target==0){\n        result.push_back(solution);\n        return;\n    }\n    for(int i=start; i<candidates.size(); i++){\n        //skip duplicates\n        if (i>start && candidates[i] == candidates[i-1]) {\n            continue;\n        }\n        solution.push_back(candidates[i]);\n        combinationSumHelper(candidates, i, target - candidates[i], solution, result);\n        solution.pop_back();\n    }\n}\n\nvector<vector<int> > combinationSum(vector<int> &candidates, int target) {\n    vector< vector<int> > result;\n    if (candidates.size()<=0){\n        return result;\n    }\n    sort(candidates.begin(), candidates.end());\n    \n    vector<int> solution;\n    combinationSumHelper(candidates, 0, target, solution, result);\n\n    return result;\n}\n\nvoid printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        cout << \"[\";\n        for(int j=0; j<vv[i].size(); j++) {\n            cout << \" \" << vv[i][j];\n        }\n        cout << \"]\" << endl;;\n    }\n}\n\nvoid printArray(vector<int> &v)\n{\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \"}\" << endl;\n}\n\n\nint main(int argc, char** argv)\n{\n    int a[] = {4,2,3,3,5,7};\n    vector<int> v(a, a+sizeof(a)/sizeof(int));\n    int target = 7;\n    cout << \"array  = \";\n    printArray(v);\n    cout << \"target = \" << target << endl;\n    \n    vector< vector<int> > vv = combinationSum(v, target);\n    printMatrix(vv);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/combinationSumIV/combinationSumIV.cpp",
    "content": "// Source : https://leetcode.com/problems/combination-sum-iv/\n// Author : Calinescu Valentin\n// Date   : 2016-08-07\n\n/*************************************************************************************** \n *\n * Given an integer array with all positive numbers and no duplicates, find the number\n * of possible combinations that add up to a positive integer target.\n * \n * Example:\n * \n * nums = [1, 2, 3]\n * target = 4\n * \n * The possible combination ways are:\n * (1, 1, 1, 1)\n * (1, 1, 2)\n * (1, 2, 1)\n * (1, 3)\n * (2, 1, 1)\n * (2, 2)\n * (3, 1)\n * \n * Note that different sequences are counted as different combinations.\n * \n * Therefore the output is 7.\n * Follow up:\n * What if negative numbers are allowed in the given array?\n * How does it change the problem?\n * What limitation we need to add to the question to allow negative numbers?\n * \n ***************************************************************************************/\n \n /* Solution\n  * --------\n  * 1) Dynamic Programming - O(N *  target)\n  *\n  * We notice that any sum S can be written as S_prev + nums[i], where S_prev is a sum of\n  * elements from nums and nums[i] is one element of the array. S_prev is always smaller \n  * than S so we can create the array sol, where sol[i] is the number of ways one can \n  * arrange the elements of the array to obtain sum i, and populate it from 1 to target,\n  * as the solution for i is made up of previously computed ones for numbers smaller than\n  * i. The final answer is sol[target], which is returned at the end.\n  *\n  * Follow up:\n  * \n  * If the array contains negative numbers as well as positive ones we can run into a cycle\n  * where some subset of the elements have sum 0 so they can always be added to an existing\n  * sum, leading to an infinite number of solutions. The limitation that we need is a rule\n  * to be followed by the input data, that which doesn't allow this type of subsets to exist.\n  */\nclass Solution {\npublic:\n    int combinationSum4(vector<int>& nums, int target) {\n        int sol[target + 1];\n        sol[0] = 1;//starting point, only 1 way to obtain 0, that is to have 0 elements\n        for(int i = 1; i <= target; i++)\n        {\n            sol[i] = 0;\n            for(int j = 0; j < nums.size(); j++)\n            {\n                if(i >= nums[j])//if there is a previously calculated sum to add nums[j] to\n                    sol[i] += sol[i - nums[j]];\n            }\n        }\n        return sol[target];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/combinations/combinations.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/combinations/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.\n* \n* For example,\n* If n = 4 and k = 2, a solution is:\n* \n* [\n*   [2,4],\n*   [3,4],\n*   [2,3],\n*   [1,2],\n*   [1,3],\n*   [1,4],\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvoid getCombination(int n, int k, vector<int>& solution, vector< vector<int> >& result );\nvector<vector<int> > combine1(int n, int k); \nvector<vector<int> > combine2(int n, int k);\n\nvector<vector<int> > combine(int n, int k) {\n    if (random()%2){\n        cout << \"recusive method!\" << endl;\n        return combine1(n, k);\n    }\n    cout << \"non-recusive method!\" << endl;\n    return combine2(n, k);\n}\n\nvector<vector<int> > combine1(int n, int k) {\n    vector<vector<int> > result;\n    vector<int> solution;\n    getCombination(n, k, solution, result);\n    return result;\n}\n\nvoid getCombination(int n, int k, vector<int>& solution, vector< vector<int> >& result ){\n    if (k==0){\n        //sort to meet LeetCode requirement\n        vector<int> v = solution;\n        sort(v.begin(), v.end());\n        result.push_back(v);\n        return;\n    }\n    for(int i=n; i>0; i--){\n        solution.push_back(i);\n        getCombination(i-1, k-1, solution, result);\n        solution.pop_back();\n    }\n}\n\nvector<vector<int> > combine2(int n, int k) {\n    \n    vector<vector<int> > result;\n    vector<int> d;\n    for (int i=0; i<n; i++){\n        d.push_back( (i<k) ? 1 : 0 );\n    }\n\n    //1) from the left, find the [1,0] pattern, change it to [0,1]\n    //2) move all of the 1 before the pattern to the most left side\n    //3) check all of 1 move to the right\n    while(1){\n        vector<int> v;\n        for(int x=0; x<n; x++){\n            if (d[x]) v.push_back(x+1);\n        }\n        result.push_back(v);\n        //step 1), find [1,0] pattern\n        int i;\n        bool found = false;\n        int ones =0;\n        for(i=0; i<n-1; i++){\n            \n            if (d[i]==1 && d[i+1]==0){\n                d[i]=0; d[i+1]=1;\n                found = true;\n                //step 2) move all of right 1 to the most left side\n                for (int j=0; j<i; j++){\n                    d[j]=( ones > 0 ) ? 1 : 0;\n                    ones--;\n                }\n                break; \n            } \n            if (d[i]==1) ones++;\n        }\n        if (!found){\n            break;\n        }\n        \n    }\n    return result;\n    \n}\n\n\n\n\nvoid printResult(vector<vector<int> >& result)\n{\n    for(int i=0; i<result.size(); i++){\n        cout << \"{\";\n        for(int j=0; j<result[i].size(); j++){\n            cout << \" \" << result[i][j];\n        }\n        cout << \" }\" <<endl;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    srand(time(NULL));\n\n    int n = 4, k =2;\n    if (argc>2){\n        n = atoi(argv[1]);\n        k = atoi(argv[2]);\n    }\n    vector<vector<int> > r = combine(n, k);\n    printResult(r);\n}\n"
  },
  {
    "path": "algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp",
    "content": "// Source : https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/\n// Author : Hao Chen\n// Date   : 2019-10-01\n\n/***************************************************************************************************** \n *\n * Let's define a function f(s) over a non-empty string s, which calculates the frequency of the \n * smallest character in s. For example, if s = \"dcce\" then f(s) = 2 because the smallest character is \n * \"c\" and its frequency is 2.\n * \n * Now, given string arrays queries and words, return an integer array answer, where each answer[i] is \n * the number of words such that f(queries[i]) < f(W), where W is a word in words.\n * \n * Example 1:\n * \n * Input: queries = [\"cbd\"], words = [\"zaaaz\"]\n * Output: [1]\n * Explanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").\n * \n * Example 2:\n * \n * Input: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\n * Output: [1,2]\n * Explanation: On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and \n * f(\"aaaa\") are both > f(\"cc\").\n * \n * Constraints:\n * \n * \t1 <= queries.length <= 2000\n * \t1 <= words.length <= 2000\n * \t1 <= queries[i].length, words[i].length <= 10\n * \tqueries[i][j], words[i][j] are English lowercase letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {\n        cout << queries.size() << \" : \" << words.size() << endl;\n        vector<int> freq;\n        for (auto w : words) {\n            freq.push_back(f(w));\n        }\n        sort(freq.begin(), freq.end());\n\n        vector<int> result;\n        for (auto q : queries) {\n            result.push_back(binary_search(freq, f(q)));\n        }\n        return result;\n    }\n\n    int f(string& s) {\n        char ch = 'z' + 1; //stroe the smallest char\n        int cnt = 0;  //stroe the frequency of the smallest char\n        for (auto c : s) {\n            if (c < ch) { //find the smaller char, reset the count\n                cnt  = 1;\n                ch = c;\n            } if (c == ch) {\n                cnt++;\n            }\n        }\n        return cnt;\n    }\n\n    int binary_search(vector<int> &v, int target) {\n        int low=0, high=v.size()-1, mid;\n\n        while (low < high) {\n            mid = low + (high - low) / 2;\n            if ( v[mid] > target) {\n                high = mid -1;\n            } else if (v[mid] <= target) {\n                low = mid + 1;\n            }\n        }\n\n        low = v[low] > target  ? low : low + 1;\n\n        return v.size() - low;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/compareVersionNumbers/compareVersionNumbers.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/compare-version-numbers/\n// Author : Hao Chen\n// Date   : 2014-12-16\n\n/********************************************************************************** \n * \n * Compare two version numbers version1 and version1.\n * If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.\n * \n * You may assume that the version strings are non-empty and contain only digits and the . character.\n * The . character does not represent a decimal point and is used to separate number sequences.\n * For instance, 2.5 is not \"two and a half\" or \"half way to version three\", it is the fifth second-level revision of the second first-level revision.\n * \n * Here is an example of version numbers ordering:\n * 0.1 < 1.1 < 1.2 < 13.37\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\nclass Solution {\n    public:\n        vector<int> &split(const string &s, char delim, vector<int> &elems) {\n            stringstream ss(s);\n            string item;\n            while (getline(ss, item, delim)) {\n                elems.push_back(atoi(item.c_str()));\n            }\n            return elems;\n        }\n\n\n        vector<int> split(const string &s, char delim) {\n            vector<int> elems;\n            split(s, delim, elems);\n            return elems;\n        }\n\n        void rightTrimZero(vector<int> &v){\n            while (v.back() == 0){\n                v.pop_back();\n            }\n        }\n\n        int compareVersion(string version1, string version2) {\n\n            //split the version by delimer '.'\n            vector<int> ver1 = split(version1, '.');\n            vector<int> ver2 = split(version2, '.');\n\n            //remove the right Zeros\n            rightTrimZero(ver1);\n            rightTrimZero(ver2);\n\n            //compare two versions \n            for (int i=0; i<ver1.size() && i < ver2.size(); i++) {\n                if (ver1[i] < ver2[i]){\n                    return -1;\n                }else if(ver1[i] > ver2[i]){\n                    return 1;\n                }\n            }\n\n            //if the above for-loop is not returned, which means they are equal so far\n            //then check the length.\n            if (ver1.size() > ver2.size()) {\n                return 1;\n            }else if (ver1.size() < ver2.size()) {\n                return -1;\n            }\n\n            return 0;\n\n        }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/constructBinaryTreeFromInorderAndPostorderTraversal/constructBinaryTreeFromInorderAndPostorderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-10\n\n/********************************************************************************** \n* \n* Given inorder and postorder traversal of a tree, construct the binary tree.\n* \n* Note:\n* You may assume that duplicates do not exist in the tree.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nTreeNode *buildTree(vector<int> &inorder, int in_offset, vector<int> &postorder, int post_offset, int n );\n\nTreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {\n    return buildTree(inorder, 0, postorder, 0, postorder.size());\n}\n\n// n - how many number,  offset - start from where?\nTreeNode *buildTree(vector<int> &inorder, int in_offset, vector<int> &postorder, int post_offset, int n ) {\n\n    if ( n<=0 || postorder.size()<=0 || inorder.size()<=0 ) return NULL;\n\n    TreeNode *root = new TreeNode(postorder[post_offset+n-1]);\n    if ( n==1 ){\n        return root;\n    }\n\n    //searching in inorder -- can be optimized by using <map>\n    int i;\n    for(i=in_offset; i<in_offset+n; i++){\n        if (inorder[i] == postorder[post_offset+n-1]){\n            break;\n        }\n    }\n\n    //error: not found\n    if (i == inorder.size()) return NULL;\n\n    int left_n = i - in_offset;\n    int right_n = in_offset + n - i - 1;\n    root->left = buildTree(inorder, in_offset, postorder, post_offset, left_n );\n    root->right = buildTree(inorder, i+1, postorder, post_offset+left_n, right_n);\n\n    return root;\n}\n\n//cause the problem: memory limited error\nTreeNode *buildTree2(vector<int> &inorder, vector<int> &postorder) {\n    \n    if (postorder.size()<=0 || inorder.size()<=0 ) return NULL;\n\n    int post_n = postorder.size();\n    TreeNode *root = new TreeNode(postorder[post_n-1]);\n    if ( inorder.size()==1 && postorder.size()==1 ){\n        return root;\n    }\n\n    //searching in inorder -- can be optimized by using <map>\n    int i;\n    for(i=0; i<inorder.size(); i++){\n        if (inorder[i] == postorder[post_n-1]){\n            break;\n        }\n    }\n\n    //error: not found\n    if (i == inorder.size()) return NULL;\n\n    \n    vector<int>   in(inorder.begin(), inorder.begin()+i);\n    vector<int> post(postorder.begin(), postorder.begin()+i);\n    if (in.size()>0) {\n        root->left = buildTree(in, post);\n    }\n\n    in.clear();\n    in.assign(inorder.begin()+i+1, inorder.end());\n    post.clear();\n    post.assign(postorder.begin()+i, postorder.end()-1);\n    if (in.size()>0) {\n        root->right = buildTree(in, post);\n    }\n\n    return root;\n}\n\nvoid printTree_pre_order(TreeNode *root)\n{\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n    printf(\"%c \", root->val );\n\n    printTree_pre_order(root->left);\n    printTree_pre_order(root->right);\n}\n\nvoid printTree_in_order(TreeNode *root)\n{\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n\n    printTree_in_order(root->left);\n    printf(\"%c \", root->val );\n    printTree_in_order(root->right);\n}\n\n\nvoid printTree_level_order(TreeNode *root)\n{\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0){\n        TreeNode* n = q.front();\n        q.pop();\n        if (n==NULL){\n            printf(\"# \");\n            continue;\n        }\n        printf(\"%c \", n->val);\n        q.push(n->left);\n        q.push(n->right);\n    }\n    printf(\"\\n\");\n}\n\n\nint main()\n{\n    int   in_order[]={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};\n    int post_order[]={'A', 'C', 'E', 'D', 'B', 'H', 'I', 'G', 'F'};\n    vector<int>   inorder(  in_order,  in_order + 9 );\n    vector<int> postorder( post_order, post_order + 9 );\n\n    TreeNode* tree = buildTree(inorder, postorder);\n\n    printTree_level_order(tree);\n    printTree_pre_order(tree);\n    printf(\"\\n\");\n    printTree_in_order(tree);\n    printf(\"\\n\");\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/constructBinaryTreeFromPreorderAndInorderTraversal/constructBinaryTreeFromPreorderAndInorderTraversal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/\n// Author : Hao Chen\n// Date   : 2014-07-09\n\n/********************************************************************************** \n* \n* Given preorder and inorder traversal of a tree, construct the binary tree.\n* \n* Note:\n* You may assume that duplicates do not exist in the tree.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nTreeNode *buildTree(vector<int>& preorder, int& preidx, vector<int>& inorder);\n\nTreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {\n    int preidx=0;\n    return buildTree(preorder, preidx, inorder);\n}\n\nTreeNode *buildTree(vector<int>& preorder, int& preidx, vector<int>& inorder) {\n\n    if (preorder.size()<=0 || inorder.size()<=0 ) return NULL;\n\n    TreeNode *root = new TreeNode(preorder[preidx]);\n    if (inorder.size()==1){\n        return root;\n    }\n\n    int i;\n    for(i=0; i<inorder.size(); i++){\n        if (inorder[i] == preorder[preidx]){\n            break;\n        }\n    }\n\n    //error: not found\n    if (i == inorder.size()) return NULL;\n\n    if (preidx+1 >= preorder.size()){\n        return root;\n    }\n\n    \n    vector<int> v(inorder.begin(), inorder.begin()+i);\n    if (v.size()>0) {\n        preidx++;\n        root->left = buildTree(preorder, preidx, v);\n    }\n\n    v.clear();\n    v.assign(inorder.begin()+i+1, inorder.end());\n    if (v.size()>0) {\n        preidx++;\n        root->right = buildTree(preorder, preidx, v);\n    }\n\n    return root;\n}\n\nvoid printTree_pre_order(TreeNode *root)\n{\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n    printf(\"%c \", root->val );\n\n    printTree_pre_order(root->left);\n    printTree_pre_order(root->right);\n}\n\nvoid printTree_in_order(TreeNode *root)\n{\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n\n    printTree_in_order(root->left);\n    printf(\"%c \", root->val );\n    printTree_in_order(root->right);\n}\n\n\nvoid printTree_level_order(TreeNode *root)\n{\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0){\n        TreeNode* n = q.front();\n        q.pop();\n        if (n==NULL){\n            printf(\"# \");\n            continue;\n        }\n        printf(\"%c \", n->val);\n        q.push(n->left);\n        q.push(n->right);\n    }\n    printf(\"\\n\");\n}\n\n\nint main()\n{\n    int pre_order[]={'F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H'};\n    int  in_order[]={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};\n    vector<int> preorder( pre_order, pre_order + 9 );\n    vector<int>  inorder(  in_order,  in_order + 9 );\n\n    TreeNode* tree = buildTree(preorder, inorder);\n\n    printTree_level_order(tree);\n    printTree_pre_order(tree);\n    printf(\"\\n\");\n    printTree_in_order(tree);\n    printf(\"\\n\");\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/constructTheLexicographicallyLargestValidSequence/ConstructTheLexicographicallyLargestValidSequence.cpp",
    "content": "// Source : https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/\n// Author : Hao Chen\n// Date   : 2021-04-24\n\n/***************************************************************************************************** \n *\n * Given an integer n, find a sequence that satisfies all of the following:\n * \n * \tThe integer 1 occurs once in the sequence.\n * \tEach integer between 2 and n occurs twice in the sequence.\n * \tFor every integer i between 2 and n, the distance between the two occurrences of i is \n * exactly i.\n * \n * The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of \n * their indices, |j - i|.\n * \n * Return the lexicographically largest sequence. It is guaranteed that under the given constraints, \n * there is always a solution. \n * \n * A sequence a is lexicographically larger than a sequence b (of the same length) if in the first \n * position where a and b differ, sequence a has a number greater than the corresponding number in b. \n * For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they \n * differ is at the third number, and 9 is greater than 5.\n * \n * Example 1:\n * \n * Input: n = 3\n * Output: [3,1,2,3,2]\n * Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest \n * valid sequence.\n * \n * Example 2:\n * \n * Input: n = 5\n * Output: [5,3,1,4,3,5,2,4,2]\n * \n * Constraints:\n * \n * \t1 <= n <= 20\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    void print(vector<int>& v) {\n        cout << \"[\" ;\n        for(int i=0; i<v.size()-1; i++){\n            cout << v[i] << \",\";\n        }\n        cout << v[v.size()-1] << \"]\" << endl;\n    }\npublic:\n    vector<int> constructDistancedSequence(int n) {\n        vector<int> result(2*n-1, 0);\n        vector<bool> available(n+1, true); // an array remember which num hasn't been chosen.\n        available[0] = false;\n        \n        dfs(available, result, 0, n);\n        \n        return result;\n    }\n    \n    bool dfs(vector<bool>& available, vector<int>& result, int pos, int cnt){\n        //the `cnt` means how many number has been processed.\n        if (cnt == 0) return true;\n        \n        //start from the bigger number.\n        int n = 0;\n        for(int i = available.size()-1; i > 0; i--){\n            // if the number has already been chosen, skip to next one.\n            if (!available[i]) continue;\n            //if the number cannot be put into the array, skip to next one\n            if ( i > 1 && pos + i >= result.size()) continue;\n            if ( i > 1 && (result[pos] != 0 || result[pos+i] != 0)) continue;\n            \n            // choose the current number `i`\n            available[i] = false;\n            result[pos] = i;\n            if (i > 1) result[pos+i] = i;\n            int next_pos = pos;\n            while( next_pos < result.size() && result[next_pos]!=0) next_pos++;\n            \n            //print(result);\n            if (dfs(available, result, next_pos, cnt-1)) return true; \n            \n            // if failed to find the answer. roll back.\n            available[i] = true;\n            result[pos] = 0;\n            if (i > 1) result[pos+i] = 0;\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/container-with-most-water/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). \n* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). \n* \n* Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n* \n* Note: You may not slant the container.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    int maxArea(vector<int> &height) {\n\n        int maxArea = 0;\n        // two pointers scan from two sides to middle\n        int left = 0; \n        int right = height.size()-1;\n\n        int area; \n        while ( left < right ){\n            // calculate the area\n            area = (right - left) * ( height[left] < height[right] ? height[left] : height[right]);\n            // tracking the maxium area\n            maxArea = area > maxArea ? area : maxArea;\n            // because the area is decided by the shorter edge\n            // so we increase the area is to increase the shorter edge\n            //\n            //     height[left] < height[right] ? left++ : right-- ;\n            //\n            // However, the above code could cause the unnecessary `area` cacluation\n            // We can do some improvement as below:\n            if (height[left] < height[right]) {\n                do {\n                    left++;\n                } while (left < right && height[left-1] >= height[left]);\n            } else {\n                do {\n                    right--;\n                } while (right > left && height[right+1] >= height[right]);\n            }\n        }\n        \n        return maxArea;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/containsDuplicate/ContainsDuplicate.II.cpp",
    "content": "// Source : https://leetcode.com/problems/contains-duplicate-ii/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Given an array of integers and an integer k, find out whether there there are \n * two distinct indices i and j in the array such that nums[i] = nums[j] and \n * the difference between i and j is at most k.\n * \n *               \n **********************************************************************************/\n\nclass Solution {\npublic:\n    bool containsNearbyDuplicate(vector<int>& nums, int k) {\n        unordered_map<int, int> m;\n        for (int i=0; i<nums.size(); i++) {\n            int n = nums[i];\n            if (m.find(n) != m.end() && i - m[n] <= k) {\n                return true;\n            }\n            m[n] = i;\n        }\n        return false;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/containsDuplicate/ContainsDuplicate.III.cpp",
    "content": "// Source : https://leetcode.com/problems/contains-duplicate-iii/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Given an array of integers, find out whether there are two distinct indices i and j \n * in the array such that the difference between nums[i] and nums[j] is at most t and \n * the difference between i and j is at most k.\n *               \n **********************************************************************************/\n\n\n\nclass Solution {\npublic:\n    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {\n        if(nums.size() < 2 || k == 0) return false;\n        int low = 0;\n        //maintain a sliding window \n        set<long long> window;\n        for (int i=0; i<nums.size(); i++){\n            //make sure window size <= k\n            if (i - low > k) {\n                window.erase(nums[low]);\n                low++;\n            }\n            \n            // lower_bound() is the key, \n            // it returns an iterator pointing to the first element >= val \n            auto it = window.lower_bound((long long)nums[i] - (long long)t );\n            if (it != window.end() && abs((long long)nums[i] - *it) <= (long long)t) {\n                return true;\n            }\n            window.insert(nums[i]);\n        }\n        return false;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/containsDuplicate/ContainsDuplicate.cpp",
    "content": "// Source : https://leetcode.com/problems/contains-duplicate/\n// Author : Hao Chen\n// Date   : 2015-06-11\n\n/********************************************************************************** \n * \n * Given an array of integers, find if the array contains any duplicates. \n * Your function should return true if any value appears at least twice in the array, \n * and it should return false if every element is distinct.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    bool containsDuplicate(vector<int>& nums) {\n        unordered_map<int, bool> m;\n        for (auto item : nums) {\n            if (m.find(item) != m.end()) return true;\n            m[item]=true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp",
    "content": "// Source : https://leetcode.com/problems/convert-a-number-to-hexadecimal/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * Given an integer, write an algorithm to convert it to hexadecimal. For negative \n * integer, two’s complement method is used.\n * \n * Note:\n * \n * All letters in hexadecimal (a-f) must be in lowercase.\n * The hexadecimal string must not contain extra leading 0s. If the number is zero, it \n * is represented by a single zero character '0'; otherwise, the first character in the \n * hexadecimal string will not be the zero character.\n * The given number is guaranteed to fit within the range of a 32-bit signed integer.\n * You must not use any method provided by the library which converts/formats the \n * number to hex directly.\n * \n * Example 1:\n * \n * Input:\n * 26\n * \n * Output:\n * \"1a\"\n * \n * Example 2:\n * \n * Input:\n * -1\n * \n * Output:\n * \"ffffffff\"\n ***************************************************************************************/\n\nclass Solution {\npublic:\n\n    string toHex(int num) {\n        \n        if (num == 0) return \"0\";\n        \n        unsigned int x = num;\n\n        string result;\n        for(;x > 0; x/=16) {\n            int n = x % 16;\n            char c;\n            if (n < 10) c = n + '0';\n            else c = 'a' + n - 10 ;\n            result = c + result;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/\n// Author : Hao Chen\n// Date   : 2014-06-23\n\n/********************************************************************************** \n* \n* Given an array where elements are sorted in ascending order, convert it to a height balanced BST.\n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode *sortedArrayToBST(vector<int> &num) {\n        if(num.size()==0){\n            return NULL;\n        }\n        if(num.size()==1){\n            return new TreeNode(num[0]);\n        }\n        int mid = num.size()/2;\n        \n        TreeNode *node = new TreeNode(num[mid]);\n        \n        vector<int>::const_iterator first;\n        vector<int>::const_iterator last;\n\n        first = num.begin();\n        last = num.begin()+mid;\n        vector<int> v(first, last);\n        node->left = sortedArrayToBST(v);\n        \n        if (mid==num.size()-1){\n            node->right = NULL;\n        }else{\n            first = num.begin()+mid+1;\n            last = num.end();\n            vector<int> v(first, last);\n            node->right = sortedArrayToBST(v);\n        }\n        return node;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/convertSortedListToBinarySearchTree/convertSortedListToBinarySearchTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a singly linked list where elements are sorted in ascending order, \n* convert it to a height balanced BST.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <queue>\nusing namespace std;\n\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\n\nTreeNode* sortedListToBST(int low, int high, ListNode*& head);\n\nTreeNode *sortedListToBST(ListNode *head) {\n    int len = 0;\n    \n    for(ListNode* p=head; p!=NULL; p=p->next){\n        len++;\n    }\n    return sortedListToBST(0, len-1, head);\n}\n\nTreeNode* sortedListToBST(int low, int high, ListNode*& head) {\n    if (low>high || head==NULL) return NULL;\n\n    int mid = low + (high - low)/2;\n\n    TreeNode* leftNode = sortedListToBST(low, mid-1, head);\n\n    TreeNode* node = new TreeNode(head->val);\n    node->left = leftNode;\n    head = head->next;\n\n    TreeNode* rightNode = sortedListToBST(mid+1, high, head);\n    node->right = rightNode;\n\n    return node;\n}\n\nvoid printTree_level_order(TreeNode *root)\n{\n    queue<TreeNode*> q;\n    q.push(root);\n    while (q.size()>0){\n        TreeNode* n = q.front();\n        q.pop();\n        if (n==NULL){\n            cout << \"# \";\n            continue;\n        }\n        cout << n->val << \" \";\n        q.push(n->left);\n        q.push(n->right);\n    }\n    cout << endl;\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d -> \", h->val);\n        h = h->next;\n    }\n    printf(\"NULL\\n\");\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 8;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    int *a = new int[n];\n    for(int i=0; i<n; i++){\n        a[i]=i+1;\n    }\n    ListNode* head = createList(a, n);\n    printList(head);\n    TreeNode* root = sortedListToBST(head); \n    printTree_level_order(root);\n    delete[] a; \n\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/copyListWithRandomPointer/copyListWithRandomPointer.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/copy-list-with-random-pointer/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* A linked list is given such that each node contains an additional random pointer \n* which could point to any node in the list or null.\n* \n* Return a deep copy of the list.\n* \n*               \n**********************************************************************************/\n\n\n\n/**\n * Definition for singly-linked list with a random pointer.\n * struct RandomListNode {\n *     int label;\n *     RandomListNode *next, *random;\n *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}\n * };\n */\n\n\n/*    \n *\n *  The idea as below:\n *\n *  Consider we have a linked list as below:\n *\n *    node1->random = node2;\n *    node2->random = node1;\n *    node3->random = node1;\n *    \n *       +-------------+                         \n *       |             v                         \n *    +-------+    +-------+    +-------+        \n *    | node1 |----> node2 |----> node3 |--->NULL\n *    +-------+    +-------+    +-------+        \n *      ^  ^           |           |             \n *      |  +-----------+           |             \n *      +--------------------------+             \n *    \n *\n *  To copy the list, \n *   \n *    1) We insert a new node for each node's next position\n *\n * \n *       +-------------------------+                                     \n *       |                         v                                     \n *    +--+----+     +-----+    +-------+     +-----+    +-------+     +-----+     \n *    | node1 |---> | NEW |----> node2 |---> | NEW |----> node3 |---> | NEW | ---> NULL\n *    +-------+     +-----+    +---+---+     +-----+    +--+----+     +-----+ \n *      ^  ^                       |                       |             \n *      |  +-----------------------+                       |             \n *      +--------------------------------------------------+             \n *\n *    2) Then, we can construt the new node's random pointer:\n *\n *        (node1->next) -> random  = (node1->random) -> next;\n *\n *    3) After we take out all of the \"NEW\" node to finish the copy.\n *    \n */\n\nclass Solution {\npublic:\n    RandomListNode *copyRandomList(RandomListNode *head) {\n        RandomListNode *p = NULL, *h=NULL, *t=NULL;\n        if (head == NULL){\n            return NULL;\n        }\n        \n        //creat a new node for each node and insert its next\n        p = head;\n        while ( p != NULL){\n            RandomListNode *node = new RandomListNode(p->label);\n            node->next = p->next;\n            p->next = node;\n            p = node->next;\n        }\n        \n        //copy random pointer for each new node\n        p = head;\n        while (p != NULL){\n            if (p->random != NULL){\n                p->next->random = p->random->next;\n            }\n            p = p->next->next;\n        }\n        \n        //break to two list\n        p = head;\n        h = t = head->next;\n        while ( p != NULL ){\n            p->next = p->next->next;\n            if (t->next!=NULL){\n                t->next = t->next->next;\n            }\n            \n            p = p->next;\n            t = t->next;\n        }\n        \n        return h;\n    }\n};\n\n\n/*\n *  Considering we have a link as below:\n *\n *\n *       +-------------+\n *       |             v\n *    +-------+    +-------+    +-------+\n *    | node1 |----> node2 |----> node3 |--->NULL\n *    +-------+    +-------+    +-------+\n *      ^  ^           |           |\n *      |  +-----------+           |\n *      +--------------------------+\n * \n *  1) Using a map to store each node's random pointer's position\n *\n *      map[node1->random] = 1;\n *      map[node2->random] = 0;\n *      map[node3->random] = 0;\n *\n *  2) Clone the linked list (only consider the next pointer)\n *\n *      new1 --> new2 --> new3 --> NULL \n *\n *  3) Using an array to strore the order of the cloned linked-list\n *\n *      v[0] = &new1\n *      v[1] = &new2\n *      v[2] = &new3\n * \n *  4) Then we can clone the random pointers.\n *\n *      new->random = v [ map[node->random] ]\n *\n */ \nclass MySolution {\npublic:\n    RandomListNode *copyRandomList(RandomListNode *head) {\n\n        RandomListNode *p = NULL, *h=NULL, *t=NULL;\n        //using a map to store the random pointer's postion.\n        map<RandomListNode*, int> m;\n        //construct the map\n        int pos =0;\n        for ( p = head; p != NULL; p = p->next, pos++){\n            m[p] = pos;\n        }\n        \n        //clone the linked list  (only consider the next pointer)\n        //and using a vector to store each node's postion.\n        vector<RandomListNode*> v;\n        for (p = head; p != NULL; p = p->next){\n            RandomListNode *node = new RandomListNode(p->label);\n            v.push_back(node);\n            if (h==NULL){\n                h = t = node;\n            }else{\n                t->next = node;\n                t = node;\n            }\n        }\n\n        //p => source link head \n        //t => new link head\n        //move the p and t synchronously, and \n        //     t->random = vector[ map[p->random] ];\n        for (t=h, p = head; t!=NULL && p!= NULL; p=p->next, t=t->next){\n            if (p->random!=NULL) {\n                pos = m[p->random];\n                t->random = v[pos];\n            }\n        }\n        \n        return h;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countAndSay/countAndSay.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/count-and-say/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* The count-and-say sequence is the sequence of integers beginning as follows:\n* 1, 11, 21, 1211, 111221, ...\n* \n* 1 is read off as \"one 1\" or 11.\n* 11 is read off as \"two 1s\" or 21.\n* 21 is read off as \"one 2, then one 1\" or 1211.\n* \n* Given an integer n, generate the nth sequence.\n* \n* Note: The sequence of integers will be represented as a string.\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nstring vecToStr(vector<int> v) {\n    stringstream ss;\n    for (int i=0; i<v.size(); i++) {\n        ss << v[i]; \n    }\n    return ss.str();\n}\n\nvector<int> getNext(vector<int>& v) {\n    int cnt=0;\n    int val=0;\n    vector<int> ret;\n    for(int i=0; i<v.size(); i++){\n        if (i==0){\n            val = v[i];\n            cnt = 1;\n            continue;\n        }\n        if (v[i] == val){\n            cnt++;\n        }else{\n            ret.push_back(cnt); \n            ret.push_back(val); \n            val = v[i];\n            cnt = 1;\n        }\n    }\n    if (cnt>0 && val>0){\n        ret.push_back(cnt); \n        ret.push_back(val); \n    }\n    return ret;\n}\n    \n\nstring countAndSay(int n) {\n    if (n<=0) return \"\";\n    if (n==1) return \"1\";\n\n    string s;\n    vector<int> v;\n    v.push_back(1);\n    for(int i=2; i<=n; i++){\n       v = getNext(v);\n       //s = s + \", \" +vecToStr(v);\n    }\n    s = vecToStr(v);\n    return s;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 4;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    cout << countAndSay(n) << endl;\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/countCompleteTreeNodes/CountCompleteTreeNodes.cpp",
    "content": "// Source : https://leetcode.com/problems/count-complete-tree-nodes/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Given a complete binary tree, count the number of nodes.\n * \n * Definition of a complete binary tree from Wikipedia:\n * http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\n *\n * In a complete binary tree every level, except possibly the last, is completely filled, \n * and all nodes in the last level are as far left as possible. \n * It can have between 1 and 2^h nodes inclusive at the last level h.\n *               \n **********************************************************************************/\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    //return -1 if it is not.\n    int isCompleteTree(TreeNode* root) {\n        if (!root) return 0;\n\n        int cnt = 1;\n        TreeNode *left = root, *right = root;\n        for(; left && right; left=left->left, right=right->right) {\n            cnt *= 2;\n        }\n      \n        if (left!=NULL || right!=NULL) {\n            return -1;\n        }\n        return cnt-1;\n    }\n\n    int countNodes(TreeNode* root) {\n        int cnt = isCompleteTree(root);\n        if (cnt != -1) return cnt;\n        int leftCnt = countNodes(root->left);\n        int rightCnt = countNodes(root->right);\n        return leftCnt + rightCnt + 1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countGoodMeals/CountGoodMeals.cpp",
    "content": "// Source : https://leetcode.com/problems/count-good-meals/\n// Author : Hao Chen\n// Date   : 2021-03-30\n\n/***************************************************************************************************** \n *\n * A good meal is a meal that contains exactly two different food items with a sum of deliciousness \n * equal to a power of two.\n * \n * You can pick any two different foods to make a good meal.\n * \n * Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i^​​​​​​\n * th​​​​​​​​ item of food, return the number of different good meals you can make from this list \n * modulo 10^9 + 7.\n * \n * Note that items with different indices are considered different even if they have the same \n * deliciousness value.\n * \n * Example 1:\n * \n * Input: deliciousness = [1,3,5,7,9]\n * Output: 4\n * Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\n * Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.\n * \n * Example 2:\n * \n * Input: deliciousness = [1,1,1,3,3,3,7]\n * Output: 15\n * Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n * \n * Constraints:\n * \n * \t1 <= deliciousness.length <= 10^5\n * \t0 <= deliciousness[i] <= 2^20\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countPairs(vector<int>& deliciousness) {\n        const int MAX_EXP = 22;\n        int pow2[MAX_EXP];\n        for (int i=0; i<MAX_EXP; i++){\n            pow2[i] = 1 << i;\n            //cout << pow2[i] << \", \";\n        }\n        \n        unordered_map<int, int> stat;\n        int big = 0;\n        for(auto& d: deliciousness){\n            stat[d]++;\n\n        }\n\n        long m = 0;\n        for(auto& d: deliciousness){\n            for(int i=MAX_EXP-1; i>=0 && pow2[i] >= d; i--){\n                int x = pow2[i] - d;\n                if ( stat.find(x) != stat.end() ){\n                    m += (x==d) ? stat[x]-1 : stat[x];\n                }\n            }\n        }\n        \n        // remove the duplication - m/2, \n        // because both [1,3] and [3,1] are counted.\n        return (m/2) % 1000000007;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countItemsMatchingARule/CountItemsMatchingARule.cpp",
    "content": "// Source : https://leetcode.com/problems/count-items-matching-a-rule/\n// Author : Hao Chen\n// Date   : 2021-03-14\n\n/***************************************************************************************************** \n *\n * You are given an array items, where each items[i] = [typei, colori, namei] describes the type, \n * color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and \n * ruleValue.\n * \n * The ith item is said to match the rule if one of the following is true:\n * \n * \truleKey == \"type\" and ruleValue == typei.\n * \truleKey == \"color\" and ruleValue == colori.\n * \truleKey == \"name\" and ruleValue == namei.\n * \n * Return the number of items that match the given rule.\n * \n * Example 1:\n * \n * Input: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], \n * ruleKey = \"color\", ruleValue = \"silver\"\n * Output: 1\n * Explanation: There is only one item matching the given rule, which is \n * [\"computer\",\"silver\",\"lenovo\"].\n * \n * Example 2:\n * \n * Input: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], \n * ruleKey = \"type\", ruleValue = \"phone\"\n * Output: 2\n * Explanation: There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] \n * and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.\n * \n * Constraints:\n * \n * \t1 <= items.length <= 104\n * \t1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10\n * \truleKey is equal to either \"type\", \"color\", or \"name\".\n * \tAll strings consist only of lowercase letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {\n        int idx;\n        switch(ruleKey[0]) {\n            case 't': idx = 0; break;\n            case 'c': idx = 1; break;\n            case 'n': idx = 2; break;\n            default: return 0;\n        }\n        \n        int cnt = 0;\n        for (auto& item : items) {\n            if (item[idx] == ruleValue) cnt++;\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countNicePairsInAnArray/CountNicePairsInAnArray.cpp",
    "content": "// Source : https://leetcode.com/problems/count-nice-pairs-in-an-array/\n// Author : Hao Chen\n// Date   : 2021-04-06\n\n/***************************************************************************************************** \n *\n * You are given an array nums that consists of non-negative integers. Let us define rev(x) as the \n * reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of \n * indices (i, j) is nice if it satisfies all of the following conditions:\n * \n * \t0 <= i < j < nums.length\n * \tnums[i] + rev(nums[j]) == nums[j] + rev(nums[i])\n * \n * Return the number of nice pairs of indices. Since that number can be too large, return it modulo \n * 10^9 + 7.\n * \n * Example 1:\n * \n * Input: nums = [42,11,1,97]\n * Output: 2\n * Explanation: The two pairs are:\n *  - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n *  - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.\n * \n * Example 2:\n * \n * Input: nums = [13,10,35,24,76]\n * Output: 4\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t0 <= nums[i] <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int rev(int n) {\n        int x = 0;\n        while(n > 0) {\n            x = x*10 + (n % 10);\n            n /= 10;\n        }\n        return x;\n    }\n\npublic:\n    int countNicePairs(vector<int>& nums) {\n        return countNicePairs02(nums);\n        return countNicePairs01(nums);\n    }\n    int countNicePairs01(vector<int>& nums) {\n        // suppose n' = rev(n) \n        // define:  a + b' == b + a'\n        //   then:  a - a' == b - b'\n        \n        unordered_map<int, int> stat;\n        for(auto& n : nums) {\n            stat[n-rev(n)]++;\n            \n        }\n        \n        //if there are n elements  has same value, \n        // then there are  n*(n-1)/2 unique pairs.\n        int result = 0;\n        for(auto& [n, cnt] : stat) {\n            result  =  (result + cnt * (cnt -1l) / 2)  % 1000000007;\n        }\n        return result;\n    }\n    \n    int countNicePairs02(vector<int>& nums) {\n        // suppose n' = rev(n) \n        // define:  a + b' == b + a'\n        //   then:  a - a' == b - b'\n        int result = 0;\n        unordered_map<int, int> stat;\n        for(auto& n : nums) {\n            int delta = n-rev(n);\n            stat[delta]++;\n            result = (result + (stat[delta] - 1l)) % 1000000007 ;\n        }\n        \n        return result ;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countNumberOfHomogenousSubstrings/CountNumberOfHomogenousSubstrings.cpp",
    "content": "// Source : https://leetcode.com/problems/count-number-of-homogenous-substrings/\n// Author : Hao Chen\n// Date   : 2021-02-14\n\n/***************************************************************************************************** \n *\n * Given a string s, return the number of homogenous substrings of s. Since the answer may be too \n * large, return it modulo 109 + 7.\n * \n * A string is homogenous if all the characters of the string are the same.\n * \n * A substring is a contiguous sequence of characters within a string.\n * \n * Example 1:\n * \n * Input: s = \"abbcccaa\"\n * Output: 13\n * Explanation: The homogenous substrings are listed as below:\n * \"a\"   appears 3 times.\n * \"aa\"  appears 1 time.\n * \"b\"   appears 2 times.\n * \"bb\"  appears 1 time.\n * \"c\"   appears 3 times.\n * \"cc\"  appears 2 times.\n * \"ccc\" appears 1 time.\n * 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\n * \n * Example 2:\n * \n * Input: s = \"xy\"\n * Output: 2\n * Explanation: The homogenous substrings are \"x\" and \"y\".\n * \n * Example 3:\n * \n * Input: s = \"zzzzz\"\n * Output: 15\n * \n * Constraints:\n * \n * \t1 <= s.length <= 105\n * \ts consists of lowercase letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countHomogenous(string s) {\n        long long result = 0;\n        char current = '\\0';\n        long long len = 0;\n        for(int i = 0; i < s.size() ; i++) {\n            if (current != s[i] ){\n                //sum from 1 to len\n                result += len * (len+1)/2;\n                current = s[i];\n                len = 1;\n            }else{\n                len++;\n            }\n        }\n        //the rest string\n        result += len * (len+1)/2;\n        return result % 1000000007;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countNumbersWithUniqueDigits/CountNumbersWithUniqueDigits.cpp",
    "content": "// Source : https://leetcode.com/problems/count-numbers-with-unique-digits/\n// Author : Hao Chen\n// Date   : 2019-03-24\n\n/***************************************************************************************************** \n *\n * Given a non-negative integer n, count all numbers with unique digits, x, where 0 &le; x < 10n.\n * \n * Example:\n * \n * Input: 2\n * Output: 91 \n * Explanation: The answer should be the total numbers in the range of 0 &le; x < 100, \n *              excluding 11,22,33,44,55,66,77,88,99\n * \n ******************************************************************************************************/\n\n\n// Considering three digits\n//   - the first place could be [1-9] which has 9 choices.\n//   - the second place could be [0-9] with excluding the first digit, which is 10-1=9 choices.\n//   - the third place could be [0-9] with excluding the 1st and 2nd digits, which is 10-2=8 choices.\n// So, three digits has 9*9*8 unique digits.\n//\n// After adds the 1 digit unique number,and 2 digits unique number, we can have the result:\n//\n//   9*9*8 + 9*9 + 10 = 648 + 81 + 10 = 739\n//\n// n = 0, a[0] = 1;\n// n = 1, a[1] = 9 + a[0];\n// n = 2, a[2] = 9*9 + a[1];\n// n = 3, a[3] = 9*9*8 + a[2];\n// n = 4, a[4] = 9*9*8*7 + a[3];\n// ....\nclass Solution {\npublic:\n    int countNumbersWithUniqueDigits(int n) {\n        int result = 1;\n        for (int i=0; i<n; i++) {\n            result += ( 9 * nine_factor(i) );\n        }\n        return result;\n    }\n\n    int nine_factor(int n) {\n        int result = 1;\n        for (int i=0; i<n; i++) {\n            result *= (9-i);\n        }\n        return result;\n    }\n};\n\n\n//actually, the function nine_factor() could be optimized!\n\nclass Solution {\npublic:\n    int countNumbersWithUniqueDigits(int n) {\n        int result = 1;\n        int nine_factor = 1;\n        for (int i=0; i<n; i++) {\n            result += ( 9 * nine_factor );\n            nine_factor *= (9-i);\n        }\n        return result;\n    }\n\n\n};\n"
  },
  {
    "path": "algorithms/cpp/countOddNumbersInAnIntervalRange/CountOddNumbersInAnIntervalRange.cpp",
    "content": "// Source : https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/\n// Author : Hao Chen\n// Date   : 2020-10-07\n\n/***************************************************************************************************** \n *\n * Given two non-negative integers low and high. Return the count of odd numbers between low and high \n * (inclusive).\n * \n * Example 1:\n * \n * Input: low = 3, high = 7\n * Output: 3\n * Explanation: The odd numbers between 3 and 7 are [3,5,7].\n * \n * Example 2:\n * \n * Input: low = 8, high = 10\n * Output: 1\n * Explanation: The odd numbers between 8 and 10 are [9].\n * \n * Constraints:\n * \n * \t0 <= low <= high <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countOdds1(int low, int high) {\n        //remove the edge cases, make it as same pattern - both low and high are odd number.\n        if  (high % 2 == 0) high--;\n        if  (low % 2 == 0 ) low++;\n        return (high-low)/2+1;\n    }\n    int countOdds2(int low, int high) {\n        return (high+1)/2 - low/2;\n    }\n    int countOdds(int low, int high) {\n        return countOdds2(low, high);\n        return countOdds1(low, high);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp",
    "content": "// Source : https://leetcode.com/problems/count-of-range-sum/\n// Author : Hao Chen\n// Date   : 2016-01-15\n\n/*************************************************************************************** \n *\n * Given an integer array nums, return the number of range sums that lie in [lower, \n * upper] inclusive.\n * \n *     Range sum S(i, j) is defined as the sum of the elements in nums between indices \n * i and \n *     j (i ≤ j), inclusive.\n * \n *     Note:\n *     A naive algorithm of O(n2) is trivial. You MUST do better than that.\n * \n *     Example:\n *     Given nums = [-2, 5, -1], lower = -2, upper = 2,\n *     Return 3.\n *     The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n\n/*\n *  At first of all, we can do preprocess to calculate the prefix sums \n * \n *      S[i] = S(0, i), then S(i, j) = S[j] - S[i]. \n *  \n *  Note: S(i, j) as the sum of range [i, j) where j exclusive and j > i. \n *\n *  With these prefix sums, it is trivial to see that with O(n^2) time we can find all S(i, j) \n *  in the range [lower, upper]\n *\n *      int countRangeSum(vector<int>& nums, int lower, int upper) {\n *        int n = nums.size();\n *        long[] sums = new long[n + 1];\n *        for (int i = 0; i < n; ++i) {\n *            sums[i + 1] = sums[i] + nums[i];\n *        }\n *        int ans = 0;\n *        for (int i = 0; i < n; ++i) {\n *            for (int j = i + 1; j <= n; ++j) {\n *                if (sums[j] - sums[i] >= lower && sums[j] - sums[i] <= upper) {\n *                    ans++;\n *                }\n *            }\n *        }\n *        delete []sums;\n *        return ans;\n *      }\n * \n *  The above solution would get time limit error.\n *\n *  Recall `count smaller number after self` where we encountered the problem\n *\n *      count[i] = count of nums[j] - nums[i] < 0 with j > i\n *\n *  Here, after we did the preprocess, we need to solve the problem\n *\n *      count[i] = count of a <= S[j] - S[i] <= b with j > i   \n *\n *  In other words, if we maintain the prefix sums sorted, and then are able to find out \n *  - how many of the sums are less than 'lower', say num1, \n *  - how many of the sums are less than 'upper + 1', say num2, \n *  Then 'num2 - num1' is the number of sums that lie within the range of [lower, upper].\n *\n */\n\nclass Node{\n    public:\n        long long val;\n        int cnt; //amount of the nodes\n        Node *left, *right;\n        Node(long long v):val(v), cnt(1), left(NULL), right(NULL) {}\n};\n\n// a tree stores all of prefix sums\nclass Tree{\n    public:\n        Tree():root(NULL){ }\n        ~Tree() { freeTree(root); }\n        \n        void Insert(long long val) {\n            Insert(root, val);\n        }\n        int LessThan(long long sum, int val) {\n            return LessThan(root, sum, val, 0);\n        }\n        \n    private:\n        Node* root;\n        \n        //general binary search tree insert algorithm\n        void Insert(Node* &root, long long val) {\n            if (!root) {\n                root = new Node(val);\n                return;\n            }\n            \n            root->cnt++;\n            \n            if (val < root->val ) {\n                Insert(root->left, val);\n            }else if (val > root->val) {\n                Insert(root->right, val);\n            }\n        }\n        //return how many of the sums less than `val`\n        //  -  `sum` is the new sums which hasn't been inserted\n        //  -  `val` is the `lower` or `upper+1`\n        int LessThan(Node* root, long long sum, int val, int res) {\n            \n            if (!root) return res;\n\n            if ( sum - root->val < val) {\n                //if (sum[j, i] < val), which means all of the right branch must be less than `val` \n                //so we add the amounts of sums in right branch, and keep going the left branch.\n                res += (root->cnt - (root->left ? root->left->cnt : 0) );\n                return LessThan(root->left, sum, val, res);\n            }else if ( sum - root->val > val) {\n                //if (sum[j, i] > val), which means all of left brach must be greater than `val`\n                //so we just keep going the right branch.\n                return LessThan(root->right, sum, val, res);\n            }else {\n                //if (sum[j,i] == val), which means we find the correct place, \n                //so we just return the the amounts of right branch.]\n                return res + (root->right ? root->right->cnt : 0);\n            }\n        }\n        void freeTree(Node* root){\n            if (!root) return;\n            if (root->left) freeTree(root->left);\n            if (root->right) freeTree(root->right);\n            delete root;\n        }\n        \n};\n\n\n\nclass Solution {\npublic:\n    int countRangeSum(vector<int>& nums, int lower, int upper) {\n        Tree tree;\n        tree.Insert(0);\n        long long sum = 0;\n        int res = 0;\n        \n        for (int n : nums) {\n            sum += n;\n            int lcnt = tree.LessThan(sum, lower);\n            int hcnt = tree.LessThan(sum, upper + 1);\n            res += (hcnt - lcnt);\n            tree.Insert(sum);\n        }\n\n        return res;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf.cpp",
    "content": "// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-12-08\n\n/*************************************************************************************** \n *\n * You are given an integer array nums and you have to return a new counts array. The \n * counts array has the property where counts[i] is the number of smaller elements to \n * the right of nums[i].\n * \n * Example:\n * \n * Given nums = [5, 2, 6, 1]\n * \n * To the right of 5 there are 2 smaller elements (2 and 1).\n * To the right of 2 there is only 1 smaller element (1).\n * To the right of 6 there is 1 smaller element (1).\n * To the right of 1 there is 0 smaller element.\n * \n * Return the array [2, 1, 1, 0].\n * \n ***************************************************************************************/\n\n\n// The following idea is based on a `Binary Index Tree` or 'Fenwick Tree'\n// There are two articles explaining this technique quite well:\n// 1) http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/\n// 2) http://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a\n\n#define zeros(i) (i ^ (i - 1)) & i\nclass Solution {\npublic:\n    vector <int> sorted, sol, fenwick;\n    int n;\n    int search(int t)\n    {\n        int step = 0;\n        for(; (1 << step) <= n; step++);\n        int i = 0;\n        for(int k = step; k >= 0; k--)\n            if(i + (1 << k) < n && sorted[i + (1 << k)] <= t)\n                i += (1 << k);\n        return i;\n    }\n    int compute(int t)\n    {\n        int s = 0;\n        for(int i = t; i > 0; i -= zeros(i))\n            s += fenwick[i];\n        return s;\n    }\n    void add(int t)\n    {\n        for(int i = t; i <= n; i += zeros(i))\n            fenwick[i]++;\n    }\n    vector<int> countSmaller(vector<int>& nums) {\n        if(nums.size())\n        {\n            sorted = nums;\n            n = nums.size();\n            sort(sorted.begin(), sorted.end());\n            vector <int> f(sorted.size());\n            fenwick = f;\n            for(int i = nums.size() - 1; i >= 0; i--)\n            {\n                int pos = search(nums[i]) + 1;\n                sol.push_back(compute(pos - 1));\n                add(pos);\n            }\n            reverse(sol.begin(), sol.end());\n        }\n        return sol;\n    }\n};\n\n\n/*************************************************************************************** \n * Another solution - Binary Search Tree\n ***************************************************************************************/\n\n\nclass BinarySearchTreeNode\n{\n    public:\n        int val;     \n        int less;      // count of members less than val\n        int count;     // count of members equal val\n        BinarySearchTreeNode *left, *right;\n        BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {}\n};\n\nclass BinarySearchTree\n{\n    private:\n        BinarySearchTreeNode* root;\n    public:\n        BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ }\n        ~BinarySearchTree() {\n            freeTree(root);\n        }\n        void insert(const int value, int &numLessThan) {\n            insert(root, value, numLessThan);\n        }\n    private:\n        void freeTree(BinarySearchTreeNode* root){\n            if (root == NULL) return;\n            if (root->left) freeTree(root->left);\n            if (root->right) freeTree(root->right);\n            delete root;\n        }\n\n        void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) {\n\n            if(value < root->val) {  // left\n                root->less++;\n                if(root->left == NULL) {\n                    root->left = new BinarySearchTreeNode(value);\n                }else{\n                    this->insert(root->left, value, numLessThan);\n                }\n            } else if(value > root->val) { // right\n                numLessThan += root->less + root->count;\n                if(!root->right) {\n                    root->right = new BinarySearchTreeNode(value);\n                }else{\n                    this->insert(root->right, value, numLessThan);\n                }\n            } else {\n                numLessThan += root->less;\n                root->count++;\n                return;\n            }\n        }\n};\n\nclass Solution {\n    public:\n        vector<int> countSmaller(vector<int>& nums) {\n            vector<int> counts(nums.size());\n            if(nums.size() == 0) return counts;\n\n            BinarySearchTree tree(nums[nums.size()-1]);\n\n            for(int i = nums.size() - 2; i >= 0; i--) {\n                int numLessThan = 0;\n                tree.insert( nums[i], numLessThan);\n                counts[i] = numLessThan;\n            }\n            return counts; \n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/countPairsOfNodes/CountPairsOfNodes.cpp",
    "content": "// Source : https://leetcode.com/problems/count-pairs-of-nodes/\n// Author : Hao Chen\n// Date   : 2021-03-23\n\n/***************************************************************************************************** \n *\n * You are given an undirected graph represented by an integer n, which is the number of nodes, and \n * edges, where edges[i] = [ui, vi] which indicates that there is an undirected edge between ui and \n * vi. You are also given an integer array queries.\n * \n * The answer to the j^th query is the number of pairs of nodes (a, b) that satisfy the following \n * conditions:\n * \n * \ta < b\n * \tcnt is strictly greater than queries[j], where cnt is the number of edges incident to a or \n * b.\n * \n * Return an array answers such that answers.length == queries.length and answers[j] is the answer of \n * the j^th query.\n * \n * Note that there can be repeated edges.\n * \n * Example 1:\n * \n * Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\n * Output: [6,5]\n * Explanation: The number of edges incident to at least one of each pair is shown above.\n * \n * Example 2:\n * \n * Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\n * Output: [10,10,9,8,6]\n * \n * Constraints:\n * \n * \t2 <= n <= 2 * 10^4\n * \t1 <= edges.length <= 10^5\n * \t1 <= ui, vi <= n\n * \tui != vi\n * \t1 <= queries.length <= 20\n * \t0 <= queries[j] < edges.length\n ******************************************************************************************************/\n\n/*\n   The constraint `a < b` could mislead us,\n      - it doesn't mean we need check the pair,\n      - it only means we don't include the duplicated pair.\n\n   For Example: [1, 2] and [2, 1] are duplicated.\n\n   So, we can ignore the `a < b` if we make sure there hasn't duplicated pair.\n\n\n\n\n   We assume all of the nodes are independent, and there is no any pair has connection.\n   So, we can count the number of edge for every node.\n\n   For Example: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]],\n\n   We can have - the `degree` means number of edges.\n        degree[1] = 3\n        degree[2] = 4\n        degree[3] = 2\n        degree[4] = 1\n\n   Then, we could sort all of node by their edges.\n\n       degree:  1 ,  2 ,  3 ,  4\n         node: [4], [3], [1], [2]\n\n   Now, if the `query = 2`, we can have two pointer, one is from left, another one from right.\n\n         degree:  1 ,  2 ,  3 ,  4\n           node: [4], [3], [1], [2]\n                  ^              ^\n                  left          right\n\n        So, (degree[left] + degree[right] > q), it means we can have the following pairs:\n\n         degree:     1+4   2+4   3+4\n           node:    [4,2] [3,2] [1,2]\n\n         ( NB: don't worry about [4,2] & [3,2] are not satsfied `a>b`, they could be [2,4] & [2,3] )\n\n        Then, we can have the following soure code:\n\n            if (degree[left] + degree[right] > query) {\n                count_of_pairs = right - left;\n                right--;\n            }else {\n                left++;\n            }\n\n\n\n   Now, we can deal with pair which are connected, because they have shared edges.\n   So, we need go through all of the pairs they are connect.\n\n   And we need check two condition:\n\n   -  `degree[a] + degree[b] > query` ==> this pair had been counted before!\n   -  `degree[a] + degree[b] - shared_edges(a,b) < query` ==> this pair should be counted!\n\n*/\n\nclass Solution {\npublic:\n    vector<int> countPairs(int n, vector<vector<int>>& edges, vector<int>& queries) {\n        vector<int> degree(n+1);\n        unordered_map<int, unordered_map<int, int>> shared;\n        for (auto& e : edges) {\n            int x = e[0], y = e[1];\n            degree[x]++;\n            degree[y]++;\n            shared[min(x,y)][max(x,y)]++;\n        }\n\n        vector<int> sorted = degree;\n        sort(sorted.begin(), sorted.end());\n\n        vector<int> result;\n        for (auto& q : queries) {\n            int cnt = 0;\n            int left = 1, right = n;\n            //Assuming all of the nodes are independent.\n            while( left < right ) {\n                if (q < sorted[left] + sorted[right] ) {\n                    cnt += (right - left);\n                    right--;\n                }else {\n                    left++;\n                }\n            }\n            //check all of pair they are connected.\n            for (int i = 1; i <= n; i++){\n                for (auto [j, shared_edges] : shared[i]) {\n                    int all_edges = degree[i] + degree[j];\n                    // `q < all_edges`  ==> this pair had been counted before!\n                    // `q >= all_edges - shared_edges` ==> this pair should be counted!\n                    if ( q < all_edges && q >= all_edges - shared_edges ) {\n                        cnt--;\n                    }\n                }\n            }\n            result.push_back(cnt);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countPairsWithXorInARange/CountPairsWithXorInARange.cpp",
    "content": "// Source : https://leetcode.com/problems/count-pairs-with-xor-in-a-range/\n// Author : Hao Chen\n// Date   : 2021-03-21\n\n/***************************************************************************************************** \n *\n * Given a (0-indexed) integer array nums and two integers low and high, return the number of nice \n * pairs.\n * \n * A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= \n * high.\n * \n * Example 1:\n * \n * Input: nums = [1,4,2,7], low = 2, high = 6\n * Output: 6\n * Explanation: All nice pairs (i, j) are as follows:\n *     - (0, 1): nums[0] XOR nums[1] = 5 \n *     - (0, 2): nums[0] XOR nums[2] = 3\n *     - (0, 3): nums[0] XOR nums[3] = 6\n *     - (1, 2): nums[1] XOR nums[2] = 6\n *     - (1, 3): nums[1] XOR nums[3] = 3\n *     - (2, 3): nums[2] XOR nums[3] = 5\n * \n * Example 2:\n * \n * Input: nums = [9,8,4,2,1], low = 5, high = 14\n * Output: 8\n * Explanation: All nice pairs (i, j) are as follows:\n *     - (0, 2): nums[0] XOR nums[2] = 13\n *     - (0, 3): nums[0] XOR nums[3] = 11\n *     - (0, 4): nums[0] XOR nums[4] = 8\n *     - (1, 2): nums[1] XOR nums[2] = 12\n *     - (1, 3): nums[1] XOR nums[3] = 10\n *     - (1, 4): nums[1] XOR nums[4] = 9\n *     - (2, 3): nums[2] XOR nums[3] = 6\n *     - (2, 4): nums[2] XOR nums[4] = 5\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 2 * 10^4\n * \t1 <= nums[i] <= 2 * 10^4\n * \t1 <= low <= high <= 2 * 10^4\n ******************************************************************************************************/\n\n/*\nThe problem can be solved using Trie. \n\nThe idea is to iterate over the given array and for each array element, \ncount the number of elements present in the Trie whose bitwise XOR with \nthe current element is less than K and insert the binary representation \nof the current element into the Trie. Finally, print the count of pairs \nhaving bitwise XOR less than K. Follow the steps below to solve the problem:\n\n  - Create a Trie store the binary representation of each element of the given array.\n  \n  - Traverse the given array, and count the number of elements present in the Trie \n    whose bitwise XOR with the current element is less than K and insert the binary \n    representation of the current element.\n    \n\nLet's assume,  we have an array [A, B, C, D, E], all of number are 5 bits.\n\nFind a pair is (X, E) such that X ^ E < K.  (Note: X could be A,B,C,D)\n\nNow, let's say the binary of K = 11010. E = 01010.\n\nfrom the left to right, \n\n1) Step One - the 1st bit\n\n   K = 1 1 0 1 0\n   E = 0 1 0 1 0\n       ^\n   X = 0 x x x x   ->  all of number with `0` as the 1st bit need to be counted.\n \nNotes: for the 1st bit of X, it could be `0` or `1`.\n \n   - `0`: after XOR E, the 1st bit is `0`, so, it must be smaller than `K`\n   - `1`: after XOR E, the 1st bit is `1`, so, we have to check the rest bits -> Step Two\n   \n2) Step Two - the 2nd bit \n\n   K = 1 1 0 1 0\n   E = 0 1 0 1 0\n         ^\n   X = 1 1 x x x   ->  all of number with `1` as the 2nd bit need to be counted.\n\n3) Step Three - the 3rd bit\n\n   K = 1 1 0 1 0\n   E = 0 1 0 1 0\n           ^\n   X = 1 0 0 x x   ->  must be 0, and go to evaluate next bit\n\n4) Step Four - the 4th bit\n\n   K = 1 1 0 1 0\n   E = 0 1 0 1 0\n             ^\n   X = 1 1 0 1 x   ->  all of number with `1` as the 4th bit need to be counted.\n   \n5) Step Five - the 5th bit\n\n   K = 1 1 0 1 0\n   E = 0 1 0 1 0\n               ^\n   X = 1 1 0 1 0   ->  must be 0, and go to evaluate next bit\n\nSo, all of number will be sum of (step one, two, four)\n    \n*/ \n\nconst int LEVEL = 16; // 1 <= nums[i] <= 20000\n\nstruct TrieNode { \n    TrieNode *child[2];  // Stores binary represention of numbers  \n    int cnt; // Stores count of elements present in a node\n    TrieNode() { \n        child[0] = child[1] = NULL; \n        cnt = 0; \n    } \n}; \n \n \n// Function to insert a number into Trie \nvoid insertTrie(TrieNode *root, int n) { \n    // Traverse binary representation of X \n    for (int i = LEVEL; i >= 0; i--) { \n        // Stores ith bit of N \n        bool x = (n) & (1 << i); \n        // Check if an element already present in Trie having ith bit x\n        if(!root->child[x]) { \n            // Create a new node of Trie. \n            root->child[x] = new TrieNode(); \n        } \n        // Update count of elements whose ith bit is x \n        root->child[x]->cnt += 1; \n        \n        //Go to next level\n        root = root->child[x]; \n    } \n} \n\n\nclass Solution {\nprivate:\n    // Count elements in Trie whose XOR with N less than K \n    int countSmallerPairs(TrieNode * root,  int N, int K) { \n        // Stores count of elements whose XOR with N less than K \n        int cntPairs = 0; \n        // Traverse binary representation of N and K in Trie \n        for (int i = LEVEL; i >= 0 && root; i--) {                 \n            bool x = N & (1 << i); // Stores ith bit of N \n            bool y = K & (1 << i); // Stores ith bit of K \n\n            // If the ith bit of K is 0 \n            if (y == 0 ) { \n                // find the number which bit is same as N\n                // so that they can be xored to ZERO\n                root = root->child[x]; \n                continue;\n            } \n            // If the ith bit of K is 1 \n            // If an element already present in Trie having ith bit (x)\n            if(root->child[x]) {\n                // find the number which bit is same as N\n                // so that they can be xored to ZERO. so it would be smaller than K\n                cntPairs  += root->child[x]->cnt; \n            }\n            //go to another way for next bit count\n            root = root->child[1 - x]; \n        } \n        return cntPairs; \n    } \npublic:\n    int countPairs(vector<int>& nums, int low, int high) {\n        \n        TrieNode* root = new TrieNode();\n        \n        int cnt = 0;\n        for (auto& num : nums) {\n            cnt += countSmallerPairs(root, num, high + 1) - countSmallerPairs(root, num, low);\n            insertTrie(root, num);\n        }\n        \n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/countPrimes/CountPrimes.cpp",
    "content": "// Source : https://leetcode.com/problems/count-primes/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Description:\n * Count the number of prime numbers less than a non-negative number, n.\n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.\n * \n *   Let's start with a isPrime function. To determine if a number is prime, we need to check if \n *   it is not divisible by any number less than n. The runtime complexity of isPrime function \n *   would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?\n *   \n *   As we know the number must not be divisible by any number > n / 2, we can immediately cut the total \n *   iterations half by dividing only up to n / 2. Could we still do better?\n *   \n *   Let's write down all of 12's factors:\n * \n * \t2 × 6 = 12\n * \t3 × 4 = 12\n * \t4 × 3 = 12\n * \t6 × 2 = 12\n * \n * As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider \n * factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.\n * \n * Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?\n * \n *\tpublic int countPrimes(int n) {\n *\t   int count = 0;\n *\t   for (int i = 1; i < n; i++) {\n *\t      if (isPrime(i)) count++;\n *\t   }\n *\t   return count;\n *\t}\n *\t\n *\tprivate boolean isPrime(int num) {\n *\t   if (num <= 1) return false;\n *\t   // Loop's ending condition is i * i <= num instead of i <= sqrt(num)\n *\t   // to avoid repeatedly calling an expensive function sqrt().\n *\t   for (int i = 2; i * i <= num; i++) {\n *\t      if (num % i == 0) return false;\n *\t   }\n *\t   return true;\n *\t}\n *   \n *   The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. \n *   But don't let that name scare you, I promise that the concept is surprisingly simple.\n *\n *\t[Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)\n * \n *\t[https://leetcode.com/static/images/solutions/Sieve_of_Eratosthenes_animation.gif]\n *\t[http://commons.wikimedia.org/wiki/File:Sieve_of_Eratosthenes_animation.gif]\n *\n *   Sieve of Eratosthenes: algorithm steps for primes below 121. \"Sieve of Eratosthenes Animation\"() \n *   by SKopp is licensed under CC BY 2.0.\n *\n *      * [Skoop](http://de.wikipedia.org/wiki/Benutzer:SKopp)\n *\t* [CC BY 2.0](http://creativecommons.org/licenses/by/2.0/)\n * \n * We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 \n * must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, \n * all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. \n * Now we look at the next number, 4, which was already marked off. What does this tell you? Should you \n * mark off all multiples of 4 as well?\n *   \n * 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible \n * by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, \n * all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. \n * There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?\n *   \n * In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off \n * by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current \n * number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... \n * Now what should be the terminating loop condition?\n *   \n * It is easy to say that the terminating loop condition is p n, which is certainly correct but not efficient. \n * Do you still remember Hint #3?\n *   \n * Yes, the terminating loop condition can be p n, as all non-primes ≥ √n must have already been marked off. \n * When the loop terminates, all the numbers in the table that are non-marked are prime.\n * \n * The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). \n * For the more mathematically inclined readers, you can read more about its algorithm complexity on \n * [Wikipedia](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity).\n * \n *\tpublic int countPrimes(int n) {\n *\t   boolean[] isPrime = new boolean[n];\n *\t   for (int i = 2; i < n; i++) {\n *\t      isPrime[i] = true;\n *\t   }\n *\t   // Loop's ending condition is i * i < n instead of i < sqrt(n)\n *\t   // to avoid repeatedly calling an expensive function sqrt().\n *\t   for (int i = 2; i * i < n; i++) {\n *\t      if (!isPrime[i]) continue;\n *\t      for (int j = i * i; j < n; j += i) {\n *\t         isPrime[j] = false;\n *\t      }\n *\t   }\n *\t   int count = 0;\n *\t   for (int i = 2; i < n; i++) {\n *\t      if (isPrime[i]) count++;\n *\t   }\n *\t   return count;\n *\t}\n *   \n *               \n **********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nint countPrimes(int n) {\n    vector<bool> isPrimer(n, true);\n\n    for(int i=2; i*i<n; i++){\n        if (isPrimer[i]){\n            for(int j=i*i; j<n; j+=i){\n                isPrimer[j] = false;\n            }\n        }\n    }\n\n    int cnt = 0;\n    for(int i=2; i<n; i++){\n        if (isPrimer[i]) { \n            //cout << i << \", \";\n            cnt++;\n        }\n    }\n    return cnt;\n}\n\n\nint main(int argc, char**argv) \n{\n    int n = 100;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n  \n    cout << endl << n << \" : \" << countPrimes(n) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/countingBits/CountingBits.cpp",
    "content": "// Source : https://leetcode.com/problems/counting-bits/\n// Author : Hao Chen\n// Date   : 2016-05-30\n\n/*************************************************************************************** \n *\n * Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ \n * num calculate the number of 1's in their binary representation and return them as an \n * array.\n * \n * Example:\n * For num = 5 you should return [0,1,1,2,1,2].\n * \n * Follow up:\n * \n * It is very easy to come up with a solution with run time O(n*sizeof(integer)). But \n * can you do it in linear time O(n) /possibly in a single pass?\n * Space complexity should be O(n).\n * Can you do it like a boss? Do it without using any builtin function like \n * __builtin_popcount  in c++ or in any other language.\n * \n *   You should make use of what you have produced already.\n *   Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to \n * generate new range from previous.\n *   Or does the odd/even status of the number help you in calculating the number of 1s?\n * \n * Credits:Special thanks to @ syedee  for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    /* \n     * Initialization\n     * \n     *   bits_cnt[0] => 0000 => 0\n     *   bits_cnt[1] => 0001 => 1\n     * \n     * if the number has 2 bits (2, 3), then we can split the binary to two parts, \n     * 2 = 10 + 0  and  3= 10 + 1, then we can reuse the bits_cnt[0] and bits_cnt[1] \n     *\n     *   bits_cnt[2] => 0010 => 0010 + 0 => 1 + bits_cnt[0];\n     *   bits_cnt[3] => 0011 => 0010 + 1 => 1 + bits_cnt[1];\n     *\n     * if the number has 3 bits (4,5,6,7), then we can split the binary to two parts, \n     * 4 = 100 + 0,  5 = 100 + 01, 6= 100 + 10, 7 = 100 +11\n     * then we can reuse the bits_cnt[0] and bits_cnt[1] \n     * \n     *   bits_cnt[4] => 0110 => 0100 + 00 => 1 + bits_cnt[0];\n     *   bits_cnt[5] => 0101 => 0100 + 01 => 1 + bits_cnt[1];\n     *   bits_cnt[6] => 0110 => 0100 + 10 => 1 + bits_cnt[2];\n     *   bits_cnt[7] => 0111 => 0100 + 11 => 1 + bits_cnt[3];\n     *\n     * so, we can have the solution:\n     *\n     *   bits_cnt[x] = bits_cnt[x & (x-1) ] + 1;\n     *\n     */\n    vector<int> countBits(int num) {\n        vector<int> bits_cnt(num+1, 0); \n        \n        for (int i=1; i<=num; i++) {\n            bits_cnt[i] = bits_cnt[i & (i-1)] + 1;\n        }\n        return bits_cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/courseSchedule/CourseSchedule.II.cpp",
    "content": "// Source : https://leetcode.com/problems/course-schedule-ii/\n// Author : Hao Chen\n// Date   : 2015-06-10\n\n/********************************************************************************** \n * \n * There are a total of n courses you have to take, labeled from 0 to n - 1.\n * \n * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, \n * which is expressed as a pair: [0,1]\n * \n * Given the total number of courses and a list of prerequisite pairs, return the ordering of courses \n * you should take to finish all courses.\n * \n * There may be multiple correct orders, you just need to return one of them. If it is impossible to \n * finish all courses, return an empty array.\n * \n * For example:\n *      2, [[1,0]]\n * There are a total of 2 courses to take. To take course 1 you should have finished course 0. \n * So the correct course order is [0,1]\n * \n *      4, [[1,0],[2,0],[3,1],[3,2]]\n * There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. \n * Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. \n * Another correct ordering is[0,2,1,3].\n * \n * Note:\n * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. \n * Read more about how a graph is represented.\n * \n * click to show more hints.\n * \n * Hints:\n * \n *  - This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, \n *    no topological ordering exists and therefore it will be impossible to take all courses.\n *\n *  - Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining \n *    the basic concepts of Topological Sort.\n *\n *  - Topological sort could also be done via BFS.\n * \n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    // if has cycle, return false, else return true\n    bool topologicalSort( int n, vector<int>& explored, vector<int>& path, \n                          unordered_map<int, vector<int>>& graph, \n                          vector<int>& result) \n    {\n        \n        for(int i=0; i<graph[n].size(); i++) {\n            \n            int prereq = graph[n][i];\n            \n            if ( path[prereq] ) {\n                result.clear();\n                return false;\n            }\n            \n            path[prereq] = true;\n            if (!topologicalSort(prereq, explored, path, graph, result)){\n                result.clear();\n                return false;\n            }\n            path[prereq] = false;\n        }\n        if (!explored[n]) {\n            result.push_back(n);\n        }\n        explored[n] = true;\n        return true;\n    }\n\n    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {\n        \n        vector<int> result;\n        vector<int> enterance (numCourses, true);\n        \n        //using map to stroe the graph, it's easy to search the edge for each node\n        //the bool in pair means it is explored or not\n        unordered_map<int, vector<int>> graph;\n        for(int i=0; i<prerequisites.size(); i++){\n            graph[prerequisites[i].first].push_back( prerequisites[i].second );\n            enterance[prerequisites[i].second] = false;\n        }\n\n        //explored[] is used to record the node already checked!\n        vector<int> explored(numCourses, false);\n\n        //path[] is used to check the cycle during DFS\n        vector<int> path(numCourses, false);\n\n        for(int i=0; i<numCourses; i++){\n            if (!enterance[i] || explored[i]) continue;\n            if (!topologicalSort(i, explored, path, graph, result)) return result;\n        }\n        //if there has one course hasn't been explored, means there is a cycle\n        for (int i=0; i<numCourses; i++){\n            if (!explored[i]) return vector<int>();\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/courseSchedule/CourseSchedule.cpp",
    "content": "// Source : https://leetcode.com/problems/course-schedule/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * There are a total of n courses you have to take, labeled from 0 to n - 1.\n * \n * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, \n * which is expressed as a pair: [0,1]\n * \n * Given the total number of courses and a list of prerequisite pairs, is it possible for you to \n * finish all courses?\n * \n * For example:\n *      2, [[1,0]]\n * There are a total of 2 courses to take. To take course 1 you should have finished course 0. \n * So it is possible.\n * \n *      2, [[1,0],[0,1]]\n * There are a total of 2 courses to take. To take course 1 you should have finished course 0, \n * and to take course 0 you should also have finished course 1. So it is impossible.\n * \n * Note:\n * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. \n * Read more about how a graph is represented.\n * \n * click to show more hints.\n * \n * Hints:\n * \n *  - This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, \n *    no topological ordering exists and therefore it will be impossible to take all courses.\n *\n *  - Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic \n *    concepts of Topological Sort. (https://class.coursera.org/algo-003/lecture/52)\n *\n *  - Topological sort could also be done via BFS. (http://en.wikipedia.org/wiki/Topological_sorting#Algorithms)\n * \n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n\n    bool hasCycle(int n, vector<int>& explored, vector<int>& path, map<int, vector<int>>& graph) {\n        \n        for(int i=0; i<graph[n].size(); i++){\n            \n            //detect the cycle\n            if ( path[graph[n][i]] ) return true;\n            \n            //set the marker\n            path[graph[n][i]] = true;\n            \n            if (hasCycle(graph[n][i], explored, path, graph)) {\n                return true;\n            }\n            //backtrace reset\n            path[graph[n][i]] = false;\n        }\n        //no cycle found, mark this node can finished!\n        explored[n] = true;\n        return false;\n        \n    }\n\n    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {\n        \n        //using map to stroe the graph, it's easy to search the edge for each node\n        //the bool in pair means it is explored or not\n        map<int, vector<int>> graph;\n        for(int i=0; i<prerequisites.size(); i++){\n            graph[prerequisites[i].first].push_back( prerequisites[i].second );\n        }\n        \n        //explored[] is used to record the node already checked!\n        vector<int> explored(numCourses, false);\n        \n        //path[] is used to check the cycle during DFS\n        vector<int> path(numCourses, false);\n        \n        for(int i=0; i<numCourses; i++){\n            \n            if (explored[i]) continue;\n            if (hasCycle(i, explored, path, graph)) return false;\n            \n\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/courseSchedule/non-recursive/course_schedule.cpp",
    "content": "//\n//  course_schedule.cpp\n//  LeeteCodeOJ#207\n//\n//  Created by Wang Yi on 28/11/16.\n//  Copyright (c) 2016 Wang Yi. All rights reserved.\n//\n\n#include <stdio.h>\n\n#include <stack>\n#include <queue>\n#include <vector>\n#include <unordered_set>\n\nusing std::stack;\nusing std::queue;\nusing std::vector;\nusing std::unordered_set;\nusing std::pair;\n\ntypedef pair<int, int> Val;\ntypedef vector<unordered_set<int>> Graph;\n\n#define FOR(s, e) \\\nfor (s = 0; s < e; s++) {\n#define END ;}\n    \n    typedef struct _node {\n        int val;\n        // int depth;\n        struct _node * parent;\n    } node;\n    \n    class Solution {\n    public:\n        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {\n            vector<int> outdepth(numCourses, 0);\n            unordered_set<int> vex;\n            if ((int) prerequisites.size() == 0)\n                return true;\n            vector<unordered_set<int>> graph = to_neighbor_repr(numCourses, prerequisites, outdepth);\n            \n            return dsf(numCourses, graph, outdepth);\n        }\n        \n        vector<unordered_set<int>> to_neighbor_repr(int numOfvex, vector<Val>& edges,\n                                                    vector<int>& outdepth) {\n            // std::cout << \"building ... \" << std::endl;\n            vector<unordered_set<int>> graph(numOfvex);\n            for (auto edge : edges) {\n                graph[edge.second].insert(edge.first); // second -> first\n                outdepth[edge.second]++;\n                // std::cout << edge.first << \" <- \" << edge.second << std::endl;\n            }\n            \n            return graph;\n            \n        }\n        \n        \n        bool dsf(int numOfvex, vector<unordered_set<int>>& graph, vector<int>& outdepth)\n        {\n            // preparation\n            stack<node> s;\n            vector<bool> visited(numOfvex, false);\n            vector<bool> onpath(numOfvex, false);\n            vector<int> starts;\n            \n            int i;\n            \n            unordered_set<int> children;\n            \n            \n            FOR(i, numOfvex)\n            if (outdepth[i] !=0 ) {\n                starts.push_back(i);\n            }\n            END\n            \n            if ((int)starts.size() == 0)\n                return false; // no vertex with indepth of 0 found, a circle found\n            \n            for (auto j: starts) {\n                // std::cout << \"start from \" << j << std::endl;\n                // do dsf search, if not visited\n                // when a circle in a path found, return false.\n                // else return true\n                if (visited[j])\n                    continue;\n                \n                node head;\n                head.val = j;\n                head.parent = NULL;\n                // head.depth = 1;\n                s.push(head);\n                \n                // non-recursive search\n                while (!s.empty()) {\n                    node* curr = &(s.top());\n                    \n                    if (visited[curr->val]) {\n                        // all children have been read\n                        s.pop();\n                        onpath[curr->val] = false;\n                        continue; // ignore ...\n                    }\n                    \n                    onpath[curr->val] = visited[curr->val]= true;\n                    children = graph[curr->val];\n                    \n                    if ((int)children.size() == 0) {\n                        s.pop();\n                        onpath[curr->val] = false;\n                        // std::cout << \"==== reach the end ====\"<<std::endl;\n                        continue;\n                    }\n                    \n                    // std::cout << curr->val << \"'s children is: \";\n                    for (auto child: children) {\n                        // std::cout << child << \" \";\n                        //if (onpath.find(child) == onpath.end())\n                        if (onpath[child]) {\n                            \n                            // std::cout << std::endl << \"a circle found:\" << std::endl;\n                            // std::cout << child << \" <- \";\n                            // while (curr->parent != NULL) {\n                            //     std::cout << curr->val << \" <- \";\n                            //     curr = curr->parent;\n                            // }\n                            // std::cout << curr->val << std::endl;\n                            \n                            return false; // a circle found, might print debug here\n                        }\n                        \n                        node nd;\n                        nd.val = child;\n                        // nd.depth = curr->depth+1;\n                        nd.parent = curr; // for debug purpose ...\n                        s.push(nd);\n                    }\n                    // std::cout << std::endl;\n                }\n                \n            } // end of for\n            return true;\n        }\n        \n    };"
  },
  {
    "path": "algorithms/cpp/courseSchedule/non-recursive/main.cpp",
    "content": "//\n//  main.cpp\n//  LeeteCodeOJ#207\n//\n//  Created by Wang Yi on 28/11/16.\n//  Copyright (c) 2016 Wang Yi. All rights reserved.\n//\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\n#include \"course_schedule.cpp\"\n\nusing std::make_pair;\n\nint main(int argc, const char * argv[]) {\n    // insert code here...\n    Solution sl;\n    int numCourses = 4;\n    vector<Val> prerequisites;\n    prerequisites.push_back(make_pair<int, int>(0,1));\n    prerequisites.push_back(make_pair<int, int>(3,1));\n    prerequisites.push_back(make_pair<int, int>(1,3));\n    prerequisites.push_back(make_pair<int, int>(3,2));\n\n    \n    std::cout << sl.canFinish(numCourses, prerequisites);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/cousinsInBinaryTree/CousinsInBinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/cousins-in-binary-tree/\n// Author : Hao Chen\n// Date   : 2019-04-30\n\n/***************************************************************************************************** \n *\n * In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.\n * \n * Two nodes of a binary tree are cousins if they have the same depth, but have different parents.\n * \n * We are given the root of a binary tree with unique values, and the values x and y of two different \n * nodes in the tree.\n * \n * Return true if and only if the nodes corresponding to the values x and y are cousins.\n * \n * Example 1:\n * \n * Input: root = [1,2,3,4], x = 4, y = 3\n * Output: false\n * \n * Example 2:\n * \n * Input: root = [1,2,3,null,4,null,5], x = 5, y = 4\n * Output: true\n * \n * Example 3:\n * \n * Input: root = [1,2,3,null,4], x = 2, y = 3\n * Output: false\n * \n * Note:\n * \n * \tThe number of nodes in the tree will be between 2 and 100.\n * \tEach node has a unique integer value from 1 to 100.\n * \n ******************************************************************************************************/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isCousins(TreeNode* root, int x, int y) {\n        int dx=0, dy=0;\n        TreeNode *px=root, *py=root;\n        dx = DepthAndParent(root, px, 0, x);\n        dy = DepthAndParent(root, py, 0, y);\n        if (dx && dy){\n            return (dx == dy && px != py);\n        }\n\n        return false;\n\n    }\n\n    int DepthAndParent(TreeNode* root, TreeNode*& parent, int depth, int x) {\n        if (!root) return 0;\n        if ( root->val == x) return depth;\n\n        int d=0;\n        parent = root;\n        if  ( ( d = DepthAndParent(root->left, parent, depth+1, x)) > 0 ) return d;\n\n        parent = root;\n        if ( ( d = DepthAndParent(root->right, parent, depth+1, x)) > 0 ) return d;\n        return 0;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/create-maximum-number/\n// Author : Hao Chen\n// Date   : 2016-01-21\n\n/*************************************************************************************** \n *\n * Given two arrays of length m and n with digits 0-9 representing two numbers.\n *     Create the maximum number of length k  from digits of the two. The relative \n * order of the digits\n *     from the same array must be preserved. Return an array of the k digits. You \n * should try to optimize your time and space complexity.\n * \n *     Example 1:\n * \n *     nums1 = [3, 4, 6, 5]\n *     nums2 = [9, 1, 2, 5, 8, 3]\n *     k = 5\n *     return [9, 8, 6, 5, 3]\n * \n *     Example 2:\n * \n *     nums1 = [6, 7]\n *     nums2 = [6, 0, 4]\n *     k = 5\n *     return [6, 7, 6, 0, 4]\n * \n *     Example 3:\n * \n *     nums1 = [3, 9]\n *     nums2 = [8, 9]\n *     k = 3\n *     return [9, 8, 9]\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\n\n/*\n * Solution\n * --------\n * \n * 1) We split the `K` to two parts : `i` & `k-i`  0<= i <= k\n * \n * 2) Find the max number for both arrays with giving the length `i` and `k-i`\n *      - sub1 = FindMaxNumber(num1, len=i);\n *      - sub2 = FindMaxNumber(num2, len=k-i);\n *    Here, we need use stack-way to solve find the max number.\n * \n * 3) Merge two arrays \n *      - solution = Merge(sub1, sub2);\n *    Here, we need be careful if a two number are same which one we need to take.  For examples: \n *      [6,7]\n *      [6,0,4]\n *      5\n *      \n *      [2,5,6,4,4,0]\n *      [7,3,8,0,6,5,7,6,2]\n *      15\n * \n * 4) compare with the last solution\n *     - result = max(result, solution); \n * \n * \n */\n\n\nclass Solution {\npublic:\n    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {\n        vector<int> result;\n        int len1 = nums1.size();\n        int len2 = nums2.size();\n        for (int i=0; i<=k; i++){\n            if (len1 < i || len2 < k-i) continue;\n            vector<int> sub1 = findMaxSubArray(nums1, i);\n            vector<int> sub2 = findMaxSubArray(nums2, k-i);\n            vector<int> merge = mergeTwoArrays(sub1, sub2);\n            if (compareTwoArray(merge, 0, result, 0)) {\n                result = merge;\n            }\n        }\n        return result;\n    }\n    \n    \n    bool compareTwoArray(vector<int>& nums1, int start1, vector<int>& nums2, int start2) {\n        int n1 = nums1.size();\n        int n2 = nums2.size();\n        for(; start1<n1 && start2<n2; start1++, start2++){\n            if (nums1[start1] > nums2[start2]) return true;\n            if (nums1[start1] < nums2[start2]) return false;\n        }\n        //if num1 still have numbers, return true, else return false\n        return start1 < nums1.size();\n    }\n    \n    vector<int> mergeTwoArrays(vector<int>& nums1, vector<int>& nums2) {\n        vector<int> result;\n        int len1 = nums1.size();\n        int len2 = nums2.size();\n        int pos1=0, pos2=0;\n        while ( pos1 < len1 && pos2 < len2 ){\n            // Be careful if two numbers are equal. consider the following case\n            // case 1: [6,7], [6,0,4]  - we have same item - 6\n            // case 2: [4,0,2], [2,0,3,1] - we have same item - 0\n            // which one we need to merge?\n            // We need compare the rest of array.\n            if (nums1[pos1] == nums2[pos2]){\n                result.push_back( compareTwoArray(nums1, pos1+1, nums2, pos2+1) ? \n                                    nums1[pos1++] : nums2[pos2++]);\n            }else {\n                result.push_back(nums1[pos1] > nums2[pos2] ? \n                                    nums1[pos1++] : nums2[pos2++]);\n            }\n        }\n        \n        if (pos1 < len1){\n            result.insert(result.end(), nums1.begin()+pos1, nums1.end());\n        }\n        if (pos2 < len2) {\n            result.insert(result.end(), nums2.begin()+pos2, nums2.end());\n        }\n        \n        return result;\n    }\n    \n    \n    // using a stack method to find the max sub-array\n    // k <= nums.size()\n    vector<int> findMaxSubArray(vector<int>& nums, int k) {\n        int len = nums.size();\n        if ( k >= len ) return nums;\n        vector<int> result(k, 0);\n        int idx = 0; // the postion for result array\n        for (int i=0; i<len; i++){\n            // if we met a number > the last element of result[], \n            // and we still have enough numbers,\n            // then pop up the item\n            while (idx>0 && k - idx < len - i && result[idx-1] < nums[i]) {\n                idx--;\n            }\n            //push the number into the result[]\n            if (idx < k) {\n                result[idx++] = nums[i];\n            }\n        }\n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/decodeString/DecodeString.cpp",
    "content": "// Source : https://leetcode.com/problems/decode-string/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * Given an encoded string, return it's decoded string.\n * \n * The encoding rule is: k[encoded_string], where the encoded_string inside the square \n * brackets is being repeated exactly k times. Note that k is guaranteed to be a \n * positive integer.\n * \n * You may assume that the input string is always valid; No extra white spaces, square \n * brackets are well-formed, etc.\n * \n * Furthermore, you may assume that the original data does not contain any digits and \n * that digits are only for those repeat numbers, k. For example, there won't be input \n * like 3a or 2[4].\n * \n * Examples:\n * \n * s = \"3[a]2[bc]\", return \"aaabcbc\".\n * s = \"3[a2[c]]\", return \"accaccacc\".\n * s = \"2[abc]3[cd]ef\", return \"abcabccdcdcdef\".\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    string decodeString(string s) {\n        if (!isValid(s)) return \"\";\n        \n        stack<string> _stack;\n        stack<int> _nstack;\n        \n        string result;\n        string tmp;\n        int n=0;\n        for (int i=0; i<s.size(); i++) {\n            \n            if ( isNum(s[i]) ) {\n                n = 0;\n                for(; isNum(s[i]); i++ ) {\n                   n = n*10 + s[i] - '0'; \n                }\n            }\n            \n            if (s[i] == '[') {\n                tmp=\"\";\n                _stack.push(tmp);\n                _nstack.push(n);\n            } else if (s[i] == ']') {\n                n = _nstack.top(); \n                tmp=\"\";\n                for (; n>0; n--) {\n                    tmp += _stack.top();\n                }\n                _stack.pop();\n                _nstack.pop();\n                if ( ! _stack.empty() ) {\n                    _stack.top() += tmp;\n                }else {\n                    result += tmp;\n                }\n            } else {\n                if ( ! _stack.empty() ) {\n                    _stack.top() += s[i];\n                } else {\n                    result += s[i];\n                }\n                \n            }\n        }\n        \n        return result;\n    }\n    \nprivate:\n\n    //only check the following rules:\n    // 1) the number must be followed by '['\n    // 2) the '[' and ']' must be matched.\n    bool isValid(string& s) {\n        stack<char> _stack;\n        for (int i=0; i<s.size(); i++) {\n            if ( isNum(s[i]) ) {\n                for(; isNum(s[i]); i++);\n                if (s[i] != '[') {\n                    return false;\n                } \n                _stack.push('[');\n                continue;\n            } else if (s[i] == ']' ) {\n                if ( _stack.top() != '[' ) return false;\n                _stack.pop();\n            }\n        }\n        \n        return (_stack.size() == 0);\n    }\n    \n    bool isNum(char ch) {\n        return (ch>='0' && ch<='9');\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/decodeWays/decodeWays.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/decode-ways/\n// Author : Hao Chen\n// Date   : 2014-07-16\n\n/********************************************************************************** \n* \n* A message containing letters from A-Z is being encoded to numbers using the following mapping:\n* \n* 'A' -> 1\n* 'B' -> 2\n* ...\n* 'Z' -> 26\n* \n* Given an encoded message containing digits, determine the total number of ways to decode it.\n* \n* For example,\n* Given encoded message \"12\",\n* it could be decoded as \"AB\" (1 2) or \"L\" (12).\n* \n* The number of ways decoding \"12\" is 2.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <string.h>\nusing namespace std;\n\n\n//Count[i] = Count[i-1]              if S[i-1] is a valid char (not '0')\n//         = Count[i-1]+ Count[i-2]  if S[i-1] and S[i-2] together is still a valid char (10 to 26).\n\nint check(char ch){\n    //check 0 or not\n    return (!isdigit(ch) || ch=='0') ? 0 : 1;\n}\n\nint check(char ch1, char ch2){\n    //check it's between 10 and 26\n    return (ch1=='1' || (ch1=='2' && ch2<='6')) ? 1: 0;\n}\n\nint numDecodings(string s) {\n    if (s.size()<=0) return 0;\n    if (s.size()==1) return check(s[0]);\n   \n    int* dp = new int[s.size()];\n    memset(dp, 0, s.size()*sizeof(int));\n\n    dp[0] = check(s[0]);\n    dp[1] = check(s[0]) *  check(s[1]) + check(s[0], s[1]) ;\n    for (int i=2; i<s.size(); i++) {\n        if (!isdigit(s[i])) break; \n        if (check(s[i])) {\n            dp[i] = dp[i-1];\n        }\n        if (check(s[i-1], s[i])) {\n            dp[i] += dp[i-2];\n        }\n    \n    }\n    int result = dp[s.size()-1];\n    delete[] dp;\n    return result;\n}\n\n\nint main(int argc, char**argv)\n{\n    string s = \"123\";\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << \"\\\"\" << s << \"\\\" : \" << numDecodings(s) << endl; \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/decodeXORedPermutation/DecodeXoredPermutation.cpp",
    "content": "// Source : https://leetcode.com/problems/decode-xored-permutation/\n// Author : Hao Chen\n// Date   : 2021-02-17\n\n/***************************************************************************************************** \n *\n * There is an integer array perm that is a permutation of the first n positive integers, where n is \n * always odd.\n * \n * It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] \n * XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].\n * \n * Given the encoded array, return the original array perm. It is guaranteed that the answer exists \n * and is unique.\n * \n * Example 1:\n * \n * Input: encoded = [3,1]\n * Output: [1,2,3]\n * Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\n * \n * Example 2:\n * \n * Input: encoded = [6,5,4,6]\n * Output: [2,4,1,5,3]\n * \n * Constraints:\n * \n * \t3 <= n < 105\n * \tn is odd.\n * \tencoded.length == n - 1\n ******************************************************************************************************/\n/*\n    XOR Basic Rules\n    ---------------\n    At first, we need understand the following XOR rules\n\n    x^x = 0\n    0^x = x\n    with the rule 1 and 2 , we can have: x^x^y = y . the element ocurrs twice would be removed.\n    if x^y = z , then x = y^z and y = x^z\n   \n    XOR from 1 to n\n    ---------------\n    Secondly, suppose the f(n) is XOR from 1 to n , f(n) = 1^2^3^4^5 .... ^n .\n    if the n is odd number, then we can observse the following things:\n\n    f(1) = 1\n    f(3) = 1^2^3 = 0\n    f(5) = 1^2^3^4^5 = 1\n    f(7) = 1^2^3^4^5^6^7 = 0\n    f(9) = 1^2^3^4^5^6^7^8^9 = 1\n    ... ...\n    so, f(n) = [ (n-1)/2 + 1 ] % 2 - (n is odd number)\n\n    Solution\n    --------\n    We know,\n    encode = { (p1^p2), (p2^p3), (p3^p4), ... } - p is the permutation array\n\n    so, if xor the odd index of encoded[] array,\n\n    encoded[1] = p2 ^ p3;\n    encoded[3] = p4 ^ p5;\n    encoded[5] = p6 ^ p7;\n    ......\n    we can get: f(m) = p2 ^ p3 ^ p4 ...pn, without the p1\n\n    with the XOR rule 3, we know\n\n    p1 = f(n) ^ f(m)\n\n    with the XOR rule 4, we know encoded[0] = p1^p2 then\n    p2 = p1 ^ enclode[0]\n\n    So,\n\n    p[i+1] = p[i] ^ enclode[i]\n*/\nclass Solution {\npublic:\n    vector<int> decode(vector<int>& encoded) {\n        \n        // f(n)  = 1^2^3^4^5 .... ^n ( n is odd number)\n        // then, \n        //   f(3) = 1\n        //   f(5) = 0\n        //   f(7) = 1\n        //   f(9) = 0\n        //   ... ...\n        // f(n) = [ (n-1)/2 + 1 ] % 2\n        int nxor = (encoded.size() / 2 + 1) % 2 ;\n        \n        // suppose the a[1], a[2], a[3] .... a[n] is the result array.\n        // xor the odd index of encoded[] array,\n        //    encoded[1] = a[2] ^ a[3];\n        //    encoded[3] = a[4] ^ a[5];\n        //    encode [5] = a[6] ^ a[7];\n        //    ......\n        // we can get:  f(m) = a[2] ^ a[3] ^ a[4] ...a[n] \n        int mxor = encoded[1];\n        for (int i=3; i< encoded.size(); i+=2) {\n            mxor ^= encoded[i];\n        }\n        \n        // a[1] = f(n) ^ f(m) \n        x = nxor ^ mxor;\n        \n        vector<int> result;\n        result.push_back(x);\n        \n        // we know, encoded[i] = a[i] ^ a[i+1]\n        // so, a[i+1] = a[i] ^ encoded[i]\n        for (int i=0; i< encoded.size(); i++) {\n            x = x ^ encoded[i];\n            result.push_back(x);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp",
    "content": "// Source : https://leetcode.com/problems/delete-node-in-a-linked-list/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Write a function to delete a node (except the tail) in a singly linked list, given \n * only access to that node.\n * \n * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with \n * value 3, the linked list should become 1 -> 2 -> 4 after calling your function.\n * \n **********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    //becasue the deleted is not the tail.\n    //So, we can move the content of next node to this one, and delete the next one \n    void deleteNode(ListNode* node) {\n        node->val = node->next->val;\n        node->next = node->next->next;\n    }\n};\n\n\n"
  },
  {
    "path": "algorithms/cpp/designAuthenticationManager/DesignAuthenticationManager.cpp",
    "content": "// Source : https://leetcode.com/problems/design-authentication-manager/\n// Author : Hao Chen\n// Date   : 2021-03-22\n\n/***************************************************************************************************** \n *\n * There is an authentication system that works with authentication tokens. For each session, the user \n * will receive a new authentication token that will expire timeToLive seconds after the currentTime. \n * If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the \n * (potentially different) currentTime.\n * \n * Implement the AuthenticationManager class:\n * \n * \tAuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the \n * timeToLive.\n * \tgenerate(string tokenId, int currentTime) generates a new token with the given tokenId at \n * the given currentTime in seconds.\n * \trenew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at \n * the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the \n * request is ignored, and nothing happens.\n * \tcountUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given \n * currentTime.\n * \n * Note that if a token expires at time t, and another action happens on time t (renew or \n * countUnexpiredTokens), the expiration takes place before the other actions.\n * \n * Example 1:\n * \n * Input\n * [\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \n * \"renew\", \"countUnexpiredTokens\"]\n * [[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]\n * Output\n * [null, null, null, 1, null, null, null, 0]\n * \n * Explanation\n * AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the \n * AuthenticationManager with timeToLive = 5 seconds.\n * authenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing \n * happens.\n * authenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\n * authenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only \n * unexpired one at time 6, so return 1.\n * authenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\n * authenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= \n * 7, so at time 8 the renew request is ignored, and nothing happens.\n * authenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so \n * the renew request is fulfilled and now the token will expire at time 15.\n * authenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, \n * and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.\n * \n * Constraints:\n * \n * \t1 <= timeToLive <= 10^8\n * \t1 <= currentTime <= 10^8\n * \t1 <= tokenId.length <= 5\n * \ttokenId consists only of lowercase letters.\n * \tAll calls to generate will contain unique values of tokenId.\n * \tThe values of currentTime across all the function calls will be strictly increasing.\n * \tAt most 2000 calls will be made to all functions combined.\n ******************************************************************************************************/\n\nclass AuthenticationManager {\nprivate: \n    int ttl;\n    set<pair<int, string>> time_set;\n    unordered_map<string, int> token_map;\npublic:\n    AuthenticationManager(int timeToLive):ttl(timeToLive) { }\n    \n    void generate(string tokenId, int currentTime) {\n        token_map[tokenId] = currentTime;\n        time_set.insert({currentTime, tokenId});\n    }\n    \n    void renew(string tokenId, int currentTime) {\n        //if the token is not found, or the token is expired\n        if (token_map.find(tokenId) == token_map.end() ||\n            token_map[tokenId] + ttl <= currentTime ) {\n            return;\n        }\n        time_set.erase({token_map[tokenId], tokenId});\n        time_set.insert({currentTime, tokenId});\n        token_map[tokenId] = currentTime;\n    }\n    \n    int countUnexpiredTokens(int currentTime) {\n        return clean(currentTime - ttl);\n    }\n    \n    int clean(int expired) {\n\n        auto it = time_set.begin();\n        while(!time_set.empty() && it->first <= expired) {\n            token_map.erase(it->second);\n            time_set.erase(it);\n            it = time_set.begin();\n        }\n        return time_set.size();\n    }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n"
  },
  {
    "path": "algorithms/cpp/detectCapital/DetectCapital.cpp",
    "content": "// Source : https://leetcode.com/problems/detect-capital/\n// Author : Hao Chen\n// Date   : 2019-02-04\n\n/***************************************************************************************************** \n *\n * \n * Given a word, you need to judge whether the usage of capitals in it is right or not.\n * \n * We define the usage of capitals in a word to be right when one of the following cases holds:\n * \n * All letters in this word are capitals, like \"USA\".\n * All letters in this word are not capitals, like \"leetcode\".\n * Only the first letter in this word is capital if it has more than one letter, like \"Google\".\n * \n * Otherwise, we define that this word doesn't use capitals in a right way.\n * \n * Example 1:\n * \n * Input: \"USA\"\n * Output: True\n * \n * Example 2:\n * \n * Input: \"FlaG\"\n * Output: False\n * \n * Note:\n * The input will be a non-empty word consisting of uppercase and lowercase latin letters.\n ******************************************************************************************************/\nclass Solution {\n    bool is_lower(char ch) {\n        return ch >='a' && ch <='z';\n    }\n    bool is_upper(char ch) {\n        return ch >='A' && ch <='Z';\n    }\n    bool is_alpha(char ch) {\n        return is_lower(ch) || is_upper(ch);\n    }\npublic:\n    bool detectCapitalUse(string word) {\n        bool all_upper = true, all_lower = true, first = is_upper(word[0]);\n        for(int i=1; i<word.size(); i++) {\n            if (is_lower(word[i])) all_upper = false;\n            if (is_upper(word[i])) all_lower = false;\n        }\n        return all_lower || first && all_upper; \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/determineColorOfAChessboardSquare/DetermineColorOfAChessboardSquare.cpp",
    "content": "// Source : https://leetcode.com/problems/determine-color-of-a-chessboard-square/\n// Author : Hao Chen\n// Date   : 2021-04-06\n\n/***************************************************************************************************** \n *\n * You are given coordinates, a string that represents the coordinates of a square of the chessboard. \n * Below is a chessboard for your reference.\n * \n * Return true if the square is white, and false if the square is black.\n * \n * The coordinate will always represent a valid chessboard square. The coordinate will always have the \n * letter first, and the number second.\n * \n * Example 1:\n * \n * Input: coordinates = \"a1\"\n * Output: false\n * Explanation: From the chessboard above, the square with coordinates \"a1\" is black, so return false.\n * \n * Example 2:\n * \n * Input: coordinates = \"h3\"\n * Output: true\n * Explanation: From the chessboard above, the square with coordinates \"h3\" is white, so return true.\n * \n * Example 3:\n * \n * Input: coordinates = \"c7\"\n * Output: false\n * \n * Constraints:\n * \n * \tcoordinates.length == 2\n * \t'a' <= coordinates[0] <= 'h'\n * \t'1' <= coordinates[1] <= '8'\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool squareIsWhite(string coordinates) {\n        return (coordinates[0] - 'a'+1) % 2 != (coordinates[1] - '0') % 2;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/\n// Author : Arshdeep Singh\n// Date   : 2021-10-01\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\nprivate:\n    int diameter;\n    int maxDepth(TreeNode* root) {\n        if(root==NULL) return 0;\n        int left = maxDepth(root->left);\n        int right = maxDepth(root->right);\n        diameter = max(diameter, left + right);\n        return 1 + max(left, right);\n    }\npublic:\n    int diameterOfBinaryTree(TreeNode* root) {\n        diameter = 0;\n        maxDepth(root);\n        return diameter;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/differentWaysToAddParentheses/DifferentWaysToAddParentheses.cpp",
    "content": "// Source : https://leetcode.com/problems/different-ways-to-add-parentheses/\n// Author : Hao Chen\n// Date   : 2015-08-15\n\n/********************************************************************************** \n * \n * Given a string of numbers and operators, return all possible results from computing \n * all the different possible ways to group numbers and operators. The valid operators \n * are +, - and *.\n * \n * Example 1\n * Input: \"2-1-1\". \n * ((2-1)-1) = 0\n * (2-(1-1)) = 2\n * Output: [0, 2]\n * \n * Example 2\n * Input: \"2*3-4*5\" \n * (2*(3-(4*5))) = -34\n * ((2*3)-(4*5)) = -14\n * ((2*(3-4))*5) = -10\n * (2*((3-4)*5)) = -10\n * (((2*3)-4)*5) = 10\n * Output: [-34, -14, -10, -10, 10] \n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test \n * cases.\n *               \n **********************************************************************************/\n#include <stdlib.h>\n#include <ctype.h>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <map>\nusing namespace std;\n\n\nbool isOperator(char ch){\n    return (ch=='+' || ch=='-' || ch=='*');\n}\n\n\n//Divide & Conque  - recursive way\nvector<int> diffWaysToCompute(string input) {\n    //if the result has been cacluated, then just get it from the cache and return \n    static map< string, vector<int> > cache;\n    if ( cache.find(input) != cache.end() ){\n        return cache[input];\n    }\n\n\n    vector<int> result; \n    for (int i=0; i<input.size(); i++){\n        char ch = input[i];\n        if (isOperator(ch)){\n            //split the input to two parts, left part and right part \n            //And recursively invoke this function.\n            string left  = input.substr(0, i);\n            string right = input.substr(i+1);\n            vector<int> lv = diffWaysToCompute(left);\n            vector<int> rv = diffWaysToCompute(right);\n\n            //merge two result to one\n            for(int li=0; li<lv.size(); li++) {\n                for(int ri=0; ri<rv.size(); ri++) {\n                    switch(ch){\n                        case '+' : result.push_back(lv[li] + rv[ri]); break;\n                        case '-' : result.push_back(lv[li] - rv[ri]); break;\n                        case '*' : result.push_back(lv[li] * rv[ri]); break;\n                    }\n                }\n            }\n\n        }\n    }\n    //if we cannot find the \"operator\" in input, \n    //which means, it is a number, just put the number into the result. \n    if (result.size()==0) {\n        result.push_back(atoi(input.c_str()));\n    }\n    \n    //cache the result, key = input, value = result;\n    cache[input] = result;\n\n    return result;\n}\n\nvoid printVector(vector<int>& v) {\n    cout << \"[\";\n    for(int i=0; i<v.size(); i++) {\n        cout << v[i] << (i==v.size()-1 ? \"]\":\", \");\n    }\n    cout << endl;\n}\n\nint main(int argc, char**argv) \n{\n    string exp = \"2*3-4*5\";\n    if ( argc > 1 ){\n        exp = argv[1];\n    }\n    vector<int> v = diffWaysToCompute(exp);\n    cout << exp << endl;\n    printVector(v);\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/distinctSubsequences/distinctSubsequences.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/distinct-subsequences/\n// Author : Hao Chen\n// Date   : 2014-07-06\n\n/***************************************************************************************************** \n *\n * Given a string S and a string T, count the number of distinct subsequences of S which equals T.\n * \n * A subsequence of a string is a new string which is formed from the original string by deleting some \n * (can be none) of the characters without disturbing the relative positions of the remaining \n * characters. (ie, \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not).\n * \n * Example 1:\n * \n * Input: S = \"rabbbit\", T = \"rabbit\"\n * Output: 3\n * Explanation:\n * \n * As shown below, there are 3 ways you can generate \"rabbit\" from S.\n * (The caret symbol ^ means the chosen letters)\n * \n * rabbbit\n * ^^^^ ^^\n * rabbbit\n * ^^ ^^^^\n * rabbbit\n * ^^^ ^^^\n * \n * Example 2:\n * \n * Input: S = \"babgbag\", T = \"bag\"\n * Output: 5\n * Explanation:\n * \n * As shown below, there are 5 ways you can generate \"bag\" from S.\n * (The caret symbol ^ means the chosen letters)\n * \n * babgbag\n * ^^ ^\n * babgbag\n * ^^    ^\n * babgbag\n * ^    ^^\n * babgbag\n *   ^  ^^\n * babgbag\n *     ^^^\n * \n ******************************************************************************************************/\n#include <stdlib.h>\n#include <time.h>\n#include <string.h>\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\nusing namespace std;\n\n//=====================\n// Dynamic Programming\n//=====================\n//\n//  The idea as below:\n//\n//     Considering m[i][j] means the distance from T[i] to S[j], and add the empty \"\" case, then,\n//\n//     A) Initialization for empty case:  m[0][j] = 1;\n//\n//     B) Calculation \n//\n//        a) Target-len > Source-len cannot found any substring\n//           i > j : m[i][j] = 0;   \n//\n//        b) if not equal, take the value of T[i] => S[j-1] (e.g. [\"ra\" => \"rabb\"] =[\"ra\" => \"rab\"] )\n//           S[j] != T[i] :  m[i][j] = m[i][j-1]\n//\n//        c) if equal. (e.g.  [\"rab\" => \"rabb\"] = [\"rab\" =>\"rab\"] + [\"ra\" => \"rab\"] ) \n//           S[j] == T[i] :  m[i][j] = m[i][j-1] + m[i-1][j-1]\n//\n//  1) Initialize a table as below   \n//       \"\"  r  a  b  b  b  i  t\n//    \"\"  1  1  1  1  1  1  1  1\n//    r     \n//    b   \n//    t  \n//\n//  2) Calculation\n//       \"\"  r  a  b  b  b  i  t\n//    \"\"  1  1  1  1  1  1  1  1\n//    r   0  1  1  1  1  1  1  1 \n//    b   0  0  0  1  2  3  3  3\n//    t   0  0  0  0  0  0  0  3\n//\nint numDistinct1(string S, string T) {\n    vector< vector<int> > m(T.size()+1, vector<int>(S.size()+1));\n    \n    for (int i=0; i<m.size(); i++){\n        for (int j=0; j<m[i].size(); j++){\n\n            if (i==0){\n                m[i][j] = 1;\n                continue;\n            }\n            if ( i>j ) {\n                m[i][j] = 0;\n                continue;\n            }\n            if (S[j-1] == T[i-1]){\n                m[i][j] = m[i][j-1] + m[i-1][j-1];\n            } else {\n                m[i][j] = m[i][j-1] ;\n            }\n        }\n    }\n    return m[T.size()][S.size()];\n}\n\n\n//=====================\n// Dynamic Programming\n//=====================\n//\n//  The idea here is an optimization of above idea \n//  (It might be difficult to understand if you don't understand the above idea)\n//\n//    For example:\n//\n//      S = \"abbbc\"  T=\"abb\"\n//      posMap = { [a]={0}, [b]={2,1} } <- the map of T's every char.\n//      numOfSubSeq = {1, 0, 0, 0 }\n//\n//      S[0] is 'a', pos is 0,  numOfSubSeq = {1, 0+1, 0, 0};\n//\n//      S[1] is 'b', pos is 2,  numOfSubSeq = {1, 1, 0, 0+0};\n//                   pos is 1,  numOfSubSeq = {1, 1, 0+1, 0};\n//\n//      S[2] is 'b', pos is 2,  numOfSubSeq = {1, 1, 1, 0+1};\n//                   pos is 1,  numOfSubSeq = {1, 1, 1+1, 1};\n//\n//      S[3] is 'b', pos is 2,  numOfSubSeq = {1, 1, 2, 2+1};\n//                   pos is 1,  numOfSubSeq = {1, 1, 1+2, 3};\n//\n//      S[4] is 'c', not found, numOfSubSeq = {1, 1, 3, 3};\n// \n//\nint numDistinct2(string S, string T) {\n\n    map< char, vector<int> > pos_map;\n    int len = T.size();\n    vector<int> numOfSubSeq(len+1);\n    numOfSubSeq[0] = 1;\n\n    for (int i=len-1; i>=0; i--){\n        pos_map[T[i]].push_back(i);\n    }\n    \n    for (int i=0; i<S.size(); i++){\n        char ch = S[i];\n        if ( pos_map.find(ch) != pos_map.end() ) {\n            for (int j=0; j<pos_map[ch].size(); j++) {\n                int pos = pos_map[ch][j];\n                numOfSubSeq[pos+1] += numOfSubSeq[pos];\n            } \n        }\n    }\n\n    return numOfSubSeq[len];\n}\n\n\n//random invoker\nint numDistinct(string S, string T) {\n    srand(time(0));\n    if (rand()%2){\n        cout << \"-----Dynamic Programming Method One-----\" << endl;\n        return numDistinct1(S,T);\n    }\n    cout << \"-----Dynamic Programming Method Two-----\" << endl;\n    return numDistinct2(S,T);\n}\n\n\nint main(int argc, char** argv)\n{\n    string s = \"rabbbit\";\n    string t = \"rabbit\";\n    if (argc>2){\n        s = argv[1];\n        t = argv[2];\n    }\n    cout << \"S=\\\"\" << s << \"\\\"  T=\\\"\" << t << \"\\\"\" << endl;\n    cout << \"numDistinct = \" << numDistinct(s, t) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/distributeCoinsInBinaryTree/DistributeCoinsInBinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/distribute-coins-in-binary-tree/\n// Author : Hao Chen\n// Date   : 2019-03-29\n\n/***************************************************************************************************** \n *\n * Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there \n * are N coins total.\n * \n * In one move, we may choose two adjacent nodes and move one coin from one node to another.  (The \n * move may be from parent to child, or from child to parent.)\n * \n * Return the number of moves required to make every node have exactly one coin.\n * \n * Example 1:\n * \n * Input: [3,0,0]\n * Output: 2\n * Explanation: From the root of the tree, we move one coin to its left child, and one coin to its \n * right child.\n * \n * Example 2:\n * \n * Input: [0,3,0]\n * Output: 3\n * Explanation: From the left child of the root, we move two coins to the root [taking two moves].  \n * Then, we move one coin from the root of the tree to the right child.\n * \n * Example 3:\n * \n * Input: [1,0,2]\n * Output: 2\n * \n * Example 4:\n * \n * Input: [1,0,0,null,3]\n * Output: 4\n * \n * Note:\n * \n * \t1<= N <= 100\n * \t0 <= node.val <= N\n * \n ******************************************************************************************************/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int distributeCoins(TreeNode* root) {\n        int result = 0;\n        dfs(root, result);\n        return result;\n    }\n\n    //\n    // if a node has 0 coin, which means one move from its parent.\n    //               1 coin, which means zero move from its parent.\n    //               N coins, which means N-1 moves to its parent.\n    //\n    // So, we can simply know, the movement = coins -1.\n    // - negative number means the the coins needs be moved in.\n    // - positive number means the the coins nees be moved out.\n    //\n    // A node needs to consider the movement requests from both its left side and right side.\n    // and need to calculate the coins after left and right movement.\n    //\n    // So, the node coins  = my conins - the coins move out + the coins move in.\n    //\n    // Then we can have to code as below.\n    //\n    int dfs(TreeNode* root, int& result) {\n        if (root == NULL) return 0;\n\n        int left_move = dfs(root->left, result);\n        int right_move = dfs(root->right, result);\n        result += (abs(left_move) + abs(right_move));\n\n        // the coin after movement: coins = root->val +left_move + right_move\n        // the movement needs:  movement = coins - 1\n        return root->val + left_move + right_move - 1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/divideTwoInt/divideTwoInt.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/divide-two-integers/\n// Author : Hao Chen\n// Date   : 2014-06-20\n\n/********************************************************************************** \n* \n* Divide two integers without using multiplication, division and mod operator.\n* \n* If it is overflow, return MAX_INT. \n*\n**********************************************************************************/\n\n#include <stdio.h>\n#include <string.h>\n#include <iostream>\nusing namespace std;\n\n#define INT_MAX     2147483647\n#define INT_MIN     (-INT_MAX - 1)\n\nint divide(int dividend, int divisor) {\n\n    int sign = (float)dividend / divisor > 0 ? 1 : -1;\n    unsigned int dvd = dividend > 0 ? dividend : -dividend;\n    unsigned int dvs = divisor > 0 ? divisor : -divisor;\n\n    unsigned int bit_num[33];\n    unsigned int i=0;\n    long long d = dvs;\n    bit_num[i] = d;\n    while( d <= dvd ){\n        bit_num[++i] = d = d << 1;\n    }\n    i--;\n\n    unsigned int result = 0;\n    while(dvd >= dvs){\n        if (dvd >= bit_num[i]){\n            dvd -= bit_num[i];\n            result += (1<<i);\n        }else{\n            i--;\n        }\n    }\n\n    //becasue need to return `int`, so we need to check it is overflowed or not.\n    if ( result > INT_MAX && sign > 0 ) {\n        return INT_MAX;\n    }\n    return (int)result * sign;\n}\n\n\nint main()\n{\n    cout << \"0/2=\" << divide(0, 2) << endl;\n    cout << \"10/2=\" << divide(10, 2) << endl;\n    cout << \"10/3=\" << divide(10, 3) << endl;\n    cout << \"10/5=\" << divide(10, 5) << endl;\n    cout << \"10/7=\" << divide(10, 7) << endl;\n    cout << \"10/10=\" << divide(10, 10) << endl;\n    cout << \"10/11=\" << divide(10, 11) << endl;\n    cout << \"-1/1=\" << divide(1, -1) << endl;\n    cout << \"1/-1=\" << divide(1, -1) << endl;\n    cout << \"-1/-1=\" << divide(-1, -1) << endl;\n    cout << \"2147483647/1=\" << divide(2147483647, 1) << endl;\n    cout << \"-2147483647/1=\" << divide(-2147483647, 1) << endl;\n    cout << \"2147483647/-1=\" << divide(2147483647, -1) << endl;\n    cout << \"-2147483647/-1=\" << divide(-2147483647, -1) << endl;\n    cout << \"2147483647/2=\" << divide(2147483647, 2) << endl;\n    cout << \"2147483647/10=\" << divide(2147483647, 10) << endl;\n    cout << \"-2147483648/1=\" << divide(-2147483648, 1) << endl;\n    cout << \"-2147483648/-1=\" << divide(-2147483648, -1) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/dungeonGame/dungeonGame.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/dungeon-game/\n// Author : Hao Chen\n// Date   : 2015-01-16\n\n/********************************************************************************** \n * \n * The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. \n * The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned \n * in the top-left room and must fight his way through the dungeon to rescue the princess. \n *\n * The knight has an initial health point represented by a positive integer. \n * If at any point his health point drops to 0 or below, he dies immediately. \n *\n * Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; \n * other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).\n * In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. \n * \n * Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.\n * For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path \n * RIGHT-> RIGHT -> DOWN -> DOWN.\n * \n *   \n *   +------+------+------+\n *   |      |      |      |\n *   | -2(K)|  -3  |  -3  |\n *   |      |      |      |\n *   +--------------------+\n *   |      |      |      |\n *   |  -5  | -10  |   1  |\n *   |      |      |      |\n *   +--------------------+\n *   |      |      |      |\n *   |  10  |  30  | -5(P)|\n *   |      |      |      |\n *   +------+------+------+\n *   \n * \n * Notes:\n * \n * The knight's health has no upper bound.\n * Any room can contain threats or power-ups, \n * even the first room the knight enters and the bottom-right room where the princess is imprisoned.  \n * \n * Credits:Special thanks to @stellari for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\nclass Solution {\n    public:\n        int calculateMinimumHP(vector<vector<int> > &dungeon) {\n            int row = dungeon.size();\n            int col = row>0 ? dungeon[0].size() : 0;\n            if (row<=0 || col <=0) return 0;\n\n            //dp[r][c] = min( max( dp[r+1][c] - dungeon[r][c], 1), max( dp[r][c+1] - dungeon[r][c], 1) );\n            int dp[row][col];\n            memset(dp, 0, sizeof(dp));\n\n            for(int r=row-1; r>=0; r--){\n                for (int c=col-1; c>=0; c--){\n\n                    /*if (r == row - 1 && c == col - 1 ){\n                      dp[r][c] = max(1 - dungeon[r][c], 1);\n                      }else if ( r == row - 1 ) {\n                      dp[r][c] = max(dp[r][c+1] - dungeon[r][c], 1);\n                      }else if ( c == col - 1 ) {\n                      dp[r][c] = max(dp[r+1][c] - dungeon[r][c], 1);\n                      }else{\n                      dp[r][c] = min( max( dp[r+1][c] - dungeon[r][c], 1), max( dp[r][c+1] - dungeon[r][c], 1) );\n                      }*/\n\n                    if (r == row - 1 && c == col - 1 ){\n                        dp[r][c] = max(1 - dungeon[r][c], 1);\n                    }else{ \n                        int h1 = ( c == col-1  ) ? INT_MAX : max(dp[r][c+1] - dungeon[r][c], 1);\n                        int h2 =  ( r == row-1 ) ? INT_MAX : max(dp[r+1][c] - dungeon[r][c], 1);\n\n                        dp[r][c] = min( h1, h2 );\n                    }\n\n                }\n            }\n\n            return dp[0][0];\n\n\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/editDistance/editDistance.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/edit-distance/\n// Author : Hao Chen\n// Date   : 2014-08-22\n\n/********************************************************************************** \n* \n* Given two words word1 and word2, find the minimum number of steps required to \n* convert word1 to word2. (each operation is counted as 1 step.)\n* \n* You have the following 3 operations permitted on a word:\n* \n* a) Insert a character\n* b) Delete a character\n* c) Replace a character\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\n/*\n *  Dynamic Programming\n *\n *    Definitaion\n *\n *        m[i][j] is minimal distance from word1[0..i] to word2[0..j]\n *\n *    So, \n *\n *        1) if word1[i] == word2[j], then m[i][j] == m[i-1][j-1].\n *\n *        2) if word1[i] != word2[j], then we need to find which one below is minimal:\n *\n *             min( m[i-1][j-1], m[i-1][j],  m[i][j-1] )\n *            \n *             and +1 - current char need be changed.\n *\n *        Let's take a look  m[1][2] :  \"a\" => \"ab\" \n *\n *               +---+  +---+                                         \n *        ''=> a | 1 |  | 2 | '' => ab                                \n *               +---+  +---+                                         \n *                                                                    \n *               +---+  +---+                                         \n *        a => a | 0 |  | 1 | a => ab                                 \n *               +---+  +---+                                         \n *                                                            \n *        To know the minimal distance `a => ab`, we can get it from one of the following cases:\n *\n *            1) delete the last char in word1,  minDistance( '' => ab ) + 1                                                             \n *            2) delete the last char in word2,  minDistance(  a => a ) + 1                                                             \n *            3) change the last char,           minDistance( '' => a ) + 1                                                             \n *                                                            \n *  \n *    For Example:\n *\n *        word1=\"abb\", word2=\"abccb\"\n *\n *        1) Initialize the DP matrix as below:\n *\n *               \"\" a b c c b\n *            \"\" 0  1 2 3 4 5\n *            a  1\n *            b  2\n *            b  3\n *\n *        2) Dynamic Programming\n *\n *               \"\" a b c c b\n *            \"\"  0 1 2 3 4 5\n *            a   1 0 1 2 3 4 \n *            b   2 1 0 1 2 3\n *            b   3 2 1 1 2 2\n *\n */\nint min(int x, int y, int z) {\n    return std::min(x, std::min(y,z));\n}\n\nint minDistance(string word1, string word2) {\n    int n1 = word1.size();     \n    int n2 = word2.size();     \n    if (n1==0) return n2;\n    if (n2==0) return n1;\n    vector< vector<int> > m(n1+1, vector<int>(n2+1));\n    for(int i=0; i<m.size(); i++){\n        m[i][0] = i;\n    }\n    for (int i=0; i<m[0].size(); i++) {\n        m[0][i]=i;\n    }\n\n    //Dynamic Programming\n    int row, col;\n    for (row=1; row<m.size(); row++) {\n        for(col=1; col<m[row].size(); col++){\n            if (word1[row-1] == word2[col-1] ){\n                m[row][col] = m[row-1][col-1];\n            }else{\n                int minValue = min(m[row-1][col-1], m[row-1][col],  m[row][col-1]);\n                m[row][col] = minValue + 1;\n            }\n        }\n    }\n\n    return m[row-1][col-1];\n}\n\n\nint main(int argc, char**argv)\n{\n    string word1=\"abb\", word2=\"abccb\";\n    if (argc>2){\n        word1 = argv[1];\n        word2 = argv[2];\n    }\n\n    int steps = minDistance(word1, word2);\n\n    cout << word1 << \", \" << word2 << \" : \" << steps << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/eggDropWith2EggsAndNFloors/EggDropWith2EggsAndNFloors.cpp",
    "content": "// Source : https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/\n// Author : Hao Chen\n// Date   : 2021-11-15\n\n/***************************************************************************************************** \n *\n * You are given two identical eggs and you have access to a building with n floors labeled from 1 to \n * n.\n * \n * You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher \n * than f will break, and any egg dropped at or below floor f will not break.\n * \n * In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the \n * egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in \n * future moves.\n * \n * Return the minimum number of moves that you need to determine with certainty what the value of f is.\n * \n * Example 1:\n * \n * Input: n = 2\n * Output: 2\n * Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.\n * If the first egg breaks, we know that f = 0.\n * If the second egg breaks but the first egg didn't, we know that f = 1.\n * Otherwise, if both eggs survive, we know that f = 2.\n * \n * Example 2:\n * \n * Input: n = 100\n * Output: 14\n * Explanation: One optimal strategy is:\n * - Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting\n *   from floor 1 and going up one at a time to find f within 7 more drops. Total drops is 1 + 7 = 8.\n * - If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is \n * between 9\n *   and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 \n * more\n *   drops. Total drops is 2 + 12 = 14.\n * - If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors \n * 34, 45,\n *   55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\n * Regardless of the outcome, it takes at most 14 drops to determine f.\n * \n * Constraints:\n * \n * \t1 <= n <= 1000\n ******************************************************************************************************/\n\n/*\n 1 floor  - 1 attemp\n 2 floors - 2 attemps\n 3 floors - 2 attemps\n 4 floors - 3 attemps\n 5 floors - 3 attemps\n 6 floors - 3 attemps\n 7 floors - 4 attemps\n ...\n 11 floors - 5 attemps\n ...\n 16 floors - 6 attemps\n ...\n 22 floors - 7 attemps\n ...\n \n we can see: \n floor(1) = 1\n floor(2) = 2\n floor(4) = 3\n floor(7) = 4\n floor(11) = 5\n floor(16) = 6\n floor(22) = 7\n ...\n \n */\n\n\nclass Solution {\npublic:\n    int twoEggDrop(int n) {\n        int c = 1, i=1;\n        while(c < n) {\n            c += i;\n            i++;\n        }\n        return c==n ? i : i-1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/eliminationGame/EliminationGame.cpp",
    "content": "// Source : https://leetcode.com/problems/elimination-game\n// Author : Hao Chen\n// Date   : 2016-09-07-\n\n/********************************************************************************** \n * \n * There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other \n * number afterward until you reach the end of the list.\n * \n * Repeat the previous step again, but this time from right to left, remove the right most number and every other number \n * from the remaining numbers.\n * \n * We keep repeating the steps again, alternating left to right and right to left, until a single number remains.\n * \n * Find the last number that remains starting with a list of length n.\n * \n * Example:\n * \n * Input:\n * n = 9,\n * 1 2 3 4 5 6 7 8 9\n * 2 4 6 8\n * 2 6\n * 6\n * \n * Output:\n * 6\n**********************************************************************************/\n\nclass Solution {\npublic:\n    int lastRemaining(int n) {\n        int start = 1, step = 1;\n        while (n > 1) {\n            start += step + (n-2)/2 * 2*step;\n            n /= 2;\n            step *= -2;\n        }\n        return start;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/equalSumArraysWithMinimumNumberOfOperations/EqualSumArraysWithMinimumNumberOfOperations.cpp",
    "content": "// Source : https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/\n// Author : Hao Chen\n// Date   : 2021-03-24\n\n/***************************************************************************************************** \n *\n * You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in \n * the arrays are between 1 and 6, inclusive.\n * \n * In one operation, you can change any integer's value in any of the arrays to any value between 1 \n * and 6, inclusive.\n * \n * Return the minimum number of operations required to make the sum of values in nums1 equal to the \n * sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays \n * equal.\n * \n * Example 1:\n * \n * Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\n * Output: 3\n * Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are \n * 0-indexed.\n * - Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n * - Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n * - Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n * \n * Example 2:\n * \n * Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\n * Output: -1\n * Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make \n * them equal.\n * \n * Example 3:\n * \n * Input: nums1 = [6,6], nums2 = [1]\n * Output: 3\n * Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are \n * 0-indexed. \n * - Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n * - Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n * - Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n * \n * Constraints:\n * \n * \t1 <= nums1.length, nums2.length <= 10^5\n * \t1 <= nums1[i], nums2[i] <= 6\n ******************************************************************************************************/\n\nclass Solution { \nprivate:\n    void print(vector<int>& n) {\n        cout <<\"[\";\n        for(int i=0; i< n.size() - 1; i++) {\n            cout << n[i] << \",\";\n        }\n        cout << n[n.size()-1] << \"]\" <<endl;\n    }\nprivate:\n    int minOpsBySort(int gaps, vector<int>& small, vector<int>& big) {\n        \n        sort(small.begin(), small.end());\n        sort(big.begin(), big.end());\n        \n        int op = 0;\n        int left = 0, right = big.size() -1;\n        while (gaps >0) {\n            \n            int small_gaps = left < small.size() ? 6 - small[left] : 0;\n            int big_gaps = right >= 0 ? big[right] - 1 : 0;\n            \n            if (small_gaps > big_gaps) {\n                gaps -= small_gaps;\n                left++;\n            }else{\n                gaps -= big_gaps;\n                right--;\n            }\n            op++;\n        }\n        return op;\n    }\n    \n    int minOpsByCnt1(int gaps, vector<int>& small, vector<int>& big) {\n        int small_cnt[6] = {0} , big_cnt[6] = {0};\n        for (auto& n : small) small_cnt[n-1]++;\n        for (auto& n : big) big_cnt[n-1]++;\n        \n        int op = 0;\n        int left = 0, right = 5; \n        \n        while( gaps > 0 ) {\n            while (left < 6 && small_cnt[left] == 0 ) left++;\n            while ( right >=0 && big_cnt[right] == 0 ) right--;\n            int small_gaps = left < 6 ? 6 - (left + 1) : 0;\n            int big_gaps = right >= 0 ? right : 0;\n            \n            if (small_gaps > big_gaps) {\n                gaps -= small_gaps;\n                small_cnt[left]--;\n            }else{\n                gaps -= big_gaps;\n                big_cnt[right]--;\n            }\n            op++;\n        }\n        return op;\n    }\n    \n    int minOpsByCnt2(int gaps, vector<int>& small, vector<int>& big) {\n        int cnt[6] = {0};\n        for (auto& n : small) cnt[6-n]++;\n        for (auto& n : big) cnt[n-1]++;\n        \n        int ops = 0;\n        for (int i=5 ; i >= 0 && gaps > 0; i--) {\n            if (cnt[i] == 0) continue;\n            if (cnt[i] * i > gaps) {\n                ops +=  (gaps / i  + (gaps % i ? 1:0) ) ;\n                break;\n            }\n            gaps -= cnt[i] * i;\n            ops += cnt[i];\n        }\n \n        return ops;\n    }\npublic:\n    int minOperations(vector<int>& nums1, vector<int>& nums2) {\n        int len1 = nums1.size(), len2 = nums2.size();\n        if ( len1 > 6*len2 || len2 > 6*len1) return -1;\n        \n        int sum1 = 0 , sum2 = 0;\n        for (auto& n : nums1) sum1 += n;\n        for (auto& n : nums2) sum2 += n;\n        \n        if (sum1 > sum2) {\n            swap(sum1, sum2);\n            swap(nums1, nums2);\n        }\n        int gaps = sum2 - sum1;\n        if (gaps == 0) return 0;\n        return minOpsByCnt2(gaps, nums1, nums2); //104ms\n        return minOpsByCnt1(gaps, nums1, nums2); //108ms\n        return minOpsBySort(gaps, nums1, nums2); //140ms\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/evaluateDivision/EvaluateDivision.cpp",
    "content": "// Source : https://leetcode.com/problems/evaluate-division/\n// Author : Hao Chen\n// Date   : 2016-11-05\n\n/*************************************************************************************** \n *\n * Equations are given in the format A / B = k, where  A and B are variables \n * represented as strings, and k is a real number (floating point number). Given some \n * queries, return the answers. If the answer does not exist, return -1.0.\n * \n * Example:\n * Given  a / b = 2.0, b / c = 3.0. queries are:  a / c = ?,  b / a = ?, a / e = ?,  a \n * / a = ?, x / x = ? . return  [6.0, 0.5, -1.0, 1.0, -1.0 ].\n * \n * The input is:  vector<pair<string, string>> equations, vector<double>& values, \n * vector<pair<string, string>> queries , where equations.size() == values.size(), and \n * the values are positive. This represents the equations. Return  vector<double>.\n * \n * According to the example above:\n * equations = [ [\"a\", \"b\"], [\"b\", \"c\"] ],\n * values = [2.0, 3.0],\n * queries = [ [\"a\", \"c\"], [\"b\", \"a\"], [\"a\", \"e\"], [\"a\", \"a\"], [\"x\", \"x\"] ]. \n * \n * The input is always valid. You may assume that evaluating the queries will result in \n * no division by zero and there is no contradiction.\n ***************************************************************************************/\n\nclass Solution {\nprivate:\n    bool dfs( unordered_map<string, unordered_map<string, double>>& m, \n              unordered_map<string, bool>& visited, \n              string& start, string& end, double& res  ) {\n                 \n        if ( m.find(start) == m.end() || m.find(end) == m.end() ) return false;\n        if ( start == end ) return true;\n        \n        for (auto it = m[start].begin(); it != m[start].end(); ++it) {\n           \n            auto key = it->first;\n            auto value = it->second;\n            \n            // already visited, skip it.\n            if (visited.find(key) != visited.end() ) {\n                continue;\n            }\n            \n            visited[key] = true;\n            double old = res;\n            res *= value;\n            \n            if (dfs(m, visited, key, end, res)) {\n                return true;\n            }\n            //didn't find the result, reset the current result, and go to next one\n            res = old;\n            visited.erase(key);\n        }\n        \n        return false;\n    }\npublic:\n    vector<double> calcEquation(vector<pair<string, string>> equations, \n                                vector<double>& values, \n                                vector<pair<string, string>> queries) {\n        \n        unordered_map<string, unordered_map<string, double>> m;\n        for(int i=0; i<equations.size(); i++) {\n           auto first = equations[i].first;\n           auto second = equations[i].second;\n           m[first][second] = values[i];\n           m[second][first] = 1.0 / values[i];\n        }\n        \n        \n        vector<double> result;\n        for(auto q : queries) {\n            string start = q.first;\n            string end = q.second;\n            \n            unordered_map<string, bool> visited;\n            visited[start] = true;\n            double res = 1.0;\n            \n            if(dfs(m, visited, start, end, res)) {\n                result.push_back(res);\n            } else {\n                result.push_back(-1.0);\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/evaluateReversePolishNotation/evaluateReversePolishNotation.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/\n// Author : Hao Chen\n// Date   : 2014-06-16\n\n/********************************************************************************** \n* \n* Evaluate the value of an arithmetic expression in Reverse Polish Notation.\n* \n* Valid operators are +, -, *, /. Each operand may be an integer or another expression.\n* \n* Some examples:\n* \n*   [\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n*   [\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <string>\n#include <vector>\n#include <iostream>\nusing namespace std;\n\n\nclass Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        int i =0;\n        bool err = false;\n        vector<int> exp;\n        for (int i=0; i<tokens.size() && !err; i++ ){\n            if (isNum(tokens[i])) {\n                exp.push_back(value);\n            } else if( isOp(tokens[i])==true ) {\n                if (exp.size() < 2) {\n                    return 0; //ERROR\n                }\n                int lhs, rhs;\n                rhs = exp.back();\n                exp.pop_back();\n                lhs = exp.back();\n                exp.pop_back();\n\n                int evlValue;\n                if (tokens[i]==\"+\"){\n                    evlValue = lhs + rhs;    \n                }else if (tokens[i]==\"-\"){\n                    evlValue = lhs - rhs;\n                }else if (tokens[i]==\"*\"){\n                    evlValue = lhs * rhs;\n                }else if (tokens[i]==\"/\"){\n                    evlValue = lhs / rhs;\n                }\n\n                exp.push_back(evlValue);\n\n            }else {\n                return 0; //ERROR \n            }\n        }\n\n        if (exp.size()==1){\n            return exp.back();\n        }\n        return 0;        \n\n    }\n\nprivate:\n    long value;\n\n    bool isOp(string &op) {\n        return (op==\"+\" || op==\"-\" || op==\"*\" || op==\"/\");\n    }\n\n    bool isNum(string &num) {\n        char *end;\n        value = strtol(num.c_str(), &end, 10); \n        if (end == num.c_str() || *end != '\\0' || errno == ERANGE){\n            return false;\n        }\n        return true;\n    }\n};\n\n\nint main()\n{\n    Solution s;\n    char exps[5][3] = {\"42\", \"9\", \"6\", \"-\", \"+\"};\n    vector<string> expression;\n\n    cout << \"Expression: \\n    \";\n    for (int i=0; i<5; i++){\n        expression.push_back(exps[i]);\n        cout << exps[i] << \" \";\n    }\n    cout << endl;\n    cout << s.evalRPN(expression)<<endl;;\n\n    char exps2[5][3] =  {\"2\", \"1\", \"+\", \"3\", \"*\"};\n    expression.clear();\n\n    cout << \"Expression: \\n    \";\n    for (int i=0; i<5; i++){\n        expression.push_back(exps2[i]);\n        cout << exps2[i] << \" \";\n    }\n    cout << endl;\n    cout << s.evalRPN(expression)<<endl;\n\n\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/evaluateTheBracketPairsOfAString/EvaluateTheBracketPairsOfAString.cpp",
    "content": "// Source : https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * You are given a string s that contains some bracket pairs, with each pair containing a non-empty \n * key.\n * \n * \tFor example, in the string \"(name)is(age)yearsold\", there are two bracket pairs that \n * contain the keys \"name\" and \"age\".\n * \n * You know the values of a wide range of keys. This is represented by a 2D string array knowledge \n * where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.\n * \n * You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains \n * some key keyi, you will:\n * \n * \tReplace keyi and the bracket pair with the key's corresponding valuei.\n * \tIf you do not know the value of the key, you will replace keyi and the bracket pair with a \n * question mark \"?\" (without the quotation marks).\n * \n * Each key will appear at most once in your knowledge. There will not be any nested brackets in s.\n * \n * Return the resulting string after evaluating all of the bracket pairs.\n * \n * Example 1:\n * \n * Input: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\n * Output: \"bobistwoyearsold\"\n * Explanation:\n * The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\n * The key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\n * \n * Example 2:\n * \n * Input: s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\n * Output: \"hi?\"\n * Explanation: As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".\n * \n * Example 3:\n * \n * Input: s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\n * Output: \"yesyesyesaaa\"\n * Explanation: The same key can appear multiple times.\n * The key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\n * Notice that the \"a\"s not in a bracket pair are not evaluated.\n * \n * Example 4:\n * \n * Input: s = \"(a)(b)\", knowledge = [[\"a\",\"b\"],[\"b\",\"a\"]]\n * Output: \"ba\"\n * \n * Constraints:\n * \n * \t1 <= s.length <= 10^5\n * \t0 <= knowledge.length <= 10^5\n * \tknowledge[i].length == 2\n * \t1 <= keyi.length, valuei.length <= 10\n * \ts consists of lowercase English letters and round brackets '(' and ')'.\n * \tEvery open bracket '(' in s will have a corresponding close bracket ')'.\n * \tThe key in each bracket pair of s will be non-empty.\n * \tThere will not be any nested bracket pairs in s.\n * \tkeyi and valuei consist of lowercase English letters.\n * \tEach keyi in knowledge is unique.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    bool isBracket(char c) {\n        return c=='(' || c == ')';\n    }\npublic:\n    string evaluate(string s, vector<vector<string>>& knowledge) {\n        unordered_map<string, string> dict;\n        for(auto& k : knowledge) {\n            dict[k[0]] = k[1];\n        }\n        \n        string result;\n        string key;\n        bool meetLeftBracket = false;\n        for(auto& c : s) {\n           \n            if (c == '(') {\n                meetLeftBracket = true;\n            } else if (c == ')') {\n                meetLeftBracket = false;\n                //cout << key << endl;\n                if (dict.find(key) != dict.end()) {\n                    result += dict[key];\n                }else {\n                    result += '?';\n                }\n                key = \"\";\n            } else {\n                if (meetLeftBracket) {\n                    key += c;\n                }else{\n                    result +=c;\n                }\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/excel-sheet-column-number/\n// Author : Hao Chen\n// Date   : 2014-12-29\n\n/********************************************************************************** \n * \n * Related to question Excel Sheet Column Title\n * Given a column title as appear in an Excel sheet, return its corresponding column number.\n * \n * For example:\n *     A -> 1\n *     B -> 2\n *     C -> 3\n *     ...\n *     Z -> 26\n *     AA -> 27\n *     AB -> 28 \n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nstring base26_int2str(long long n) {\n    string ret;\n    while(n>0){\n        char ch = 'A' + (n-1)%26;\n        ret.insert(ret.begin(), ch  );\n        n -= (n-1)%26;\n        n /= 26;\n    }\n    return ret;\n}\n\nlong long base26_str2int(string& s){\n    long long ret=0;\n    for (int i=0; i<s.size(); i++){\n        int n = s[i] - 'A' + 1;\n        ret = ret*26 + n;\n    }\n    return ret;\n}\n\n\nstring titleToNumber(int n) {\n    return base26_str2int(n);\n}\n\nint main(int argc, char**argv)\n{\n    long long n = 27; \n    if (argc>1){\n        n = atoll(argv[1]);\n    }\n    string ns = base26_int2str(n);\n    n = base26_str2int(ns);\n\n    cout << n << \" = \" << ns << endl;\n\n\n    ns = \"ABCDEFG\";\n    if (argc>2){\n        ns = argv[2];\n    }\n    cout << ns << \" = \" << base26_str2int(ns) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/excelSheetColumnTitle/excelSheetColumnTitle.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/excel-sheet-column-title/\n// Author : Hao Chen\n// Date   : 2014-12-25\n\n/********************************************************************************** \n * \n * Given a positive integer, return its corresponding column title as appear in an Excel sheet.\n * \n * For example:\n * \n *     1 -> A\n *     2 -> B\n *     3 -> C\n *     ...\n *     26 -> Z\n *     27 -> AA\n *     28 -> AB \n * \n * Credits:Special thanks to @ifanchu for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nstring base26_int2str(long long n) {\n    string ret;\n    while(n>0){\n        char ch = 'A' + (n-1)%26;\n        ret.insert(ret.begin(), ch  );\n        n -= (n-1)%26;\n        n /= 26;\n    }\n    return ret;\n}\n\nlong long base26_str2int(string& s){\n    long long ret=0;\n    for (int i=0; i<s.size(); i++){\n        int n = s[i] - 'A' + 1;\n        ret = ret*26 + n;\n    }\n    return ret;\n}\n\n\nstring convertToTitle(int n) {\n    return base26_int2str(n);\n}\n\nint main(int argc, char**argv)\n{\n    long long n = 27; \n    if (argc>1){\n        n = atoll(argv[1]);\n    }\n    string ns = base26_int2str(n);\n    n = base26_str2int(ns);\n\n    cout << n << \" = \" << ns << endl;\n\n\n    ns = \"ABCDEFG\";\n    if (argc>2){\n        ns = argv[2];\n    }\n    cout << ns << \" = \" << base26_str2int(ns) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/expressionAddOperators/ExpressionAddOperators.cpp",
    "content": "// Source : https://leetcode.com/problems/expression-add-operators/\n// Author : Hao Chen\n// Date   : 2016-01-16\n\n/*************************************************************************************** \n *\n * Given a string that contains only digits 0-9 and a target value, return all \n * possibilities to add binary operators (not unary) +, -, or * between the digits so \n * they evaluate to the target value.\n * \n * Examples: \n * \"123\", 6 -> [\"1+2+3\", \"1*2*3\"] \n * \"232\", 8 -> [\"2*3+2\", \"2+3*2\"]\n * \"105\", 5 -> [\"1*0+5\",\"10-5\"]\n * \"00\", 0 -> [\"0+0\", \"0-0\", \"0*0\"]\n * \"3456237490\", 9191 -> []\n * \n * Credits:Special thanks to @davidtan1890 for adding this problem and creating all \n * test cases.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    vector<string> addOperators(string num, int target) {\n        vector<string> result;\n        if (num.size() == 0) return result;\n        helper(num, target, result, \"\", 0, 0, 0, ' ');\n        return result;        \n    }\n    \n    //DFS algorithm\n    void helper(const string &num, const int target, //`num` and `target` never change\n                vector<string>& result, // the array store all of the answers\n                string solution, //the current potential answer.\n                int idx, // the current index of `num` array\n                long long val, // the current value we calculated so far\n                long long prev, // the lastest value we used for calculation, which used for operation prioirty adjustment\n                char preop ) // the latest \"+\" or \"-\" operation, which used for operation prioirty adjustment \n    {\n        \n        if (target == val && idx == num.size()){\n            result.push_back(solution);\n            return;\n        }\n        if (idx == num.size()) return;\n        \n        string n;\n        long long v=0;\n        for(int i=idx; i<num.size(); i++) {\n            //get rid of the number which start by \"0\"\n            //e.g.  \"05\" is not the case.\n            if (n==\"0\") return;\n            \n            n = n + num[i];\n            v = v*10 + num[i]-'0';\n            \n            if (solution.size()==0){ \n                // the first time for initialization\n                helper(num, target, result, n, i+1, v, 0, ' ');\n            }else{\n                // '+' or '-' needn't to adjust the priority\n                helper(num, target, result, solution + '+' + n, i+1, val+v, v, '+');\n                helper(num, target, result, solution + '-' + n, i+1, val-v, v, '-');\n                \n                //if we meet multiply operation, we need adjust the calcualtion priority\n                // e.g. if the previous value is calculated by 2+3=5, \n                //      then if we need to multipy 4, it is not 5*4, it is 2+3*4=2+12=24\n                //      we need be careful about multiply again, such as: 2+3*4*5\n                if (preop=='+') {\n                    helper(num, target, result, solution + '*' + n, i+1, (val-prev)+prev*v, prev*v, preop);\n                }else if (preop=='-'){\n                    helper(num, target, result, solution + '*' + n, i+1, (val+prev)-prev*v, prev*v, preop);\n                }else {\n                    helper(num, target, result, solution + '*' + n, i+1, val*v, v, '*');\n                }\n            }\n        }\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/factorialTrailingZeroes/factorialTrailingZeroes.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/factorial-trailing-zeroes/\n// Author : Hao Chen\n// Date   : 2014-12-30\n\n/********************************************************************************** \n * \n * Given an integer n, return the number of trailing zeroes in n!.\n * \n * Note: Your solution should be in polynomial time complexity.\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n/*\n * The idea is: \n * \n *  1. The ZERO comes from 10.  \n *  2. The 10 comes from 2 x 5 \n *  3. And we need to account for all the products of 5 and 2. likes 4×5 = 20 ...\n *  4. So, if we take all the numbers with 5 as a factor, we'll have way more than enough even numbers \n *     to pair with them to get factors of 10\n * \n * **Example One**\n * \n * How many multiples of 5 are between 1 and 23? \n * There is 5, 10, 15, and 20, for four multiples of 5. Paired with 2's from the even factors, \n * this makes for four factors of 10, so: **23! has 4 zeros**.\n * \n * \n * **Example Two**\n * \n * How many multiples of 5 are there in the numbers from 1 to 100? \n * \n * because   100 ÷ 5 = 20, so, there are twenty multiples of 5 between 1 and 100.\n * \n * but wait, actually 25 is 5×5, so each multiple of 25 has an extra factor of 5, \n * ( e.g. 25 × 4 = 100，which introduces extra of zero )\n * \n * So, we need know how many multiples of 25 are between 1 and 100? Since 100 ÷ 25 = 4, \n * (there are four multiples of 25 between 1 and 100)\n * \n * Finally, we get 20 + 4 = 24 trailing zeroes in 100!\n * \n * \n * The above example tell us, we need care about 5, 5×5, 5×5×5, 5×5×5×5 ....\n * \n * **Example Three**\n * \n * \n * 5^1 :  4617 ÷ 5 = 923.4, so we get 923 factors of 5\n * 5^2 :  4617 ÷ 25 = 184.68, so we get 184 additional factors of 5\n * 5^3 :  4617 ÷ 125 = 36.936, so we get 36 additional factors of 5\n * 5^4 :  4617 ÷ 625 = 7.3872, so we get 7 additional factors of 5\n * 5^5 :  4617 ÷ 3125 = 1.47744, so we get 1 more factor of 5\n * 5^6 :  4617 ÷ 15625 = 0.295488, which is less than 1, so stop here.\n * \n * Then 4617! has 923 + 184 + 36 + 7 + 1 = 1151 trailing zeroes.\n * \n */\n\n\nclass Solution {\n    public:\n        int trailingZeroes(int n) {\n            int result = 0;\n            //To avoid the integer overflow ( e.g. 'n >=1808548329' )\n            for(long long i=5; n/i>0 && i <= INT_MAX; i*=5){\n                result += (n/i);\n            }\n            return result;\n        }\n\n        // Alternative implementation which naturally avoid integer overflow issue.\n        int trailingZeroes(int n) {\n            int sum=0;\n            int tmp=0;\n            while(n/5>0)\n            {\n                tmp=n/5;\n                sum+=tmp;\n                n=tmp;\n            }\n            return sum;\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/fibonacciNumber/FibonacciNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/fibonacci-number/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such \n * that each number is the sum of the two preceding ones, starting from 0 and 1. That is,\n * \n * F(0) = 0,   F(1) = 1\n * F(N) = F(N - 1) + F(N - 2), for N > 1.\n * \n * Given N, calculate F(N).\n * \n * Example 1:\n * \n * Input: 2\n * Output: 1\n * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n * \n * Example 2:\n * \n * Input: 3\n * Output: 2\n * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n * \n * Example 3:\n * \n * Input: 4\n * Output: 3\n * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n * \n * Note:\n * \n * 0 &le; N &le; 30.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int fib(int N) {\n        if (N < 2 )  return N;\n        int first = 0, second = 1;\n\n        for ( N-=1; N > 0; N-- ) {\n            second += first;\n            first = second - first;\n        }\n        return second;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp",
    "content": "// Source : https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/\n// Author : Sharvil Katariya \n// Date   : 2020-10-03\n\n/***************************************************************************************************** \n *\n * Given the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, \n * distancei]. You have to filter the restaurants using three filters.\n * \n * The veganFriendly filter will be either true (meaning you should only include restaurants with \n * veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you \n * have the filters maxPrice and maxDistance which are the maximum value for price and distance of \n * restaurants you should consider respectively.\n * \n * Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For \n * restaurants with the same rating, order them by id from highest to lowest. For simplicity \n * veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.\n * \n * Example 1:\n * \n * Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], \n * veganFriendly = 1, maxPrice = 50, maxDistance = 10\n * Output: [3,1,5] \n * Explanation: \n * The restaurants are:\n * Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\n * Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\n * Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\n * Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\n * Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \n * After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have \n * restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). \n * \n * Example 2:\n * \n * Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], \n * veganFriendly = 0, maxPrice = 50, maxDistance = 10\n * Output: [4,3,2,1,5]\n * Explanation: The restaurants are the same as in example 1, but in this case the filter \n * veganFriendly = 0, therefore all restaurants are considered.\n * \n * Example 3:\n * \n * Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], \n * veganFriendly = 0, maxPrice = 30, maxDistance = 3\n * Output: [4,5]\n * \n * Constraints:\n * \n * \t1 <= restaurants.length <= 10^4\n * \trestaurants[i].length == 5\n * \t1 <= idi, ratingi, pricei, distancei <= 10^5\n * \t1 <= maxPrice, maxDistance <= 10^5\n * \tveganFriendlyi and veganFriendly are 0 or 1.\n * \tAll idi are distinct.\n ******************************************************************************************************/\n\n\nstatic bool cmp(const vector<int>& v1, const vector<int>& v2) {\n    return v1[1] == v2[1] ? v1[0] > v2[0] : v1[1] > v2[1];\n}\nclass Solution {\npublic:\n    vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {\n        vector<vector<int>> res;\n        \n        for(int i = 0; i < restaurants.size(); i++) {\n            if (!restaurants[i][2] && veganFriendly) continue;\n            if (restaurants[i][3] > maxPrice) continue;\n            if (restaurants[i][4] > maxDistance) continue;\n            res.push_back(restaurants[i]);\n        }\n        \n        sort(res.begin(), res.end(), cmp);\n        \n        vector<int> ids;\n        for(int i = 0; i < res.size(); i++) ids.push_back(res[i][0]);\n        return ids;        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findAllAnagramsInAString/Find-All-Anagrams-in-a-String.cpp",
    "content": "// Source : https://leetcode.com/problems/find-all-anagrams-in-a-string/\n// Author : Manu Gond\n// Date   : 2019-10-06\n\n/***************************************************************************************************** \n* Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.\n\n* Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.\n\n* The order of output does not matter.\n\n* Example 1:\n\n* Input:\n   s: \"cbaebabacd\" p: \"abc\"\n\n* Output:\n  [0, 6]\n\n* Explanation:\n  The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\n  The substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n*Example 2:\n\n* Input:\n   s: \"abab\" p: \"ab\"\n\n* Output:\n   [0, 1, 2]\n\n* Explanation:\n* The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\n* The substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\n* The substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n ******************************************************************************************************/\n \n \n class Solution {\npublic:\n    vector<int> findAnagrams(string s, string p) {\n        vector<int>result;\n        vector<int>v1(26);\n        if(s.size()<p.size()){\n            return result;\n        }\n        for(int i=0;i<p.size();i++){\n            v1[p[i]-97]++;\n        }\n        for(int i=0;i<=(s.size()-p.size());i++){\n            vector<int>v2(26);\n            for(int index=i;index<(i+p.size());index++){\n                v2[s[index]-97]++;\n            }\n            if(v1==v2){\n                result.push_back(i);\n            }        \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findCenterOfStarGraph/FindCenterOfStarGraph.cpp",
    "content": "// Source : https://leetcode.com/problems/find-center-of-star-graph/\n// Author : Hao Chen\n// Date   : 2021-03-19\n\n/***************************************************************************************************** \n *\n * There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a \n * graph where there is one center node and exactly n - 1 edges that connect the center node with \n * every other node.\n * \n * You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an \n * edge between the nodes ui and vi. Return the center of the given star graph.\n * \n * Example 1:\n * \n * Input: edges = [[1,2],[2,3],[4,2]]\n * Output: 2\n * Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the \n * center.\n * \n * Example 2:\n * \n * Input: edges = [[1,2],[5,1],[1,3],[1,4]]\n * Output: 1\n * \n * Constraints:\n * \n * \t3 <= n <= 105\n * \tedges.length == n - 1\n * \tedges[i].length == 2\n * \t1 <= ui, vi <= n\n * \tui != vi\n * \tThe given edges represent a valid star graph.\n ******************************************************************************************************/\n\n\n"
  },
  {
    "path": "algorithms/cpp/findKthLargestXorCoordinateValue/FindKthLargestXorCoordinateValue.cpp",
    "content": "// Source : https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/\n// Author : Hao Chen\n// Date   : 2021-03-31\n\n/***************************************************************************************************** \n *\n * You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an \n * integer k.\n * \n * The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m \n * and 0 <= j <= b < n (0-indexed).\n * \n * Find the k^th largest value (1-indexed) of all the coordinates of matrix.\n * \n * Example 1:\n * \n * Input: matrix = [[5,2],[1,6]], k = 1\n * Output: 7\n * Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.\n * \n * Example 2:\n * \n * Input: matrix = [[5,2],[1,6]], k = 2\n * Output: 5\n * Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.\n * \n * Example 3:\n * \n * Input: matrix = [[5,2],[1,6]], k = 3\n * Output: 4\n * Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.\n * \n * Example 4:\n * \n * Input: matrix = [[5,2],[1,6]], k = 4\n * Output: 0\n * Explanation: The value of coordinate (1,1) is 5 XOR 2 XOR 1 XOR 6 = 0, which is the 4th largest \n * value.\n * \n * Constraints:\n * \n * \tm == matrix.length\n * \tn == matrix[i].length\n * \t1 <= m, n <= 1000\n * \t0 <= matrix[i][j] <= 10^6\n * \t1 <= k <= m * n\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    void print(vector<vector<int>>& m) {\n        int row = m.size();\n        int col = m[0].size();\n        for (int i=0; i<row; i++) {\n            for(int j=0; j<col-1; j++) {\n                cout << setw(3) << m[i][j] << \",\";\n            }\n            cout << setw(3) << m[i][col-1] << endl;\n        }\n        cout << endl;\n    }\npublic:\n    int kthLargestValue(vector<vector<int>>& matrix, int k) {\n        int row = matrix.size();\n        int col = matrix[0].size();\n        vector<vector<int>> xmatrix(row, vector<int>(col, 0));\n        priority_queue<int> minHeap;\n        \n        xmatrix[0][0] = matrix[0][0];\n        minHeap.push(xmatrix[0][0]);\n \n        for (int i=1; i<row; i++) {\n            xmatrix[i][0] = xmatrix[i-1][0] ^ matrix[i][0];\n            minHeap.push(xmatrix[i][0]);\n        }\n        for (int i=1; i<col; i++) {\n            xmatrix[0][i] = xmatrix[0][i-1] ^ matrix[0][i];\n            minHeap.push(xmatrix[0][i]);\n        }\n        \n        for (int i=1; i<row; i++) {\n            for(int j=1; j<col; j++) {\n                xmatrix[i][j] = matrix[i][j] ^ \n                    xmatrix[i-1][j] ^ xmatrix[i][j-1] ^ xmatrix[i-1][j-1];\n                minHeap.push(xmatrix[i][j]);\n            }\n        }\n        //print(matrix);\n        //print(xmatrix);\n        while( k-- > 1) {\n            minHeap.pop();\n        }\n        \n        return minHeap.top();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findMedianFromDataStream/FindMedianFromDataStream.cpp",
    "content": "// Source : https://leetcode.com/problems/find-median-from-data-stream/\n// Author : Hao Chen\n// Date   : 2015-11-14\n\n/*************************************************************************************** \n *\n * Median is the middle value in an ordered integer list. If the size of the list is \n * even, there is no middle value. So the median is the mean of the two middle value.\n * Examples: \n * [2,3,4] , the median is 3\n * [2,3], the median is (2 + 3) / 2 = 2.5 \n * \n * Design a data structure that supports the following two operations:\n * \n * void addNum(int num) - Add a integer number from the data stream to the data \n * structure.\n * double findMedian() - Return the median of all elements so far.\n * \n * For example:\n * \n * add(1)\n * add(2)\n * findMedian() -> 1.5\n * add(3) \n * findMedian() -> 2\n * \n * Credits:Special thanks to @Louis1992 for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n\nclass MedianFinder {\n    \nprivate:\n    //we seprate the sorted array to two parts\n    multiset<int> first, second;\n    \npublic:\n\n    // Adds a number into the data structure.\n    void addNum(int num) {\n        if (first.empty() || num <= *(first.rbegin()) ) {\n            first.insert(num);\n        } else {\n            second.insert(num);\n        }\n        \n        if (first.size() > second.size() + 1) {\n            auto it = first.end();\n            it--;\n            second.insert(*(it));\n            first.erase(it);\n        }\n        \n        if ( first.size() < second.size() ) {\n            first.insert(*(second.begin()));\n            second.erase(second.begin());\n        }\n    }\n\n    // Returns the median of current data stream\n    double findMedian() {\n        if (first.size()> second.size()) {\n            return *(first.rbegin());\n        }\n        double x = *first.rbegin();\n        double y = *second.begin();\n        return (x+y)/2;\n    }\n};\n\n// Your MedianFinder object will be instantiated and called as such:\n// MedianFinder mf;\n// mf.addNum(1);\n// mf.findMedian();\n"
  },
  {
    "path": "algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/\n// Author : Hao Chen\n// Date   : 2014-10-21\n\n/********************************************************************************** \n* \n* Follow up for \"Find Minimum in Rotated Sorted Array\":\n* What if duplicates are allowed?\n* \n* Would this affect the run-time complexity? How and why?\n* \n* Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n* \n* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n* \n* Find the minimum element.\n* \n* The array may contain duplicates.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\n/*\n * Need be very careful for the following cases:\n *\n *    [3, 3, 3, 3, 3]\n *  \n *    [3, 3, 3, 1, 3]\n *\n */\n\nint findMin(vector<int> &num) {\n\n    int low=0, high=num.size()-1;\n\n    while(high-low>1){\n        //skip the same element, this would cause the O(n) run-time complexity. \n        while (high - low > 1 && num[low] == num[high]){\n            low++;\n        }\n        //binary search\n        int mid = low + (high-low)/2;\n        //If the array is not rotated then return num[low]\n        //Notes: checking the equal situation\n        if (num[low] <= num[mid] && num[mid] <= num[high]){\n            return num[low];\n        }\n        //move the high pointer to the middle, if sub-array from low to mid is rotated.\n        if (num[low] > num [mid]){\n            high = mid;\n            continue;\n        }\n        // move the low pointer to the middle, if sub-array from mid to high is rotated.\n        if (num[mid] > num[high]){\n            low = mid;\n            continue;\n        }\n    }\n    \n    // checking the edge case \n    if (high == low) return num[low];\n    return num[low] < num[high] ? num[low] : num[high];\n\n}\n\n\nvoid rotate_array(int a[], int n, int pos){\n    int i, from=0;\n    pos = pos % n;\n    if (n<=0) return;\n\n    int tmp = a[0];\n\n    for(int i=0, step=0; step<n && i<pos; step++){\n        int to;\n        if (from-pos < 0) {\n            to = n-pos+from; \n        }else{\n            to = from-pos;\n        }\n        int t ;\n        t = a[to];\n        a[to] = tmp; \n        tmp = t;\n        from = to;\n        if ( to == i ){\n            i++;\n            from++;\n            tmp = a[from];\n        }\n    }\n\n}\n\nvoid printArray(int A[], int n) {\n    printf(\"{\");\n    for(int i=0; i<n; i++) {\n        printf(\"%d, \", A[i]);\n    }\n    printf(\"}\\n\");\n}\n\nint main(int argc, char** argv)\n{\n\n    int cnt=20;\n\n    if (argc>1) {\n        cnt = atoi(argv[1]);\n    }\n\n    srand(time(NULL)); \n\n    int expectedMin, actualMin;\n    int *a = new int[cnt];\n    for(int n=0; n<=cnt; n++) {\n        printf(\"--------------------------------------\\n\");\n        //generate the array with random elements\n        for(int i=0; i<cnt; i++){\n            a[i]=rand()%cnt;\n        }\n        //sort the array\n        sort(a, a+cnt); \n        expectedMin = a[0];\n        //printArray(a, cnt);\n        int rotate_pos = random() % cnt;\n        //rotate_pos=2;\n        printf(\"rotate=%d\\n\", rotate_pos);\n        rotate_array(a, cnt, rotate_pos);\n        printArray(a, cnt);\n\n        vector<int> num(a, a+cnt);\n        actualMin = findMin(num);\n        cout << \"findMin = \" << actualMin << \"   \" << (expectedMin==actualMin ? \"passed\" : \"failed\") << endl;\n\n    }\n    delete[] a;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n// Author : Hao Chen\n// Date   : 2014-10-20\n\n/********************************************************************************** \n* \n* Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n* \n* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n* \n* Find the minimum element.\n* \n* You may assume no duplicate exists in the array.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n/* \n *  Obveriously, to search any sorted array, the binary search is the common sense.\n * \n *  To solve this problem, the idea is same as the search in rotated sorted array.\n */\nint findMin(vector<int> &num) {\n\n    int low=0, high=num.size()-1;\n\n    while(high-low>1){\n        int mid = low + (high-low)/2;\n        // Chek the array if it is non-rotated, then just return the first element.\n        if (num[low] < num[mid] && num[mid] < num[high]){\n            return num[low];\n        }\n\n        // The array is rotated\n        // Split it into two part, the minimal value must be the rotated part\n        \n        // if the left part is rotated, warch the left part\n        if (num[low] > num [mid]){\n            high = mid;\n            continue;\n        }\n        // if the right part is rotated, search the right part.\n        if (num[mid] > num[high]){\n            low = mid;\n            continue;\n        }\n    }\n    // the array only has 1 element\n    if (high == low) return num[low];\n\n    // the array has 2 elements\n    return num[low] < num[high] ? num[low] : num[high];\n\n}\n\n\nvoid rotate_array(int a[], int n, int pos){\n    int i, from=0;\n    pos = pos % n;\n    if (n<=0) return;\n\n    int tmp = a[0];\n\n    for(int i=0, step=0; step<n && i<pos; step++){\n        int to;\n        if (from-pos < 0) {\n            to = n-pos+from; \n        }else{\n            to = from-pos;\n        }\n        int t ;\n        t = a[to];\n        a[to] = tmp; \n        tmp = t;\n        from = to;\n        if ( to == i ){\n            i++;\n            from++;\n            tmp = a[from];\n        }\n    }\n\n}\n\nvoid printArray(int A[], int n) {\n    printf(\"{\");\n    for(int i=0; i<n; i++) {\n        printf(\"%d, \", A[i]);\n    }\n    printf(\"}\\n\");\n}\n\nint main(int argc, char** argv)\n{\n\n    int cnt=20;\n\n    if (argc>1) {\n        cnt = atoi(argv[1]);\n    }\n\n    srand(time(NULL)); \n\n    int expectedMin, actualMin;\n    int *a = new int[cnt];\n    for(int n=0; n<=cnt; n++) {\n        printf(\"--------------------------------------\\n\");\n        for(int i=0; i<cnt; i++){\n            a[i]=i;\n        }\n        expectedMin = a[0];\n        //printArray(a, cnt);\n        int rotate_pos = random() % cnt;\n        //rotate_pos=2;\n        printf(\"rotate=%d\\n\", rotate_pos);\n        rotate_array(a, cnt, rotate_pos);\n        printArray(a, cnt);\n\n        vector<int> num(a, a+cnt);\n        actualMin = findMin(num);\n        cout << \"findMin = \" << actualMin << \"   \" << (expectedMin==actualMin ? \"passed\" : \"failed\") << endl;\n\n    }\n    delete[] a;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/findNearestPointThatHasTheSameXOrYCoordinate/FindNearestPointThatHasTheSameXOrYCoordinate.cpp",
    "content": "// Source : https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/\n// Author : Hao Chen\n// Date   : 2021-03-13\n\n/***************************************************************************************************** \n *\n * You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, \n * y). You are also given an array points where each points[i] = [ai, bi] represents that a point \n * exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as \n * your location.\n * \n * Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your \n * current location. If there are multiple, return the valid point with the smallest index. If there \n * are no valid points, return -1.\n * \n * The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).\n * \n * Example 1:\n * \n * Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\n * Output: 2\n * Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] \n * and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. \n * [2,4] has the smallest index, so return 2.\n * \n * Example 2:\n * \n * Input: x = 3, y = 4, points = [[3,4]]\n * Output: 0\n * Explanation: The answer is allowed to be on the same location as your current location.\n * \n * Example 3:\n * \n * Input: x = 3, y = 4, points = [[2,3]]\n * Output: -1\n * Explanation: There are no valid points.\n * \n * Constraints:\n * \n * \t1 <= points.length <= 104\n * \tpoints[i].length == 2\n * \t1 <= x, y, ai, bi <= 104\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {\n        int result = -1;\n        int distance = INT_MAX;\n        for(int i=0; i<points.size(); i++) {\n            if ( x  != points[i][0]  && y != points[i][1] ) continue;\n            int dist = abs(x - points[i][0]) + abs( y - points[i][1]);\n            if ( distance > dist ){\n                distance = dist;\n                result = i;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findPeakElement/findPeakElement.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/find-peak-element/\n// Author : Hao Chen\n// Date   : 2014-12-05\n\n/********************************************************************************** \n* \n* A peak element is an element that is greater than its neighbors.\n* \n* Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.\n* \n* You may imagine that num[-1] = num[n] = -∞.\n* \n* For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.\n* \n* click to show spoilers.\n* \n* Note:\n* Your solution should be in logarithmic complexity.\n* \n* Credits:Special thanks to @ts for adding this problem and creating all test cases.\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\n\n/*\n *    Binary search is common idea here.\n *\n *    However, you need to think about two senarios:\n *\n *    1) Becasue we need check `num[mid-1]`, `num[mid]`, `num[mid+1]`, \n *       So, we need make sure there hasn't out-of-boundary issue.\n *   \n *\n *\n *    2) There are multiple Peak elements.\n *\n *       For example: [1,2,1,2,1], or [ 1,2,3,1,2,1]\n *\n *       LeetCode doesn't tell you what the expected result is. I guess:\n *\n *       2.1) for [1,2,1,2,1] you can return either 1 or 3, because both them are peak elements\n *\n *       2.1) for [1,2,3,2,4,2,1] it should return 4, because num[4] is the real peak.  but Leetcode accept either 2 or 4\n *\n */\n\nint findPeakElement(const vector<int> &num) {\n\n    int n = num.size();\n    int low = 0;\n    int high = n - 1;\n\n    int mid = 0, v1, v2;\n\n    while ( low < high ) {\n\n        // Find the index of middle element\n        mid = low + ( high - low ) / 2;\n\n        // Compare middle element with its neighbours (if neighbours exist)\n        if ( ( mid == 0 || num[mid] > num[mid-1] ) && \n                ( mid == n-1 ||  num[mid] > num[mid+1] )  ){\n            return mid;\n        }\n\n        // If middle element is not peak and its left neighbor is greater than it\n        // then left half must have a peak element\n        if (mid >0 && num[mid-1] > num[mid]){\n            high = mid - 1;\n        // If middle element is not peak and its right neighbor is greater than it\n        // then right half must have a peak element\n        }else{\n            low = mid + 1;\n        }\n\n    }\n\n    return low;\n}\n\n\nvoid printVector(vector<int> &n) {\n    cout << \"[ \";\n    int i;\n    for(i=0; i<n.size(); i++){\n        cout << n[i] << (i==n.size()-1 ? \" ]\" : \", \");\n    }\n    cout << endl;\n}\n\nvoid test(int a[], int n) {\n    vector<int> v(a, a+n);\n    cout << \"Peak Index = \" << findPeakElement(v) << \"\\t\";\n    printVector(v);\n}\n\n\n#define TEST(a) test(a, sizeof(a)/sizeof(a[0]))\n\nint main(int argc, char**argv)\n{\n    int n0[] = {1};\n    TEST(n0);\n\n    int n1[] = {1,2};\n    TEST(n1);\n\n    int n2[] = {2,1};\n    TEST(n2);\n\n    int n3[] = {1,2,3};\n    TEST(n3);\n\n    int n4[] = {3,2,1};\n    TEST(n4);\n\n    int n5[] = {1,2,3,2};\n    TEST(n5);\n\n    int n6[] = {0,1,2,9,7,5,4,2,1};\n    TEST(n6);\n\n    int n7[] = {1,2,1,2,1};\n    TEST(n7);\n\n    int n8[] = {1,2,1,2,3,1};\n    TEST(n8);\n\n    int n9[] = {1,2,3,2,4,2,1};\n    TEST(n9);\n\n    int n10[] = {1,3,1,2,1,3,1};\n    TEST(n10);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/findTheDifference/FindTheDifference.cpp",
    "content": "// Source : https://leetcode.com/problems/find-the-difference/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * Given two strings s and t which consist of only lowercase letters.\n * \n * String t is generated by random shuffling string s and then add one more letter at a \n * random position.\n * \n * Find the letter that was added in t.\n * \n * Example:\n * \n * Input:\n * s = \"abcd\"\n * t = \"abcde\"\n * \n * Output:\n * e\n * \n * Explanation:\n * 'e' is the letter that was added.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    char findTheDifference(string s, string t) {\n        unordered_map<char, int> m;\n        for(auto c : s) m[c]++;\n        for(auto c : t) {\n            m[c]--;\n            if (m[c] < 0) return c;\n        }\n        return '\\0';\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findTheDuplicateNumber/findTheDuplicateNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/find-the-duplicate-number/\n// Author : Hao Chen, Calinescu Valentin\n// Date   : 2015-10-19\n\n/*************************************************************************************** \n *\n * Given an array nums containing n + 1 integers where each integer is between 1 and \n * n (inclusive), prove that at least one duplicate number must exist.\n * Assume that there is only one duplicate number, find the duplicate one.\n *\n * Note:\n * > You must not modify the array (assume the array is read only).\n * > You must use only constant, O(1) extra space.\n * > Your runtime complexity should be less than O(n2).\n * > There is only one duplicate number in the array, but it could be repeated more than\n *   once.\n *\n * Credits:\n * Special thanks to @jianchao.li.fighter for adding this problem and creating all test\n * cases.\n *               \n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    //\n    // This problem can be transfromed to \"Linked List Cycle\" problem.\n    // There are two pointers, one goes one step, another goes two steps.\n    //\n    // Refer to: https://en.wikipedia.org/wiki/Cycle_detection\n    //\n    int findDuplicate(vector<int>& nums) {\n        int n = nums.size();\n        int one = n;\n        int two = n;\n\n       do{\n            one = nums[one-1];\n            two = nums[nums[two-1]-1];\n        } while(one != two); \n        \n        //find the start point of the cycle\n        one = n;\n        while(one != two){\n            one = nums[one-1];\n            two = nums[two-1];\n        }\n        \n        return one;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findTheHighestAltitude/FindTheHighestAltitude.cpp",
    "content": "// Source : https://leetcode.com/problems/find-the-highest-altitude/\n// Author : Hao Chen\n// Date   : 2021-02-17\n\n/***************************************************************************************************** \n *\n * There is a biker going on a road trip. The road trip consists of n + 1 points at different \n * altitudes. The biker starts his trip on point 0 with altitude equal 0.\n * \n * You are given an integer array gain of length n where gain[i] is the net gain in altitude between \n * points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point.\n * \n * Example 1:\n * \n * Input: gain = [-5,1,5,0,-7]\n * Output: 1\n * Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\n * \n * Example 2:\n * \n * Input: gain = [-4,-3,-2,-1,4,3,2]\n * Output: 0\n * Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n * \n * Constraints:\n * \n * \tn == gain.length\n * \t1 <= n <= 100\n * \t-100 <= gain[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int largestAltitude(vector<int>& gain) {\n        int result = 0;\n        int sum = 0;\n        for (auto& n : gain) {\n            sum += n;\n            result = max(result, sum);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findTheWinnerOfAnArrayGame/FindTheWinnerOfAnArrayGame.cpp",
    "content": "// Source : https://leetcode.com/problems/find-the-winner-of-an-array-game/\n// Author : Hao Chen\n// Date   : 2020-10-02\n\n/***************************************************************************************************** \n *\n * Given an integer array arr of distinct integers and an integer k.\n * \n * A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each \n * round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 \n * and the smaller integer moves to the end of the array. The game ends when an integer wins k \n * consecutive rounds.\n * \n * Return the integer which will win the game.\n * \n * It is guaranteed that there will be a winner of the game.\n * \n * Example 1:\n * \n * Input: arr = [2,1,3,5,4,6,7], k = 2\n * Output: 5\n * Explanation: Let's see the rounds of the game:\n * Round |       arr       | winner | win_count\n *   1   | [2,1,3,5,4,6,7] | 2      | 1\n *   2   | [2,3,5,4,6,7,1] | 3      | 1\n *   3   | [3,5,4,6,7,1,2] | 5      | 1\n *   4   | [5,4,6,7,1,2,3] | 5      | 2\n * So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\n * \n * Example 2:\n * \n * Input: arr = [3,2,1], k = 10\n * Output: 3\n * Explanation: 3 will win the first 10 rounds consecutively.\n * \n * Example 3:\n * \n * Input: arr = [1,9,8,2,3,7,6,4,5], k = 7\n * Output: 9\n * \n * Example 4:\n * \n * Input: arr = [1,11,22,33,44,55,66,77,88,99], k = 1000000000\n * Output: 99\n * \n * Constraints:\n * \n * \t2 <= arr.length <= 10^5\n * \t1 <= arr[i] <= 10^6\n * \tarr contains distinct integers.\n * \t1 <= k <= 10^9\n ******************************************************************************************************/\nclass Solution {\npublic:\n    int getWinner(vector<int>& arr, int k) { \n        \n        int left=0, right=1;\n        \n        int max = arr[left] > arr[right] ? arr[left] : arr[right];\n        int winner; \n        int win_times = 0;\n        \n        while( right < arr.size())  {\n\n            //if left < right,  the move the `left` to the `right`\n            if ( arr[left] < arr[right] ) {\n                left = right;\n            }\n            // move the `right` to next element\n            right++;\n            //record current round winner.\n            int w = arr[left];            \n            \n            if (w == winner) {\n                //if winner is same, count++\n                win_times++; \n            }else{\n                // if winner is new number, reset the count.\n                winner = w;\n                win_times = 1;\n            }\n            \n            // if the time of win equal K, return winner. \n            if (win_times >= k) return winner;\n            \n            // find the max element of this array, if k > arr.size() then return this\n            if (max < arr[right]) max = arr[right];\n        }\n        \n        return max;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findTheWinnerOfTheCircularGame/FindTheWinnerOfTheCircularGame.cpp",
    "content": "// Source : https://leetcode.com/problems/find-the-winner-of-the-circular-game/\n// Author : Hao Chen\n// Date   : 2021-04-11\n\n/***************************************************************************************************** \n *\n * There are n friends that are playing a game. The friends are sitting in a circle and are numbered \n * from 1 to n in clockwise order. More formally, moving clockwise from the i^th friend brings you to \n * the (i+1)^th friend for 1 <= i < n, and moving clockwise from the n^th friend brings you to the \n * 1^st friend.\n * \n * The rules of the game are as follows:\n * \n * \tStart at the 1^st friend.\n * \tCount the next k friends in the clockwise direction including the friend you started at. \n * The counting wraps around the circle and may count some friends more than once.\n * \tThe last friend you counted leaves the circle and loses the game.\n * \tIf there is still more than one friend in the circle, go back to step 2 starting from the \n * friend immediately clockwise of the friend who just lost and repeat.\n * \tElse, the last friend in the circle wins the game.\n * \n * Given the number of friends, n, and an integer k, return the winner of the game.\n * \n * Example 1:\n * \n * Input: n = 5, k = 2\n * Output: 3\n * Explanation: Here are the steps of the game:\n * 1) Start at friend 1.\n * 2) Count 2 friends clockwise, which are friends 1 and 2.\n * 3) Friend 2 leaves the circle. Next start is friend 3.\n * 4) Count 2 friends clockwise, which are friends 3 and 4.\n * 5) Friend 4 leaves the circle. Next start is friend 5.\n * 6) Count 2 friends clockwise, which are friends 5 and 1.\n * 7) Friend 1 leaves the circle. Next start is friend 3.\n * 8) Count 2 friends clockwise, which are friends 3 and 5.\n * 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n * \n * Example 2:\n * \n * Input: n = 6, k = 5\n * Output: 1\n * Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n * \n * Constraints:\n * \n * \t1 <= k <= n <= 500\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int findTheWinner(int n, int k) {\n        vector<int> persons(n);\n        for(int i=0; i<n; i++) persons[i] = i + 1;\n        \n        for(int start=0; n>1; n--){\n            start = (start + k -1) % n;\n            persons.erase(persons.begin() + start);\n            start = start %(n-1);\n        }\n        return persons[0];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findXorSumOfAllPairsBitwiseAnd/FindXorSumOfAllPairsBitwiseAnd.cpp",
    "content": "// Source : https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one \n * element, then its XOR sum will be equal to this element.\n * \n * \tFor example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum \n * of [3] is equal to 3.\n * \n * You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.\n * \n * Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair \n * where 0 <= i < arr1.length and 0 <= j < arr2.length.\n * \n * Return the XOR sum of the aforementioned list.\n * \n * Example 1:\n * \n * Input: arr1 = [1,2,3], arr2 = [6,5]\n * Output: 0\n * Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\n * The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\n * \n * Example 2:\n * \n * Input: arr1 = [12], arr2 = [4]\n * Output: 4\n * Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n * \n * Constraints:\n * \n * \t1 <= arr1.length, arr2.length <= 10^5\n * \t0 <= arr1[i], arr2[j] <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int getXORSum(vector<int>& arr1, vector<int>& arr2) {\n        int x = arr1[0];\n        for(int i = 1; i < arr1.size(); i++) {\n            x ^= arr1[i];\n        }\n        int y = arr2[0];\n        for(int i = 1; i< arr2.size(); i++) {\n            y ^= arr2[i];\n        }\n        return x&y;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/findingMkAverage/FindingMkAverage.cpp",
    "content": "// Source : https://leetcode.com/problems/finding-mk-average/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * You are given two integers, m and k, and a stream of integers. You are tasked to implement a data \n * structure that calculates the MKAverage for the stream.\n * \n * The MKAverage can be calculated using these steps:\n * \n * \tIf the number of the elements in the stream is less than m you should consider the \n * MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.\n * \tRemove the smallest k elements and the largest k elements from the container.\n * \tCalculate the average value for the rest of the elements rounded down to the nearest \n * integer.\n * \n * Implement the MKAverage class:\n * \n * \tMKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two \n * integers m and k.\n * \tvoid addElement(int num) Inserts a new element num into the stream.\n * \tint calculateMKAverage() Calculates and returns the MKAverage for the current stream \n * rounded down to the nearest integer.\n * \n * Example 1:\n * \n * Input\n * [\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \n * \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n * [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\n * Output\n * [null, null, null, -1, null, 3, null, null, null, 5]\n * \n * Explanation\n * MKAverage obj = new MKAverage(3, 1); \n * obj.addElement(3);        // current elements are [3]\n * obj.addElement(1);        // current elements are [3,1]\n * obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\n * obj.addElement(10);       // current elements are [3,1,10]\n * obj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n *                           // After removing smallest and largest 1 element the container will be \n * [3].\n *                           // The average of [3] equals 3/1 = 3, return 3\n * obj.addElement(5);        // current elements are [3,1,10,5]\n * obj.addElement(5);        // current elements are [3,1,10,5,5]\n * obj.addElement(5);        // current elements are [3,1,10,5,5,5]\n * obj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n *                           // After removing smallest and largest 1 element the container will be \n * [5].\n *                           // The average of [5] equals 5/1 = 5, return 5\n * \n * Constraints:\n * \n * \t3 <= m <= 10^5\n * \t1 <= k*2 < m\n * \t1 <= num <= 10^5\n * \tAt most 10^5 calls will be made to addElement and calculateMKAverage.\n ******************************************************************************************************/\n\nclass MKAverage {\nprivate:\n    vector<int> ringBuf;\n    int pos;\n    multiset<int> left, mid, right;\n    long sum;\n    long maxmin;\n    int m;\n    int k;\nprivate:\n    template <class T>\n    void print(T& v) {\n        for(auto it : v){\n            cout << it << \"+\";\n        }\n        cout <<endl;\n    }\n    int takeMax(multiset<int>& s) {\n        auto it = --s.end();\n        int n = *it;\n        s.erase(it);\n        return n;\n    }\n    int takeMin(multiset<int>& s) {\n        auto it = s.begin();\n        int n = *it;\n        s.erase(it);\n        return n;\n    }\npublic:\n    MKAverage(int _m, int _k): ring(_m, 0), m(_m), k(_k), sum(0), pos(0), maxmin(0) {\n        \n    }\n    \n    void ins(int n) {\n        left.insert(n);\n        maxmin += n;\n        if (left.size() > k ) {\n            int n = takeMax(left);\n            right.insert(n);\n            if (right.size() > k) {\n                int n = takeMin(right);\n                maxmin -= n;\n                mid.insert(n);\n            }\n        }\n    }\n    \n    void del(int n) {\n        if (n <= *(left.rbegin())) {\n            left.erase(left.find(n));\n            int n1 = takeMin(mid);\n            left.insert(n1);\n            maxmin += (n1 - n);\n        }else if (n >= *(right.begin())) {\n            right.erase(right.find(n));\n            int n1 = takeMax(mid);\n            right.insert(n1);\n            maxmin += (n1 - n);\n        }else {\n            mid.erase(mid.find(n));\n        }   \n    }\n    \n    void addElement(int num) {\n        pos++; \n        if (pos > m) {\n            int n = ringBuf[pos % m];\n            sum -= n;\n            del(n);\n            //cout << \"DEL: n=\" << n << \", sum=\" << sum << \", maxmin=\" << maxmin << endl;\n            //print(left); print(mid);print(right);\n        } \n        \n        ringBuf[pos % m] = num ;\n        sum += num;\n        \n        ins(num);\n        //cout << \"INS: n=\" << num << \", sum=\" << sum << \", maxmin=\" << maxmin << endl;\n        //print(left); print(mid);print(right);\n    }\n\n    \n    int calculateMKAverage() {\n        if (pos < m) return -1;\n        //cout << \"CAL: sum=\" << sum << \", maxmin=\" << maxmin  << \", delta=\" << sum - maxmin<< endl;\n        return (sum - maxmin) / (m-2*k);\n    }\n};\n\n/**\n * Your MKAverage object will be instantiated and called as such:\n * MKAverage* obj = new MKAverage(m, k);\n * obj->addElement(num);\n * int param_2 = obj->calculateMKAverage();\n */\n\n\n\n\n\n\n\n\n\n//TLE solution - using only one array and Binary Search.\n\n\nclass MKAverage1 {\nprivate:\n    vector<int> ring;\n    int pos;\n    vector<int> sort;\n    long sum;\n    long maxmin;\n    int m;\n    int k;\nprivate:\n    template <class T>\n    void print(T& v) {\n        for(auto it : v){\n            cout << it << \"+\";\n        }\n        cout <<endl;\n    }\npublic:\n    MKAverage1(int _m, int _k):  ring(_m,0), m(_m), k(_k), sum(0), pos(0), maxmin(0) {\n        \n    }\n    void ins(int n) {\n        \n        int low = 0, high = sort.size()-1;\n        int mid;\n        if (high < 0 || n >= sort[high]) {\n            sort.push_back(n); \n            return;\n        }\n        \n        while(low <= high){\n            mid = low + (high-low)/2;\n            if (sort[mid]  <= n ) low = mid + 1;\n            else high = mid - 1;\n        }\n        auto it = sort.begin() + low;\n        sort.insert(it, n);\n    }\n    \n    void del(int n) {\n        int len = sort.size();\n        int low = 0, high = len -1;\n        int mid;\n        while(low <= high){\n            mid = low + (high-low)/2;\n            if (sort[mid] == n) break;\n            if (sort[mid]  < n ) low = mid + 1;\n            else high = mid - 1;\n        }\n        \n        if (low > high) return;\n        \n        auto it = sort.begin() + mid;\n        sort.erase(it);\n        \n    }\n    void addElement(int num) {\n        pos++;\n        \n        if (pos > m) {\n            int n = ring[pos % m];\n            sum -= n;\n            \n            int len = sort.size();\n            if (n <= sort[k-1] ) maxmin += (sort[k]-n);\n            else if (n >= sort[len-k]) maxmin += (sort[len-k-1] - n);\n            \n            del(n);\n            //cout << \"DEL: n=\" << n << \", sum=\" << sum << \", maxmin=\" << maxmin << endl;\n            //print(sort);\n        } \n        \n        \n        ring[pos % m] = num;\n        sum += num;\n        \n        if (sort.size() < 2*k ) {\n            maxmin += num;\n        } else {\n            int len = sort.size();\n            if (num <= sort[k-1]) maxmin += (num - sort[k-1]);\n            else if (num >= sort[len-k]) maxmin += (num -sort[len-k]);\n        }\n        \n        ins(num);\n        //cout << \"INS: n=\" << num << \", sum=\" << sum << \", maxmin=\" << maxmin << endl;\n        //print(sort);\n    }\n\n    \n    int calculateMKAverage() {\n        if ( pos < m) return -1;\n        //cout << \"CAL: sum=\" << sum << \", maxmin=\" << maxmin  << \", delta=\" << sum - maxmin<< endl;\n        return (sum - maxmin) / (m-2*k);\n    }\n};\n\n/**\n * Your MKAverage object will be instantiated and called as such:\n * MKAverage* obj = new MKAverage(m, k);\n * obj->addElement(num);\n * int param_2 = obj->calculateMKAverage();\n */\n\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/findingTheUsersActiveMinutes/FindingTheUsersActiveMinutes.cpp",
    "content": "// Source : https://leetcode.com/problems/finding-the-users-active-minutes/\n// Author : Hao Chen\n// Date   : 2021-04-05\n\n/***************************************************************************************************** \n *\n * You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented \n * by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi \n * performed an action at the minute timei.\n * \n * Multiple users can perform actions simultaneously, and a single user can perform multiple actions \n * in the same minute.\n * \n * The user active minutes (UAM) for a given user is defined as the number of unique minutes in which \n * the user performed an action on LeetCode. A minute can only be counted once, even if multiple \n * actions occur during it.\n * \n * You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), \n * answer[j] is the number of users whose UAM equals j.\n * \n * Return the array answer as described above.\n * \n * Example 1:\n * \n * Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\n * Output: [0,2,0,0,0]\n * Explanation:\n * The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 \n * (minute 5 is only counted once).\n * The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\n * Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n * \n * Example 2:\n * \n * Input: logs = [[1,1],[2,2],[2,3]], k = 4\n * Output: [1,1,0,0]\n * Explanation:\n * The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\n * The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\n * There is one user with a UAM of 1 and one with a UAM of 2.\n * Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n * \n * Constraints:\n * \n * \t1 <= logs.length <= 10^4\n * \t0 <= IDi <= 10^9\n * \t1 <= timei <= 10^5\n * \tk is in the range [The maximum UAM for a user, 10^5].\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) {\n        vector<int> result(k, 0);\n        unordered_map<int, set<int>> uam;\n        for (auto& log : logs) {\n            uam[log[0]].insert(log[1]);\n        }\n        for (auto& [id, t] : uam) {\n            if (t.size() <= k) {\n                result[t.size()-1]++;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/firstBadVersion/FirstBadVersion.cpp",
    "content": "// Source : https://leetcode.com/problems/first-bad-version/\n// Author : Hao Chen\n// Date   : 2015-10-19\n\n/*************************************************************************************** \n *\n * You are a product manager and currently leading a team to develop a new product. \n * Unfortunately, the latest version of your product fails the quality check. Since \n * each version is developed based on the previous version, all the versions after a \n * bad version are also bad. \n * \n * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad \n * one, which causes all the following ones to be bad.\n * \n * You are given an API bool isBadVersion(version) which will return whether version is \n * bad. Implement a function to find the first bad version. You should minimize the \n * number of calls to the API.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\n// Forward declaration of isBadVersion API.\nbool isBadVersion(int version);\n\nclass Solution {\npublic:\n    //Binary search\n    int firstBadVersion(int n) {\n        int low=1, high=n;\n        while(low <= high) {\n            int mid = low + (high - low)/2;\n            if (isBadVersion(mid) && !isBadVersion(mid-1)){\n                return mid;\n            }\n            if (isBadVersion(mid)) {\n                high = mid - 1;\n            }else{\n                low = mid + 1;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/firstMissingPositive/firstMissingPositive.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/first-missing-positive/\n// Author : Hao Chen\n// Date   : 2014-07-18\n\n/********************************************************************************** \n* \n* Given an unsorted integer array, find the first missing positive integer.\n* \n* For example,\n* Given [1,2,0] return 3,\n* and [3,4,-1,1] return 2.\n* \n* Your algorithm should run in O(n) time and uses constant space.\n* \n*               \n**********************************************************************************/\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <map>\nusing namespace std;\n\n#define INT_MAX      2147483647\n\n/*\n *  Idea:\n * \n *    We can move the num to the place whcih the index is the num. \n *   \n *    for example,  (considering the array is zero-based.\n *       1 => A[0], 2 => A[1], 3=>A[2]\n *   \n *    Then, we can go through the array check the i+1 == A[i], if not ,just return i+1;\n *   \n *    This solution comes from StackOverflow.com\n *    http://stackoverflow.com/questions/1586858/find-the-smallest-integer-not-in-a-list\n*/\nint firstMissingPositive_move(int A[], int n) {\n    if (n<=0) return 1;\n    int num;\n    for(int i=0; i<n; i++) {\n        num = A[i];\n        while (num>0 && num<n && A[num-1]!=num) {\n            swap(A[i], A[num-1]);\n            num = A[i];\n        }\n    }\n    for (int i=0; i<n; i++){\n        if (i+1 != A[i]){\n            return i+1;\n        }\n    }\n    return n+1;\n}\n\n/*\n *    The idea is simple: \n *\n *    1) put all of number into a map.\n *    2) for each number a[i] in array, remove its continous number in the map\n *        2.1)  remove ... a[i]-3, a[i]-2, a[i]-1, a[i]\n *        2.2)  remove a[i]+1, a[i]+2, a[i]+3,...\n *    3) during the removeing process, if some number cannot be found, which means it's missed.\n *\n *    considering a case [-2, -1, 4,5,6], \n *        [-2, -1] => missed 0\n *        [4,5,6]  => missed 3\n *\n *    However, we missed 1, so, we have to add dummy number 0 whatever.\n *\n *    NOTE: this solution is not constant space slution!!!!\n *\n */\nint firstMissingPositive_map(int A[], int n) {\n    map<int, int> cache;\n    for(int i=0; i<n; i++){\n        cache[A[i]] = i;\n    }\n\n    //add dummy\n    if (cache.find(0)==cache.end() ) {\n        cache[0] = -1;\n    }\n\n    int miss = INT_MAX;\n    int x;\n    for (int i=-1; i<n && cache.size()>0; i++){\n\n        if (i == -1){\n            x = 0; //checking dummy\n        }else{\n            x = A[i];\n        } \n\n        if ( cache.find(x)==cache.end() ){\n            continue;\n        }\n\n        int num ;\n        // remove the ... x-3, x-2, x-1, x\n        for( num=x; cache.find(num)!=cache.end(); num--){\n            cache.erase(cache.find(num));\n        }\n        if ( num>0 && num < miss  ){\n            miss = num;\n        }\n        // remove the x+1, x+2, x+3 ...\n        for ( num=x+1; cache.find(num)!=cache.end(); num++){\n            cache.erase(cache.find(num));\n        }\n        if ( num>0 && num < miss) {\n            miss = num;\n        }\n    }\n\n\n    return miss;\n}\n\nint firstMissingPositive(int A[], int n) {\n    srand(time(0));\n    if (rand()%2){\n        return firstMissingPositive_move(A, n);\n    }\n    return firstMissingPositive_map(A, n);\n}\n\n\nvoid printArray(int a[], int n){\n    cout << \"[ \";\n    for(int i=0; i<n-1; i++) {\n        cout << a[i] << \", \";\n    }\n    cout << a[n-1] << \" ]\";\n}\n\nvoid Test(int a[], int n, int expected) {\n    printArray(a, n);\n    int ret = firstMissingPositive(a, n);\n    cout << \"\\t   missed = \" << ret << \"  \" << (ret==expected?\"passed!\":\"failed!\") << endl;\n    //printArray(a, n);\n    //cout <<endl;\n}\n\nint main()\n{\n#define TEST(a, e) Test(a, sizeof(a)/sizeof(int), e) \n\n    int a0[]={1};\n    TEST(a0, 2);\n\n    int a1[]={1,2,0};\n    TEST(a1, 3);\n\n    int a2[]={3,4,-1,1};\n    TEST(a2, 2);\n\n    int a3[]={1000,-1};\n    TEST(a3, 1);\n\n    int a4[]={1000, 200};\n    TEST(a4, 1);\n\n    int a5[]={2,5,3,-1};\n    TEST(a5, 1);\n\n    int a6[]={1, 100};\n    TEST(a6, 2);\n\n    int a7[]={7,8,9,11};\n    TEST(a7, 1);\n\n    int a8[]={4,3,2,1};\n    TEST(a8, 5);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/firstUniqueCharacterInAString/FirstUniqueCharacterInAString.cpp",
    "content": "// Source : https://leetcode.com/problems/first-unique-character-in-a-string/\n// Author : Hao Chen\n// Date   : 2016-08-23\n\n/*************************************************************************************** \n *\n * Given a string, find the first non-repeating character in it and return it's index. \n * If it doesn't exist, return -1.\n * \n * Examples:\n * \n * s = \"leetcode\"\n * return 0.\n * \n * s = \"loveleetcode\",\n * return 2.\n * \n * Note: You may assume the string contain only lowercase letters.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int firstUniqChar(string s) {\n        //As the question mentioned, there only have lower case chars, \n        //so the MAX_CHAR can be defined as 26, but I want this algorithm be more general for all ASCII\n        #define MAX_CHAR 256\n        #define NOT_FOUND  -1\n        #define DUPLICATION -2\n        \n        // initlize all chars status to NOT_FOUND\n        int pos_map[MAX_CHAR];\n        memset(pos_map, NOT_FOUND,sizeof(pos_map));\n        \n        // if it is the first time to find, set the status to its postion\n        // if it is the second time to find, set the status to duplication\n        // if it has already duplicated, do nothing \n        for (int i=0; i<s.size(); i++){\n            if ( pos_map[s[i]] >= 0 ) {\n                pos_map[s[i]] = DUPLICATION;\n            }else if ( pos_map[s[i]] == NOT_FOUND ) {\n                pos_map[s[i]] = i;\n            }\n        }\n        \n        // find the lowest postion\n        int pos = INT_MAX;\n        for (auto item : pos_map) {\n            cout << item << \",\";\n            if (item >= 0 && item < pos) {\n                pos = item;\n            }\n        }\n        return pos == INT_MAX ? -1 : pos;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/fizzBuzz/FizzBuzz.cpp",
    "content": "// Source : https://leetcode.com/problems/fizz-buzz/\n// Author : Hao Chen\n// Date   : 2016-11-13\n\n/*************************************************************************************** \n *\n * Write a program that outputs the string representation of numbers from 1 to n.\n * \n * But for multiples of three it should output “Fizz” instead of the number and for the \n * multiples of five output “Buzz”. For numbers which are multiples of both three and \n * five output “FizzBuzz”.\n * \n * Example:\n * \n * n = 15,\n * \n * Return:\n * [\n *     \"1\",\n *     \"2\",\n *     \"Fizz\",\n *     \"4\",\n *     \"Buzz\",\n *     \"Fizz\",\n *     \"7\",\n *     \"8\",\n *     \"Fizz\",\n *     \"Buzz\",\n *     \"11\",\n *     \"Fizz\",\n *     \"13\",\n *     \"14\",\n *     \"FizzBuzz\"\n * ]\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    vector<string> fizzBuzz_old_school_way(int n) {\n        vector<string> result;\n        for (int i=1; i<=n; i++) {\n            if ( i%3 == 0 && i%5 ==0 ) {\n                result.push_back(\"FizzBuzz\");\n            }else if (i%3 == 0) {\n                result.push_back(\"Fizz\");\n            }else if (i%5 == 0) {\n                result.push_back(\"Buzz\");\n            }else{\n                result.push_back(std::to_string(i));\n            }\n        }\n        return result;\n    }\n    \n    \n    class FizzBuzz {\n        public:\n            FizzBuzz() : x(0) {}\n            \n            string operator()() {\n                x++; \n                if ( x%3 == 0 && x%5 ==0 ) {\n                    return (\"FizzBuzz\");\n                }else if (x%3 == 0) {\n                    return (\"Fizz\");\n                }else if (x%5 == 0) {\n                    return(\"Buzz\");\n                }\n                return std::to_string(x);\n            }\n            \n        private:\n            int x;\n    };\n    \n    vector<string> fizzBuzz_cpp_way(int n) {\n        vector<string> result(n);\n        generate(result.begin(), result.end(), FizzBuzz());\n        return result;\n    }\n    \n    vector<string> fizzBuzz(int n) {\n        \n        //both method has same performance\n        \n        if (rand() % 2 == 0) {\n            return fizzBuzz_cpp_way(n); \n        }\n        return fizzBuzz_old_school_way(n);   \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/flattenBinaryTreeToLinkedList/flattenBinaryTreeToLinkedList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a binary tree, flatten it to a linked list in-place.\n* \n* For example,\n* Given\n* \n*          1\n*         / \\\n*        2   5\n*       / \\   \\\n*      3   4   6\n* \n* The flattened tree should look like:\n* \n*    1\n*     \\\n*      2\n*       \\\n*        3\n*         \\\n*          4\n*           \\\n*            5\n*             \\\n*              6\n* \n* \n* Hints:\n* If you notice carefully in the flattened tree, each node's right child points to \n* the next node of a pre-order traversal.\n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void flatten(TreeNode *root) {\n        \n        vector<TreeNode*> v, stack;\n        stack.push_back(root);\n        while(stack.size()>0){\n            TreeNode* node = stack.back();\n            stack.pop_back();\n            v.push_back(node);\n            \n            if (node && node->right){\n                stack.push_back(node->right);\n            }\n            if (node && node->left){\n                stack.push_back(node->left);\n            }\n        }\n        \n        v.push_back(NULL);\n        for(int i=0; i<v.size(); i++){\n            if (v[i]){\n                v[i]->left = NULL;\n                v[i]->right = v[i+1];\n            }\n        }\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp",
    "content": "// Source : https://leetcode.com/problems/flatten-nested-list-iterator/\n// Author : Hao Chen\n// Date   : 2016-05-30\n\n/*************************************************************************************** \n *\n * Given a nested list of integers, implement an iterator to flatten it.\n * \n * Each element is either an integer, or a list -- whose elements may also be integers \n * or other lists.\n * \n * Example 1:\n * Given the list [[1,1],2,[1,1]],\n * \n * By calling next repeatedly until hasNext returns false, the order of elements \n * returned by next should be: [1,1,2,1,1].\n * \n * Example 2:\n * Given the list [1,[4,[6]]],\n * \n * By calling next repeatedly until hasNext returns false, the order of elements \n * returned by next should be: [1,4,6].\n ***************************************************************************************/\n\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass NestedIterator {\nprivate:\n    vector<int> v;\n    int index;\n    void flatten(vector<NestedInteger> &nestedList) {\n        for (auto item : nestedList){\n            if (item.isInteger()){\n                v.push_back( item.getInteger() );\n            }else{\n                flatten( item.getList() );\n            }\n        }\n    }\npublic:\n    NestedIterator(vector<NestedInteger> &nestedList) {\n        flatten(nestedList);\n        index = 0;\n    }\n\n    int next() {\n        return v[index++];\n    }\n\n    bool hasNext() {\n        return (index < v.size() );\n    }\n};\n\n/**\n * Your NestedIterator object will be instantiated and called as such:\n * NestedIterator i(nestedList);\n * while (i.hasNext()) cout << i.next();\n */\n"
  },
  {
    "path": "algorithms/cpp/formArrayByConcatenatingSubarraysOfAnotherArray/FormArrayByConcatenatingSubarraysOfAnotherArray.cpp",
    "content": "// Source : https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * You are given a 2D integer array groups of length n. You are also given an integer array nums.\n * \n * You are asked if you can choose n disjoint subarrays from the array nums such that the i^th \n * subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)^th subarray appears before the \n * i^th subarray in nums (i.e. the subarrays must be in the same order as groups).\n * \n * Return true if you can do this task, and false otherwise.\n * \n * Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs \n * to more than one subarray. A subarray is a contiguous sequence of elements within an array.\n * \n * Example 1:\n * \n * Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\n * Output: true\n * Explanation: You can choose the 0^th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1^st one as \n * [1,-1,0,1,-1,-1,3,-2,0].\n * These subarrays are disjoint as they share no common nums[k] element.\n * \n * Example 2:\n * \n * Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\n * Output: false\n * Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect \n * because they are not in the same order as in groups.\n * [10,-2] must come before [1,2,3,4].\n * \n * Example 3:\n * \n * Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\n * Output: false\n * Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid \n * because they are not disjoint.\n * They share a common elements nums[4] (0-indexed).\n * \n * Constraints:\n * \n * \tgroups.length == n\n * \t1 <= n <= 10^3\n * \t1 <= groups[i].length, sum(groups[i].length) <= 10^3\n * \t1 <= nums.length <= 10^3\n * \t-10^7 <= groups[i][j], nums[k] <= 10^7\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool canChoose(vector<vector<int>>& groups, vector<int>& nums) {\n        \n        //constructing an length array\n        //  lens[0] = len(groups[0]) + len(groups[1]) + ... len(groups[n])\n        //  lens[1] = len(groups[1]) + len(groups[2]) + ... len(groups[n])\n        //  lens[2] = len(groups[2]) + len(groups[3]) + ... len(groups[n])\n        //  lens[n] = len(groups[n])\n        //so that, we can quickly know whether there still has enough room to match rest groups\n        vector<int> lens(groups.size());\n        int total_len=0;\n        for(int i=groups.size()-1; i >=0; i--) {\n            total_len += groups[i].size();\n            lens[i] = total_len;\n        }\n        \n        // index i - loop for groups[]\n        // index j - loop for nums[]\n        int i = 0, j = 0; \n        while ( i < groups.size() && j < nums.size() ) {\n            //if the rest room is not enought to match, return false;\n            if (nums.size() - j < lens[i]) return false;\n            \n            //if the first char is not matched, check the next.\n            if ( nums[j] != groups[i][0]) {\n                j++;\n                continue;\n            }\n            \n            //if the first char is matched, then check the groups[i]\n            bool match = true;\n            for(int k=0; k<groups[i].size(); k++) {\n                if ( nums[j+k] != groups[i][k]) {\n                    match=false;\n                    break;\n                }\n            }\n            \n            // if the groups[i] is matched, then go to next group\n            if (match) {\n                j += groups[i].size();\n                i++;\n            }else{\n                j++;  \n            }\n        }\n        \n        return i == groups.size();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/fractionToRecurringDecimal/fractionToRecurringDecimal.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/fraction-to-recurring-decimal/\n// Author : Hao Chen\n// Date   : 2014-12-16\n\n/********************************************************************************** \n* \n* Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\n* \n* If the fractional part is repeating, enclose the repeating part in parentheses.\n* \n* For example,\n* \n* Given numerator = 1, denominator = 2, return \"0.5\".\n* Given numerator = 2, denominator = 1, return \"2\".\n* Given numerator = 2, denominator = 3, return \"0.(6)\".\n* \n* Credits:Special thanks to @Shangrila for adding this problem and creating all test cases.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <map>\nusing namespace std;\n\n\n/*\n *  Be careful the following cases:\n *\n *    > 0/2\n *    > 1/0\n *    > 1/3\n *    > 2/4\n *    > 100/2\n *    > 100/3\n *    > 1/-4\n *    > -1/4\n *    > -1/-4\n *    > 25/99 = 0.25252525....\n *    > 1/7 = 0.142857142857...\n *    > 1/17 = 0.(0588235294117647)\n */\n\nstring fractionToDecimal(int numerator, int denominator) {\n    string result;\n    //deal with the `ZERO` cases\n    if (denominator == 0){ return result; }\n    if (numerator == 0) { return \"0\"; }\n\n    //using long long type make sure there has no integer overflow\n    long long n = numerator;\n    long long d = denominator;\n\n    //deal with negtive cases \n    bool sign = ((float)numerator/denominator >= 0);\n    if ( n < 0 ){ n = -n; }\n    if ( d < 0 ){ d = -d; }\n    if (sign == false){\n        result.push_back('-');\n    }\n\n    long long remainder = n % d;\n    long long division = n / d;\n    ostringstream oss;\n    oss << division;\n    result += oss.str();\n    if (remainder == 0){\n        return result;\n    }\n    //remainder has value, the result is a float\n    result.push_back('.');\n\n    //using a map to record all of reminders and their position.\n    //if the reminder appeared before, which means the repeated loop begin, \n    //then, get the place from map to insert \"(\".\n    //(In C++11, it's better to use unordered_map )\n    map<long long, int> rec;\n\n    for (int pos=result.size(); remainder!=0; pos++, remainder=(remainder*10)%d ) {\n        if (rec.find(remainder) != rec.end()) {\n            result.insert(result.begin()+rec[remainder], '(');\n            result.push_back(')');\n            return result;\n        }\n        rec[remainder] = pos;\n        result.push_back((remainder*10)/d + '0');\n    }\n\n    return result;\n}\n\n\nvoid test(int num, int deno)\n{\n    cout << \"numerator: \" << num << \"\\tdenominator: \" << deno << \"\\tresult: \" << fractionToDecimal(num, deno) << endl;\n}\n\nint main(int argc, char** argv)\n{\n    test(1, 2);\n    test(10, 2);\n    test(100, 2);\n    test(1, 3);\n    test(100, 3);\n    test(1, 6);\n    test(100, 6);\n    test(-1, 4);\n    test(1, -3);\n    test(-1, -6);\n    test(25, 99);\n    test(1, 7);\n    test(10, 7);\n    test(100, 7);\n    test(1, 17);\n    test(1, 1024);\n    test( -2147483648, -1999);\n    test(-1, -2147483648);\n\n\n    if (argc > 2) {\n        int num = atoi(argv[1]);\n        int deno = atoi(argv[2]);\n        test(num, deno);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/frequencyOfTheMostFrequentElement/FrequencyOfTheMostFrequentElement.cpp",
    "content": "// Source : https://leetcode.com/problems/frequency-of-the-most-frequent-element/\n// Author : Hao Chen\n// Date   : 2021-04-25\n\n/***************************************************************************************************** \n *\n * The frequency of an element is the number of times it occurs in an array.\n * \n * You are given an integer array nums and an integer k. In one operation, you can choose an index of \n * nums and increment the element at that index by 1.\n * \n * Return the maximum possible frequency of an element after performing at most k operations.\n * \n * Example 1:\n * \n * Input: nums = [1,2,4], k = 5\n * Output: 3\n * Explanation: Increment the first element three times and the second element two times to make nums \n * = [4,4,4].\n * 4 has a frequency of 3.\n * \n * Example 2:\n * \n * Input: nums = [1,4,8,13], k = 5\n * Output: 2\n * Explanation: There are multiple optimal solutions:\n * - Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n * - Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n * - Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n * \n * Example 3:\n * \n * Input: nums = [3,9,6], k = 2\n * Output: 1\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t1 <= nums[i] <= 10^5\n * \t1 <= k <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxFrequency(vector<int>& nums, int k) {\n        sort(nums.begin(), nums.end());\n        int m = 1;\n        int start = 0;\n        int i = 1;\n        for(; i<nums.size(); i++){\n            long delta = nums[i] - nums[i-1];\n            k -= delta * (i - start);;\n            if (k < 0 )  {\n                // remove the first one\n                k += (nums[i] - nums[start]) ;\n                start++;\n            }\n            m = max(m, i - start +1);\n            \n        }\n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/friendCircles/FriendCircles.cpp",
    "content": "// Source : https://leetcode.com/problems/friend-circles/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * \n * There are N students in a class. Some of them are friends, while some are not. Their friendship is \n * transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, \n * then A is an indirect friend of C. And we defined a friend circle is a group of students who are \n * direct or indirect friends.\n * \n * Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] \n * = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have \n * to output the total number of friend circles among all the students.\n * \n * Example 1:\n * \n * Input: \n * [[1,1,0],\n *  [1,1,0],\n *  [0,0,1]]\n * Output: 2\n * Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd \n * student himself is in a friend circle. So return 2.\n * \n * Example 2:\n * \n * Input: \n * [[1,1,0],\n *  [1,1,1],\n *  [0,1,1]]\n * Output: 1\n * Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct \n * friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend \n * circle, so return 1.\n * \n * Note:\n * \n * N is in range [1,200].\n * M[i][i] = 1 for all students.\n * If M[i][j] = 1, then M[j][i] = 1.\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n\n    // -----------------------------------------------------------------------------\n    //DFS solution is quite easy to understand, just like the \"Number of Island\"\n    int findCircleNum_DFS(vector<vector<int>>& M) {\n        int n = 0;\n        for (int i=0; i<M.size(); i++) {\n            for (int j=0; j<M[0].size(); j++) {\n                if ( M[i][j] == 1 ) {\n                    n++;\n                    M[i][j] = 2;\n                    mark(M, j);\n                }\n            }\n        }\n        return n;\n    }\n\n    void mark(vector<vector<int>>& M, int i ) {\n        for ( int j=0;  j<M[i].size(); j++ ){\n            if ( M[i][j] == 1 ) {\n                M[i][j] = 2;\n                mark(M, j);\n            }\n        }\n    }\n\n    // -----------------------------------------------------------------------------\n    //Union Find Solution\n    int findCircleNum_UF(vector<vector<int>>& M) {\n\n        vector<int> relations(M.size());\n        for (int i=0; i<relations.size(); i++){\n            relations[i] = i;\n        }\n\n        int n = M.size(); //by default, there are N friend cicles\n        for (int i=0; i<M.size(); i++) {\n            for (int j=0; j<M[0].size(); j++) {\n                if ( M[i][j] == 1 && i != j ) {\n                    if ( join(relations, i, j) ) n--;\n                }\n            }\n        }\n        return n;\n    }\n\n    //find the tail node.\n    //   if a -> b -> c -> d, then find(a),find(b) or find(c) would return d;\n    int find(vector<int>& relations, int i ) {\n        while( relations[i] != i ) {\n            i = relations[i];\n        }\n        return i;\n    }\n    // join the x cicle with y cicle,\n    // if x and y are already in same friend cicle, then return false, else return true;\n    bool join(vector<int> &relations, int x, int y) {\n        int tx = find(relations, x);\n        int ty = find(relations, y);\n        if ( tx != ty ) relations[tx] = ty;\n        return tx != ty;\n    }\n\n    // -----------------------------------------------------------------------------\n    \n    int findCircleNum(vector<vector<int>>& M) {\n        return findCircleNum_UF(M);\n        return findCircleNum_DFS(M);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/frogJump/FrogJump.cpp",
    "content": "// Source : https://leetcode.com/problems/frog-jump/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * A frog is crossing a river. The river is divided into x units and at each unit there \n * may or may not exist a stone. The frog can jump on a stone, but it must not jump \n * into the water.\n * \n * Given a list of stones' positions (in units) in sorted ascending order, determine if \n * the frog is able to cross the river by landing on the last stone. Initially, the \n * frog is on the first stone and assume the first jump must be 1 unit.\n * \n * If the frog's last jump was k units, then its next jump must be either k - 1, k, or \n * k + 1 units. Note that the frog can only jump in the forward direction.\n * \n * Note:\n * \n * The number of stones is ≥ 2 and is \n * Each stone's position will be a non-negative integer 31.\n * The first stone's position is always 0.\n * \n * Example 1:\n * \n * [0,1,3,5,6,8,12,17]\n * \n * There are a total of 8 stones.\n * The first stone at the 0th unit, second stone at the 1st unit,\n * third stone at the 3rd unit, and so on...\n * The last stone at the 17th unit.\n * \n * Return true. The frog can jump to the last stone by jumping \n * 1 unit to the 2nd stone, then 2 units to the 3rd stone, then \n * 2 units to the 4th stone, then 3 units to the 6th stone, \n * 4 units to the 7th stone, and 5 units to the 8th stone.\n * \n * Example 2:\n * \n * [0,1,2,3,4,8,9,11]\n * \n * Return false. There is no way to jump to the last stone as \n * the gap between the 5th and 6th stone is too large.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    bool canCross_recursion(vector<int>& stones, int curr, int last_jump) {\n        for(int i=curr+1; i<stones.size(); i++){\n            int next_jump = stones[i] - stones[curr];\n            //the minimal jump is far exceed the current node, go to check next node.\n            if (next_jump < last_jump - 1) continue;\n            //cannot reach this one, then simple reture false;\n            if (next_jump > last_jump + 1) return false;\n            \n            if (i == stones.size() - 1 || canCross_recursion(stones, i, next_jump)) return true;\n        }\n        return false;\n    }\n    \n    bool canCross_recursion_with_cache(vector<int>& stones, int curr, int last_jump, \n                                        unordered_map<int, unordered_map<int, bool>>& cache) \n    {\n        //check the cache is hitted ?\n        if (cache.find(curr) != cache.end() && cache[curr].find(last_jump)!=cache[curr].end()) {\n            return cache[curr][last_jump];\n        }\n        \n        for(int i=curr+1; i<stones.size(); i++){\n            int next_jump = stones[i] - stones[curr];\n            if (next_jump < last_jump - 1) continue;\n            if (next_jump > last_jump + 1) break;\n            if (i == stones.size() - 1 || canCross_recursion_with_cache(stones, i, next_jump, cache)) {\n                cache[curr][last_jump] = true;\n                return true;\n            }\n        }\n        cache[curr][last_jump] = false;\n        return false;\n    }\n    \n    bool canCross_non_recursion(vector<int>& stones) {\n        \n        // the `jumps` map store the all possible `last jumps`\n        unordered_map<int, unordered_set<int>> jumps = {{0, {0}}};\n        \n        for(int i=0; i<stones.size(); i++) {\n            if (jumps.find(i) == jumps.end()){ \n                continue;\n            }\n            //for each possible last jump which reach the current node.\n            for(int last_jump : jumps[i]) {\n                //find the next nodes can be reached.\n                for (int j=i+1; j < stones.size(); j++) {\n                    //ingore the rest node which cannot be reached\n                    if (stones[i] + last_jump + 1 < stones[j]) break;\n                    \n                    // evaluated three possbile jumps for next node \n                    for (int next_jump  = last_jump - 1;   next_jump <= last_jump + 1;  next_jump++)  {\n                        if ( stones[i] + next_jump  == stones[j] ) {\n                            jumps[j].insert(next_jump);\n                        }\n                    }\n                        \n                }\n            }\n        }\n        \n        return jumps.find(stones.size()-1)!=jumps.end();\n    }\n    \n    bool canCross(vector<int>& stones) {\n        \n        //Burst Force solution -- accepted ~500ms\n        return canCross_non_recursion(stones);\n        \n        //DFS with cache solution - accepted ~160ms\n        unordered_map<int, unordered_map<int, bool>> cache;\n        return canCross_recursion_with_cache(stones, 0, 0, cache);\n        \n        // Time Limit Error \n        return canCross_recursion(stones, 0, 0); \n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/gameOfLife/GameOfLife.cpp",
    "content": "// Source : https://leetcode.com/problems/game-of-life/\n// Author : Hao Chen\n// Date   : 2019-03-20\n\n/***************************************************************************************************** \n *\n * According to the Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular \n * automaton devised by the British mathematician John Horton Conway in 1970.\"\n * \n * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell \n * interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules \n * (taken from the above Wikipedia article):\n * \n * \tAny live cell with fewer than two live neighbors dies, as if caused by under-population.\n * \tAny live cell with two or three live neighbors lives on to the next generation.\n * \tAny live cell with more than three live neighbors dies, as if by over-population..\n * \tAny dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n * \n * Write a function to compute the next state (after one update) of the board given its current state. \n * The next state is created by applying the above rules simultaneously to every cell in the current \n * state, where births and deaths occur simultaneously.\n * \n * Example:\n * \n * Input: \n * [\n *   [0,1,0],\n *   [0,0,1],\n *   [1,1,1],\n *   [0,0,0]\n * ]\n * Output: \n * [\n *   [0,0,0],\n *   [1,0,1],\n *   [0,1,1],\n *   [0,1,0]\n * ]\n * \n * Follow up:\n * \n * \tCould you solve it in-place? Remember that the board needs to be updated at the same time: \n * You cannot update some cells first and then use their updated values to update other cells.\n * \tIn this question, we represent the board using a 2D array. In principle, the board is \n * infinite, which would cause problems when the active area encroaches the border of the array. How \n * would you address these problems?\n * \n ******************************************************************************************************/\n\n\nclass Solution {\npublic:\n    // the problem here is we need store two states in one cell,\n    // one is the original state, another is the new state\n    // So, we could store the state into the bit.\n    //  - Old State: the first  bit from the right\n    //  - New State: the second bit from the right\n    void liveCheck(vector<vector<int>>& board, int r, int c) {\n        int cnt = 0;\n        for (int i=r-1; i<=r+1; i++) {\n            if (i < 0 || i>=board.size()) continue;\n            for (int j=c-1; j<=c+1; j++) {\n                if (j<0 || j>=board[0].size() || (i==r && j==c)) continue;\n                if ( board[i][j] & 1 ) cnt++;\n            }\n        }\n\n        //live -> die\n        //if (board[r][c]==1 && (cnt < 2 || cnt > 3)) board[r][c] = 1;\n\n        //live -> live\n        if ( board[r][c] == 1 && (cnt == 2 || cnt == 3) ) board[r][c] = 3;\n\n        //die -> live\n        if ( board[r][c] == 0 && cnt == 3 ) board[r][c] = 2;\n\n    }\n\n    void gameOfLife(vector<vector<int>>& board) {\n        for (int i=0; i<board.size(); i++) {\n            for (int j=0; j<board[0].size(); j++) {\n                liveCheck(board, i, j);\n            }\n        }\n\n        for (int i=0; i<board.size(); i++) {\n            for (int j=0; j<board[0].size(); j++) {\n                board[i][j] >>= 1;\n            }\n\n        }\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/gasStation/gasStation.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/gas-station/\n// Author : Hao Chen\n// Date   : 2014-10-11\n\n/********************************************************************************** \n* \n* There are N gas stations along a circular route, where the amount of gas at station i is gas[i].\n* \n* You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to \n* its next station (i+1). You begin the journey with an empty tank at one of the gas stations.\n* \n* Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.\n* \n* Note:\n* The solution is guaranteed to be unique.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {\n        int current = 0;\n        int start = gas.size(); //start from the end to beginning\n        int total = 0;\n        \n        do {\n            if (total + gas[current] - cost[current] >= 0) {\n                total += (gas[current] - cost[current]);\n                current++; // can go from current to current+1\n            }else{\n                start--; //not enough gas, try to start the one before origin start point.\n                total += (gas[start] - cost[start]);\n            }\n        } while(current != start);\n        \n        return total>=0 ? start % gas.size() : -1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/generateParentheses/generateParentheses.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/generate-parentheses/\n// Author : Hao Chen\n// Date   : 2014-06-29\n\n/********************************************************************************** \n* \n* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n* \n* For example, given n = 3, a solution set is:\n* \n* \"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\nvoid generator(vector<string>& result, int left, int right, string s);\nvector<string> generateParenthesis(int n) {\n    \n    vector<string> result;\n    string s;\n    generator(result, n, n, s);\n    return result;\n}\n\nvoid generator(vector<string>& result, int left, int right, string s){\n    if (left==0 && right==0){\n        result.push_back(s);\n        return;\n    }\n    if (left>0){\n        generator(result, left-1, right, s+'(');\n    }\n    if (right>0 && right>left){\n        generator(result, left, right-1, s+')');\n    }\n}\n    \nvoid printResult(vector<string>& result)\n{\n    for(int i=0; i<result.size(); i++){\n        cout << result[i] <<endl;\n    }\n}\n\nint main(int argc, char** argv) \n{\n    int n=3;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector<string> r = generateParenthesis(n);\n    printResult(r);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/grayCode/grayCode.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/gray-code/\n// Author : Hao Chen\n// Date   : 2014-06-20\n\n/********************************************************************************** \n* \n* The gray code is a binary numeral system where two successive values differ in only one bit.\n* \n* Given a non-negative integer n representing the total number of bits in the code, \n* print the sequence of gray code. A gray code sequence must begin with 0.\n* \n* For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:\n* \n* 00 - 0\n* 01 - 1\n* 11 - 3\n* 10 - 2\n* \n* Note:\n* For a given n, a gray code sequence is not uniquely defined.\n* \n* For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.\n* \n* For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n/*\n * I designed the following stupid algorithm base on the blow observation\n * \n * I noticed I can use a `mirror-like` binary tree to figure out the gray code.\n * \n * For example:\n * \n *           0      \n *        __/ \\__   \n *       0       1  \n *      / \\     / \\ \n *     0   1   1   0\n * So, the gray code as below: (top-down, from left to right)\n *\n *     0 0 0 \n *     0 0 1\n *     0 1 1\n *     0 1 0\n * \n *                  0\n *            _____/ \\_____\n *           0             1\n *        __/ \\__       __/ \\__\n *       0       1     1       0\n *      / \\     / \\   / \\     / \\\n *     0   1   1   0 0   1   1   0\n * \n * So, the gray code as below:\n *\n *     0 0 0 0 \n *     0 0 0 1\n *     0 0 1 1\n *     0 0 1 0\n *     0 1 1 0\n *     0 1 1 1 \n *     0 1 0 1\n *     0 1 0 0\n */\nvector<int> grayCode01(int n) {\n    vector<int> v;\n    //n = 1<<n;\n    \n    int x =0;   \n    v.push_back(x); \n    for(int i=0; i<n; i++){\n        int len = v.size();\n        for (int j=0; j<len; j++){\n            x = v[j]<<1;\n            if (j%2==0){\n                v.push_back(x);\n                v.push_back(x+1);\n            }else{\n                v.push_back(x+1);\n                v.push_back(x);\n            }\n        }\n        v.erase(v.begin(), v.begin()+len);\n    }\n     \n    return v;\n}\n\n/*\n * Actually, there is a better way.\n * The mathematical way is: (num >> 1) ^ num; \n * Please refer to http://en.wikipedia.org/wiki/Gray_code\n */\nvector<int> grayCode02(int n) {\n    vector<int> ret;   \n    int size = 1 << n;   \n    for(int i = 0; i < size; ++i) {\n        ret.push_back((i >> 1)^i);   \n    }\n    return ret;   \n}\n\n//random invoker\nvector<int> grayCode(int n) {\n    srand(time(0));\n    if (rand()%2){\n        return grayCode01(n);\n    }\n    return grayCode02(n);\n}\n\nvoid printBits(int n, int len){\n    for(int i=len-1; i>=0; i--) {\n        if (n & (1<<i)) {\n            printf(\"1\");\n        }else{\n            printf(\"0\");\n        }\n    }\n}\n\nvoid printVector(vector<int>& v, int bit_len)\n{\n    vector<int>::iterator it;\n\n    for(it=v.begin(); it!=v.end(); ++it){\n        //bitset<bit_len> bin(*it);\n        printBits(*it, bit_len);\n        cout <<  \" \";\n        //cout << *it <<  \" \";\n    }\n    cout << endl;\n}\n\nint main(int argc, char** argv)\n{\n    int n = 2;\n    if (argc>1){\n        n = atoi(argv[1]); \n    }\n    vector<int> v = grayCode(n);\n    printVector(v, n);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/greatestCommonDivisorOfStrings/GreatestCommonDivisorOfStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/greatest-common-divisor-of-strings/\n// Author : Hao Chen\n// Date   : 2020-07-19\n\n/***************************************************************************************************** \n *\n * For strings S and T, we say \"T divides S\" if and only if S = T + ... + T  (T concatenated with \n * itself 1 or more times)\n * \n * Return the largest string X such that X divides str1 and X divides str2.\n * \n * Example 1:\n * \n * Input: str1 = \"ABCABC\", str2 = \"ABC\"\n * Output: \"ABC\"\n * \n * Example 2:\n * \n * Input: str1 = \"ABABAB\", str2 = \"ABAB\"\n * Output: \"AB\"\n * \n * Example 3:\n * \n * Input: str1 = \"LEET\", str2 = \"CODE\"\n * Output: \"\"\n * \n * Note:\n * \n * \t1 <= str1.length <= 1000\n * \t1 <= str2.length <= 1000\n * \tstr1[i] and str2[i] are English uppercase letters.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n\n\n    // Euclidean algorithm\n    // https://en.wikipedia.org/wiki/Euclidean_algorithm\n    // recursive way\n    int findGCD_r(int a, int b) {\n        if (a == 0)\n            return b;\n        return gcd(b % a, a);\n    }\n    // non-recursive way\n    int findGCD(int a, int b) {\n        int t = 1;\n        while(t != 0) {\n            t = a % b;\n            a = b;\n            b = t;\n        }\n        return a;\n    }\n\n    bool isStrRepeatByLen(string& s, int len) {\n        if (s.size() == len) return true;\n        if (s.size() % len != 0 ) return false;\n        for (int l=0; l<len; l++) {\n            for (int i=1; i<s.size()/len; i++) {\n                if (s[l] != s[i*len+l]) return false;\n            }\n        }\n        return true;\n    }\n\n    bool strPrefixComp(string& s1, string &s2, int len){\n        for(int i=0; i<len; i++) {\n            if (s1[i] != s2[i]) return false;\n        }\n        return true;\n    }\npublic:\n    string gcdOfStrings(string s1, string s2) {\n\n        int gcd = findGCD(s1.size(), s2.size());\n\n        if (strPrefixComp(s1, s2, gcd) &&\n            isStrRepeatByLen(s1, gcd)&&\n            isStrRepeatByLen(s2, gcd) ){\n            return s2.substr(0,gcd);\n        }\n\n        return \"\";\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/h-Index/h-Index.II.cpp",
    "content": "// Source : https://leetcode.com/problems/h-index-ii/\n// Author : Hao Chen\n// Date   : 2015-11-08\n\n/*************************************************************************************** \n *\n * Follow up for H-Index: What if the citations array is sorted in ascending order?\n * Could you optimize your algorithm?\n *               \n ***************************************************************************************/\n\n\n\nclass Solution {\npublic:\n    // binary search - O(log(n))\n    int hIndex(vector<int>& citations) {\n        int n = citations.size();\n        int low = 0, high = n-1;\n        \n        while( low <= high ) {\n            int mid = low + (high-low)/2;\n            if (citations[mid] == n - mid) {\n                return n - mid;\n            }else if (citations[mid] > n-mid){\n                high = mid - 1;\n            }else {\n                low = mid + 1;\n            }\n        }\n        return n-low;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/h-Index/h-Index.cpp",
    "content": "// Source : https://leetcode.com/problems/h_index/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-10-22\n\n/*************************************************************************************** \n *\n * Given an array of citations (each citation is a non-negative integer) of a \n * researcher, write a function to compute the researcher's h-index.\n * \n * According to the definition of h-index on Wikipedia: \"A scientist has index h if h of\n * his/her N papers have at least h citations each, and the other N − h papers have no\n * more than h citations each.\"\n * \n * For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 \n * papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\n * Since the researcher has 3 papers with at least 3 citations each and the remaining \n * two with no more than 3 citations each, his h-index is 3.\n * \n * Note: If there are several possible values for h, the maximum one is taken as the \n * h-index.\n *               \n ***************************************************************************************/\n\n\n\n/* \n * Solutions\n * =========\n *\n * A simple solution would be to sort the vector and then run through it starting with\n * the last element. At every step we need to check whether this element is not less than\n * the remaining number of elements bigger than it(including itself) and all the values of\n * the other elements smaller than it are not more than that number. The h_index is this\n * number of elements bigger than it(including itself).\n * \n * Time Complexity: O(N log N)\n * Space Complexity: O(1)\n * \n */\n#include <algorithm>\nclass Solution {\npublic:\n    int hIndex(vector<int>& citations) {\n        return hIndex02(citations);\n        return hIndex01(citations);\n    }\n    int hIndex01(vector<int>& citations) {\n        sort(citations.begin(), citations.end());\n        int h_index = 0;\n        for(int i = citations.size() - 1; i >= 0; i--)\n            if(citations[i] >= citations.size() - i && (i - 1 < 0 || citations[i - 1] <= citations.size() - i))\n                h_index = citations.size() - i;\n        return h_index;\n    }\n\n    // same solution but a bit different implemtation\n    int hIndex02(vector<int>& citations) {\n        sort(citations.begin(), citations.end());\n        int n = citations.size();\n        for (int i=0; i<n; i++){\n            if (citations[i] >= n-i){\n                return n-i;\n            }\n        }\n        return 0;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/happyNumber/HappyNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/happy-number/\n// Author : Hao Chen\n// Date   : 2015-06-08\n\n/********************************************************************************** \n * \n * Write an algorithm to determine if a number is \"happy\".\n * \n * A happy number is a number defined by the following process: Starting with any positive integer, \n * replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 \n * (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this \n * process ends in 1 are happy numbers.\n * \n * Example: 19 is a happy number\n * \n * 1^2 + 9^2 = 82\n * 8^2 + 2^2 = 68\n * 6^2 + 8^2 = 100\n * 1^2 + 0^2 + 0^2 = 1\n * \n * Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n#include <stdlib.h>\n#include <iostream>\n#include <map>\nusing namespace std;\n\nint squares(int n) {\n    int result = 0;\n    int sq = 0;\n    for (; n>0; n/=10) {\n        sq = n%10;\n        result += (sq * sq);\n    }\n    return result;\n}\n\nbool isHappy(int n) {\n\n    if (n==1) return true;\n\n    map<int, bool> m;\n    m[n]=true;\n\n    while (n!=1) {\n        n = squares(n);\n        //cout << n << endl;\n        if (m.find(n) != m.end()){\n            return false;\n        }\n        m[n] = true;\n    }\n\n    return true;\n}\n\n\nint main(int argc, char** argv) \n{\n    int n = 2;\n    if (argc > 1){\n        n = atoi(argv[1]);\n    }\n    cout << n << (isHappy(n) ? \" is \" : \" isn't \") << \"a happy number\" << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/houseRobber/houseRobber.II.cpp",
    "content": "// Source : https://leetcode.com/problems/house-robber-ii/\n// Author : Hao Chen\n// Date   : 2015-06-10\n\n/********************************************************************************** \n * \n * Note: This is an extension of House Robber.\n * \n * After robbing those houses on that street, the thief has found himself a new place \n * for his thievery so that he will not get too much attention. This time, all houses \n * at this place are arranged in a circle. That means the first house is the neighbor \n * of the last one. Meanwhile, the security system for these houses remain the same as\n * for those in the previous street. \n * \n * Given a list of non-negative integers representing the amount of money of each house, \n * determine the maximum amount of money you can rob tonight without alerting the police.\n * \n * Credits:Special thanks to @Freezen for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    int orginal_rob(vector<int> &money, int start, int end) {\n        int n2=0; \n        int n1=0; \n        \n        for (int i=start; i<end; i++){\n            int current = max(n1, n2 + money[i]);\n            n2 = n1;\n            n1 = current;\n        }\n        return n1;\n    }\n    \n    int rob(vector<int>& nums) {\n        int n = nums.size();\n        switch (n) {\n            case 0:\n                return 0;\n            case 1:\n                return nums[0];\n            case 2:\n                return max(nums[0], nums[1]);\n            default:\n                /*\n                 * the idea is we cannot rob[0] and rob[n-1] at same time\n                 * so, we rob [0 .. n-2] or [1 .. n-1], can return the maxinum one.\n                 */\n                int m1 = orginal_rob(nums, 0, n-1);\n                int m2 = orginal_rob(nums, 1, n);\n                \n                return max(m1, m2);\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/houseRobber/houseRobber.cpp",
    "content": "// Source : https://leetcode.com/problems/house-robber/\n// Author : Hao Chen\n// Date   : 2015-04-07\n\n/********************************************************************************** \n * \n * You are a professional robber planning to rob houses along a street. Each house has \n * a certain amount of money stashed, the only constraint stopping you from robbing \n * each of them is that adjacent houses have security system connected and it will \n * automatically contact the police if two adjacent houses were broken into on the same night.\n * \n * Given a list of non-negative integers representing the amount of money of each house, \n * determine the maximum amount of money you can rob tonight without alerting the police.\n * \n *               \n **********************************************************************************/\n\n#include <time.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;    \n/*\n * Dynamic Programming\n *\n * We can easy find the recurive fomular:\n *\n *     dp[n] = max( \n *                    dp[n-1],   // the previous house has been robbed. \n *                    dp[n-2] + money[n]  // the previous house has NOT been robbed.\n *                )\n *                  \n * The initalization is obvious:\n *     dp[1] = money[1]\n *     dp[2] = max(money[1], money[2])\n *\n */\nint rob1(vector<int> &money) {\n\n    int n = money.size();\n    if (n==0) return 0;\n\n    vector<int> dp(n, 0);\n    if (n>=1) dp[0] = money[0];\n    if (n>=2) dp[1] = max(money[0], money[1]);\n\n    for (int i=2; i<n; i++){\n        dp[i] = max(dp[i-1], dp[i-2] + money[i]);\n    }\n    return dp[n-1];\n}\n/*\n * Acutally, we no need to allocate an additional array for DP.\n * we can only use several variables to record previous steps\n */\n\nint rob2(vector<int> &money) {\n    int n2=0; // dp[i-2];\n    int n1=0; // dp[i-1];\n\n    for (int i=0; i<money.size(); i++){\n        int current = max(n1, n2 + money[i]);\n        n2 = n1;\n        n1 = current;\n    }\n    return n1;\n}\n\nint rob(vector<int> &num) {\n    if (rand()%2)\n        return rob1(num);\n    return rob2(num);\n}\n\nvoid printVector( vector<int> &v ){\n    cout << '[' ;\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] << (i==v.size()-1 ? \" \" :\", \");\n    }\n    cout << ']' << endl;\n}\n\nint main(int argc, char** argv) {\n    srand(time(0));\n    vector<int> money;\n    if (argc>1){\n        for (int i=1; i<argc; i++) {\n            money.push_back(atoi(argv[i]));\n        }\n    }else{\n        money.push_back(2);\n        money.push_back(1);\n        money.push_back(3);\n        money.push_back(4);\n    }\n\n    printVector(money);\n    cout << rob(money) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/houseRobber/houseRobberIII.cpp",
    "content": "// Source : https://leetcode.com/problems/house-robber-iii/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2016-04-29\n\n/*************************************************************************************** \n *\n * The thief has found himself a new place for his thievery again. There is only one\n * entrance to this area, called the \"root.\" Besides the root, each house has one and\n * only one parent house. After a tour, the smart thief realized that \"all houses in\n * this place forms a binary tree\". It will automatically contact the police if two \n * directly-linked houses were broken into on the same night.\n * \n * Determine the maximum amount of money the thief can rob tonight without alerting the\n * police.\n * \n * Example 1:\n *     3\n *    / \\\n *   2   3\n *    \\   \\ \n *     3   1\n * Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\n * Example 2:\n *     3\n *    / \\\n *   4   5\n *  / \\   \\ \n * 1   3   1\n * Maximum amount of money the thief can rob = 4 + 5 = 9.\n * Credits:\n * Special thanks to @dietpepsi for adding this problem and creating all test cases.\n * \n ***************************************************************************************/\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n  /* \n * Solution 1 - O(N log N)\n * =========\n *\n * We can use a recursive function that computes the solution for every node of the tree \n * using the previous solutions calculated for the left and right subtrees. At every step\n * we have 2 options:\n *\n * 1) Take the value of the current node + the solution of the left and right subtrees of\n * each of the left and right children of the current node.\n * 2) Take the solution of the left and right subtrees of the current node, skipping over\n * its value.\n *\n * This way we can make sure that we do not pick 2 adjacent nodes.\n *\n * If we implemented this right away we would get TLE. Thus, we need to optimize the\n * algorithm. One key observation would be that we only need to compute the solution for\n * a certain node once. We can use memoization to calculate every value once and then\n * retrieve it when we get subsequent calls. As the header of the recursive function\n * doesn't allow additional parameters we can use a map to link every node(a pointer) to\n * its solution(an int). For every call the map lookup of an element and its insertion\n * take logarithmic time and there are a constant number of calls for each node. Thus, the\n * algorithm takes O(N log N) time to finish.\n * \n */\nclass Solution {\npublic:\n    map<TreeNode*, int> dict;\n    int rob(TreeNode* root) {\n        if(root == NULL)\n            return 0;\n        else if(dict.find(root) == dict.end())\n        {\n            int lwith = rob(root->left);\n            int rwith = rob(root->right);\n            int lwithout = 0, rwithout = 0;\n            if(root->left != NULL)\n                lwithout = rob(root->left->left) + rob(root->left->right);\n            if(root->right != NULL)\n                rwithout = rob(root->right->left) + rob(root->right->right);\n            //cout << lwith << \" \" << rwith << \" \" << lwithout << \" \" << rwithout << '\\n';\n            dict[root] = max(root->val + lwithout + rwithout, lwith + rwith);\n        }\n        return dict[root];\n    }\n};\n\n\n// Another implementation - Hao Chen\n\nclass Solution {\npublic:\n    int max(int a, int b) {\n        return a > b ? a: b;\n    }\n    int max(int a, int b, int c) {\n        return max(a, max(b,c));\n    }\n    int max(int a, int b, int c, int d) {\n        return max(a, max(b, max(c,d)));\n    }\n\n    void rob_or_not(TreeNode* root, int& max_robbed, int& max_not_robbed) {\n        // NULL room return 0;\n        if (root == NULL) {\n            max_robbed = max_not_robbed = 0;\n            return ;\n        }\n\n        // we have two options, rob current room or not.\n        int max_left_robbed, max_left_not_robbed;\n        int max_right_robbed, max_right_not_robbed;\n        rob_or_not(root->left, max_left_robbed, max_left_not_robbed);\n        rob_or_not(root->right, max_right_robbed, max_right_not_robbed);\n\n        // If root is robbed, then both left and right must not be robbed.\n        max_robbed = root->val + max_left_not_robbed + max_right_not_robbed;\n\n        // If root is not robbed, then 4 combinations are possible:\n\t\t//     left is robbed or not and right is either robbed or not robbed,\n        max_not_robbed = max(max_left_robbed + max_right_robbed,\n                             max_left_robbed + max_right_not_robbed,\n                             max_left_not_robbed + max_right_robbed,\n                             max_left_not_robbed + max_right_not_robbed);\n\n    }\n    int rob(TreeNode* root) {\n        int robbed, not_robbed;\n        rob_or_not(root, robbed, not_robbed);\n        return max(robbed, not_robbed);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/implementQueueUsingStacks/ImplementQueueUsingStacks.cpp",
    "content": "// Source : https://leetcode.com/problems/implement-queue-using-stacks/\n// Author : Hao Chen\n// Date   : 2015-07-16\n\n/********************************************************************************** \n * \n * Implement the following operations of a queue using stacks.\n * \n * push(x) -- Push element x to the back of queue.\n * \n * pop() -- Removes the element from in front of queue.\n * \n * peek() -- Get the front element.\n * \n * empty() -- Return whether the queue is empty.\n * \n * Notes:\n * \n * You must use only standard operations of a stack -- which means only push to top, \n * peek/pop from top, size, and is empty operations are valid.\n\n * Depending on your language, stack may not be supported natively. You may simulate a \n * stack by using a list or deque (double-ended queue), as long as you use only \n * standard operations of a stack.\n\n * You may assume that all operations are valid (for example, no pop or peek operations \n * will be called on an empty queue).\n *               \n **********************************************************************************/\n\nclass Queue {\npublic:\n    // Push element x to the back of queue.\n    void push(int x) {\n        s1.push(x);\n    }\n\n    // Removes the element from in front of queue.\n    void pop(void) {\n        transfer(s1, s2);\n        s2.pop();\n        transfer(s2, s1);\n    }\n\n    // Get the front element.\n    int peek(void) {\n        transfer(s1, s2);\n        int ret = s2.top();\n        transfer(s2, s1);\n        return ret;\n    }\n\n    // Return whether the queue is empty.\n    bool empty(void) {\n        return s1.empty();\n    }\nprivate:\n    stack<int> s1, s2;\n    void transfer(stack<int>& s1, stack<int>& s2) {\n        while(!s1.empty()){\n            s2.push(s1.top());\n            s1.pop();\n        }\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/implementStackUsingQueues/ImplementStackUsingQueues.cpp",
    "content": "// Source : https://leetcode.com/problems/implement-stack-using-queues/\n// Author : Hao Chen\n// Date   : 2015-06-13\n\n/********************************************************************************** \n * \n * Implement the following operations of a stack using queues.\n * \n * push(x) -- Push element x onto stack.\n * \n * pop() -- Removes the element on top of the stack.\n * \n * top() -- Get the top element.\n * \n * empty() -- Return whether the stack is empty.\n * \n * Notes:\n * \n * You must use only standard operations of a queue -- which means only push to back, \n * peek/pop from front, size, and is empty operations are valid.\n *\n * Depending on your language, queue may not be supported natively. You may simulate \n * a queue by using a list or deque (double-ended queue), as long as you use only \n * standard operations of a queue.\n *\n * You may assume that all operations are valid (for example, no pop or top operations \n * will be called on an empty stack).\n * \n * Update (2015-06-11):\n * The class name of the Java function had been updated to MyStack instead of Stack.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and all test cases.\n *               \n **********************************************************************************/\n\n\nclass Stack {\n    public:\n        // Push element x onto stack.\n        void push(int x) {\n            nums.push(x);\n        }\n        // Removes the element on top of the stack.\n        void pop() {\n            if (!empty()) {\n                int len = nums.size()-1;\n                //Don't treat the \"-->\" is a new operator. ;-)\n                while ( len-->0) {\n                    nums.push(nums.front());\n                    nums.pop();\n                }\n                nums.pop();\n            }\n        }\n        // Get the top element.\n        int top() {\n            return nums.back();\n        }\n        // Return whether the stack is empty.\n        bool empty() {\n            return nums.empty();\n        }\n\n    private:\n        queue<int> nums;\n};\n"
  },
  {
    "path": "algorithms/cpp/implementTriePrefixTree/ImplementTriePrefixTree.cpp",
    "content": "// Source : https://leetcode.com/problems/implement-trie-prefix-tree/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Implement a trie with insert, search, and startsWith methods.\n * \n * Note:\n * You may assume that all inputs are consist of lowercase letters a-z.\n * \n *               \n **********************************************************************************/\n\n\nclass TrieNode {\npublic:\n    // Initialize your data structure here.\n    TrieNode():isWord(false) {   }\n    unordered_map<char, TrieNode*> children;\n    bool isWord;\n};\n\nclass Trie {\npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n\n    // Inserts a word into the trie.\n    void insert(string s) {\n        if (s.size()<=0) return;\n        TrieNode * node = root;\n        for (int i=0; i<s.size(); i++) {\n            if (node->children.find(s[i]) == node->children.end()){\n                node->children[s[i]] = new TrieNode();\n            }\n            node = node->children[s[i]];\n        }\n        node->isWord = true;\n    }\n\n    // Returns if the word is in the trie.\n    bool search(string key) {\n        return retrieve(key, true);\n    }\n\n    // Returns if there is any word in the trie\n    // that starts with the given prefix.\n    bool startsWith(string prefix) {\n        return retrieve(prefix, false);\n    }\n\nprivate:\n\n    inline bool retrieve(const string& key, bool isWord) {\n        if (key.size() <= 0) return false;\n        TrieNode * node = root;\n        for (int i=0; i<key.length(); i++) {\n            if (node->children.find(key[i]) == node->children.end()) {\n                return false;\n            }\n            node = node->children[key[i]];\n        }\n        return isWord ? node->isWord : true;\n    }\n\n    TrieNode* root;\n};\n\n// Your Trie object will be instantiated and called as such:\n// Trie trie;\n// trie.insert(\"somestring\");\n// trie.search(\"key\");\n"
  },
  {
    "path": "algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp",
    "content": "// Source : https://leetcode.com/problems/increasing-triplet-subsequence/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2016-02-27\n\n/*************************************************************************************** \n *\n * Given an unsorted array return whether an increasing subsequence of length 3 exists\n * or not in the array.\n * \n * Formally the function should:\n * Return true if there exists i, j, k \n * such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.\n * Your algorithm should run in O(n) time complexity and O(1) space complexity.\n * \n * Examples:\n * Given [1, 2, 3, 4, 5],\n * return true.\n * \n * Given [5, 4, 3, 2, 1],\n * return false.\n * \n ***************************************************************************************/\nclass Solution {\npublic:\n    bool increasingTriplet(vector<int>& nums) {\n        bool solution = false;\n        if(nums.size())\n        {\n            int first = nums[0];\n            int second = 0x7fffffff; //MAX_INT so we can always find something smaller than it\n            for(int i = 1; i < nums.size() && !solution; i++)\n            {\n                if(nums[i] > second)\n                    solution = true;\n                else if(nums[i] > first && nums[i] < second)\n                    second = nums[i];\n                else if(nums[i] < first)\n                    first = nums[i];\n            }\n        }\n        return solution;\n    }\n};\n\n\n//Hao Chen's implementation\nclass Solution {\npublic:\n    bool increasingTriplet(vector<int>& nums) {\n        if (nums.size() < 3) return false;\n        \n        int first=INT_MAX, second = INT_MAX;\n        \n        for(int i=0; i<nums.size(); i++) {\n            if ( first > nums[i] ) {\n                first = nums[i];\n            }else if ( first < nums[i] && nums[i] < second) {\n                second = nums[i];\n            }else if (nums[i] > second){\n                return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/incrementalMemoryLeak/IncrementalMemoryLeak.cpp",
    "content": "// Source : https://leetcode.com/problems/incremental-memory-leak/\n// Author : Hao Chen\n// Date   : 2021-05-22\n\n/***************************************************************************************************** \n *\n * You are given two integers memory1 and memory2 representing the available memory in bits on two \n * memory sticks. There is currently a faulty program running that consumes an increasing amount of \n * memory every second.\n * \n * At the i^th second (starting from 1), i bits of memory are allocated to the stick with more \n * available memory (or from the first memory stick if both have the same available memory). If \n * neither stick has at least i bits of available memory, the program crashes.\n * \n * Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in \n * seconds) when the program crashed and memory1crash and memory2crash are the available bits of \n * memory in the first and second sticks respectively.\n * \n * Example 1:\n * \n * Input: memory1 = 2, memory2 = 2\n * Output: [3,1,0]\n * Explanation: The memory is allocated as follows:\n * - At the 1^st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of \n * available memory.\n * - At the 2^nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of \n * available memory.\n * - At the 3^rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n * \n * Example 2:\n * \n * Input: memory1 = 8, memory2 = 11\n * Output: [6,0,4]\n * Explanation: The memory is allocated as follows:\n * - At the 1^st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of \n * available memory.\n * - At the 2^nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of \n * available memory.\n * - At the 3^rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of \n * available memory.\n * - At the 4^th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of \n * available memory.\n * - At the 5^th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of \n * available memory.\n * - At the 6^th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n * \n * Constraints:\n * \n * \t0 <= memory1, memory2 <= 2^31 - 1\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> memLeak(int memory1, int memory2) {\n        int i=0;\n        while(++i) {\n            int& himem = memory1 >= memory2 ? memory1 : memory2;\n            if (himem < i) break;\n            himem -= i;\n        }\n        vector<int> result={i, memory1, memory2};\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp",
    "content": "// Source : https://leetcode.com/problems/insert-delete-getrandom-o1/\n// Author : Hao Chen\n// Date   : 2016-08-25\n\n/*************************************************************************************** \n *\n * Design a data structure that supports all following operations in average O(1) time.\n * \n * insert(val): Inserts an item val to the set if not already present.\n * remove(val): Removes an item val from the set if present.\n * getRandom: Returns a random element from current set of elements. Each element must \n * have the same probability of being returned.\n * \n * Example:\n * \n * // Init an empty set.\n * RandomizedSet randomSet = new RandomizedSet();\n * \n * // Inserts 1 to the set. Returns true as 1 was inserted successfully.\n * randomSet.insert(1);\n * \n * // Returns false as 2 does not exist in the set.\n * randomSet.remove(2);\n * \n * // Inserts 2 to the set, returns true. Set now contains [1,2].\n * randomSet.insert(2);\n * \n * // getRandom should return either 1 or 2 randomly.\n * randomSet.getRandom();\n * \n * // Removes 1 from the set, returns true. Set now contains [2].\n * randomSet.remove(1);\n * \n * // 2 was already in the set, so return false.\n * randomSet.insert(2);\n * \n * // Since 1 is the only number in the set, getRandom always return 1.\n * randomSet.getRandom();\n ***************************************************************************************/\n\n\nclass RandomizedSet {\npublic:\n    /** Initialize your data structure here. */\n    RandomizedSet() {\n        srand(time(NULL));\n    }\n    \n    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */\n    bool insert(int val) {\n        if ( find(val) ) return false; \n        data.push_back(val);\n        valpos[val] = data.size() - 1;\n        return true;\n    }\n    \n    /** Removes a value from the set. Returns true if the set contained the specified element. */\n    bool remove(int val) {\n        if ( !find(val) ) return false; \n        \n\t\t/*\n         * Tricky\n         * ------\n         * 1) Copy the data from the last one to the place need be removed.\n         * 2) Remove the last one.\n         */\n        int _idx = valpos[val];\n        int _val = data.back();\n        \n        data[_idx] = _val;\n        valpos[_val] = _idx;\n        \n        valpos.erase(val);\n        data.pop_back();\n        return true;\n    }\n    \n    /** Get a random element from the set. */\n    int getRandom() {\n        return data[ rand() % data.size() ];\n    }\n    \nprivate:    \n    unordered_map<int, int> valpos; //value position map\n    vector<int> data;\n    bool find(int val) {\n        return (valpos.find(val) != valpos.end());\n    }\n    \n};\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * bool param_1 = obj.insert(val);\n * bool param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n"
  },
  {
    "path": "algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1DuplicatesAllowed.cpp",
    "content": "// Source : https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/\n// Author : Hao Chen\n// Date   : 2016-08-25\n\n/*************************************************************************************** \n *\n * Design a data structure that supports all following operations in average O(1) time.\n * Note: Duplicate elements are allowed.\n * \n * insert(val): Inserts an item val to the collection.\n * remove(val): Removes an item val from the collection if present.\n * getRandom: Returns a random element from current collection of elements. The \n * probability of each element being returned is linearly related to the number of same \n * value the collection contains.\n * \n * Example:\n * \n * // Init an empty collection.\n * RandomizedCollection collection = new RandomizedCollection();\n * \n * // Inserts 1 to the collection. Returns true as the collection did not contain 1.\n * collection.insert(1);\n * \n * // Inserts another 1 to the collection. Returns false as the collection contained 1. \n * Collection now contains [1,1].\n * collection.insert(1);\n * \n * // Inserts 2 to the collection, returns true. Collection now contains [1,1,2].\n * collection.insert(2);\n * \n * // getRandom should return 1 with the probability 2/3, and returns 2 with the \n * probability 1/3.\n * collection.getRandom();\n * \n * // Removes 1 from the collection, returns true. Collection now contains [1,2].\n * collection.remove(1);\n * \n * // getRandom should return 1 and 2 both equally likely.\n * collection.getRandom();\n ***************************************************************************************/\n\nclass RandomizedCollection {\npublic:\n    /** Initialize your data structure here. */\n    RandomizedCollection() {\n        srand(time(NULL));\n    }\n    \n    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */\n    bool insert(int val) {\n        data.push_back(val);\n        valpos[val].insert( data.size() - 1 );\n        return (valpos[val].size() == 1);\n    }\n    \n    /** Removes a value from the collection. Returns true if the collection contained the specified element. */\n    bool remove(int val) {\n        // not found\n        if (!find(val)) return false;\n        \n        \n        //same idea with non-duplication version, but need be careful with some edge case\n        int _idx = *(valpos[val].begin());\n        int _val = data.back();\n        \n        valpos[_val].insert(_idx);\n        data[_idx] = _val;\n        \n        valpos[val].erase(_idx);\n        if (valpos[val].size()==0){\n            valpos.erase(val);\n        }\n        \n        data.pop_back();\n        if ( _idx < data.size() ){\n            valpos[_val].erase(data.size());\n            valpos[_val].insert(_idx);\n        }\n        \n        return true;        \n    }\n    \n    /** Get a random element from the collection. */\n    int getRandom() {\n        return data[ rand() % data.size() ];\n    }\nprivate:\n    unordered_map<int, unordered_set<int>> valpos; //value position map\n    vector<int> data;\n    bool find(int val) {\n        return (valpos.find(val) != valpos.end());\n    }\n   \n};\n\n/**\n * Your RandomizedCollection object will be instantiated and called as such:\n * RandomizedCollection obj = new RandomizedCollection();\n * bool param_1 = obj.insert(val);\n * bool param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n"
  },
  {
    "path": "algorithms/cpp/insertInterval/insertInterval.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/insert-interval/\n// Author : Hao Chen\n// Date   : 2014-08-26\n\n/********************************************************************************** \n* \n* Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n* \n* You may assume that the intervals were initially sorted according to their start times.\n* \n* Example 1:\n* Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].\n* \n* Example 2:\n* Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].\n* \n* This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Interval {\n    int start;\n    int end;\n    Interval() : start(0), end(0) {}\n    Interval(int s, int e) : start(s), end(e) {}\n};\n\n//Two factors sorting [start:end]\nbool compare(const Interval& lhs, const Interval& rhs){\n    return (lhs.start==rhs.start) ? lhs.end < rhs.end : lhs.start < rhs.start;\n}\n\nvector<Interval> merge(vector<Interval> &intervals) {\n\n    vector<Interval> result;\n\n    if (intervals.size() <= 0) return result;\n    //sort the inervals. Note: using the customized comparing function.\n    sort(intervals.begin(), intervals.end(), compare);\n    for(int i=0; i<intervals.size(); i++) {\n        int size = result.size();\n        // if the current intervals[i] is overlapped with previous interval.\n        // merge them together\n        if( size>0 && result[size-1].end >= intervals[i].start) {\n            result[size-1].end = max(result[size-1].end, intervals[i].end);\n        }else{\n            result.push_back(intervals[i]);\n        }\n    }\n\n    return result;\n}\n\n//just reuse the solution of \"Merge Intervals\", quite straight forward\nvector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {\n\n    intervals.push_back(newInterval);\n\n    return merge(intervals);\n}\n\nint main(int argc, char**argv)\n{\n    Interval i1(1,2);\n    Interval i2(3,5);\n    Interval i3(6,7);\n    Interval i4(8,10);\n    Interval i5(12,16);\n    vector<Interval> intervals;\n    intervals.push_back(i1);\n    intervals.push_back(i2);\n    intervals.push_back(i3);\n    intervals.push_back(i4);\n    intervals.push_back(i5);\n\n    Interval n(4,9);\n    vector<Interval> r = insert(intervals, n);\n\n    for(int i=0; i<r.size(); i++){\n        cout << \"[ \" << r[i].start << \", \" << r[i].end << \" ] \";\n    }\n    cout <<endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/insertionSortList/insertionSortList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/insertion-sort-list/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Sort a linked list using insertion sort.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *insertionSortList(ListNode *head) {\n    // zero or one element in list\n    if (head == NULL || head->next ==NULL){\n        return head;\n    }\n\n    ListNode *pSorted = NULL;\n    while ( head != NULL  ){\n        /* remember the head */\n        ListNode *pHead = head;\n        /* trailing pointer for efficient splice */\n        ListNode **ppTrail = &pSorted;\n        \n        /* pop head off list */\n        head = head->next;\n        \n        /* splice head into sorted list at proper place */\n        while( *ppTrail!=NULL && pHead->val > (*ppTrail)->val )  {\n            ppTrail = &(*ppTrail)->next;\n        }\n        pHead->next = *ppTrail;\n        *ppTrail = pHead;\n    }\n\n    return pSorted;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 10;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    srand(time(NULL));\n\n    int *a = new int[n];\n    for(int i=0; i<n; i++){\n        a[i] = random()%n + 1;\n    }\n\n    ListNode *p = createList(a, n);\n    printList(p);\n    printList(insertionSortList(p));\n\n    delete[] a;\n}\n"
  },
  {
    "path": "algorithms/cpp/integerBreak/IntegerBreak.cpp",
    "content": "// Source : https://leetcode.com/problems/integer-break/\n// Author : Hao Chen\n// Date   : 2016-05-29\n\n/*************************************************************************************** \n *\n * Given a positive integer n, break it into the sum of at least two positive integers \n * and maximize the product of those integers. Return the maximum product you can get.\n * \n * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 \n * + 4).\n * \n * Note: you may assume that n is not less than 2.\n * \n *   There is a simple O(n) solution to this problem.\n *   You may check the breaking results of n ranging from 7 to 10 to discover the \n * regularities.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    // As the hint said, checking the n with ranging from 7 to 10 to discover the regularities.\n    // n = 7,    3*4 = 12\n    // n = 8,  3*3*2 = 18\n    // n = 9,  3*3*3 = 27\n    // n = 10, 3*3*4 = 36\n    // n = 11, 3*3*3*2 = 54\n    //\n    // we can see we can break the number by 3 if it is greater than 4;\n    //\n    int integerBreak(int n) {\n        if ( n == 2 ) return 1;\n        if ( n == 3 ) return 2;\n        int result = 1;\n        while( n > 4 ) {\n            result *= 3;\n            n -= 3;\n        }\n        result *= n;\n        return result;\n    }\n};\n\n// DP\nclass Solution {\npublic:\n    int integerBreak(int n) {\n        vector<int> dp(n+1,1);\n        for(int i=2;i<=n;i++){\n            for(int j=1;j<=i/2;j++){\n                dp[i] = max(dp[i],max(dp[j],j)*max(dp[i-j],i-j));\n            }\n        }\n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/integerReplacement/IntegerReplacement.cpp",
    "content": "// Source : https://leetcode.com/problems/integer-replacement/\n// Author : Hao Chen\n// Date   : 2016-11-04\n\n/*************************************************************************************** \n *\n * Given a positive integer n and you can do operations as follow:\n * \n * If n is even, replace n with n/2.\n * If n is odd, you can replace n with either n + 1 or n - 1.\n * \n * What is the minimum number of replacements needed for n to become 1?\n * \n * Example 1:\n * \n * Input:\n * 8\n * \n * Output:\n * 3\n * \n * Explanation:\n * 8 -> 4 -> 2 -> 1\n * \n * Example 2:\n * \n * Input:\n * 7\n * \n * Output:\n * 4\n * \n * Explanation:\n * 7 -> 8 -> 4 -> 2 -> 1\n * or\n * 7 -> 6 -> 3 -> 2 -> 1\n ***************************************************************************************/\n\nclass Solution {\npublic:\n\n\n    int integerReplacement_recursion(int n) {\n        if ( n <= 1) return 0; // recursive exited point\n        if ( n == INT_MAX ) return 32; // special case to avoid integer overflow.\n        if ( n % 2 == 0 ) return integerReplacement(n/2) + 1;\n        return min( integerReplacement(n+1), integerReplacement(n-1) ) + 1;\n    }\n    \n    int integerReplacement_recursionWithCache(int n) {\n        static unordered_map<int, int> cache;\n        //if hitted the cache, just return the result\n        if (cache.find(n) != cache.end()) return cache[n];\n        \n        int result;\n        if ( n <= 1) return 0; // recursive exited point\n        if ( n == INT_MAX ) return 32; // special case to avoid integer overflow.\n        if ( n % 2 == 0 ) result = integerReplacement(n/2) + 1;\n        else result = min( integerReplacement(n+1), integerReplacement(n-1) ) + 1;\n        \n        //add into cache\n        cache[n] = result;\n        return result;\n    }\n    \n    int integerReplacement_simple(int n){\n        int ans = 0;\n        size_t m = n;\n        while (1 != m) {\n            if (1 == (m & 1)) {\n                if (m==3) --m; //special case\n                else m = (m&0b11^0b01) ? m + 1 : m - 1;\n            }\n            else m >>= 1;\n            ++ans;\n        }\n    return ans;\n    }\n\n    int integerReplacement(int n) {\n        return integerReplacement_recursionWithCache(n);\n        return integerReplacement_simple(n);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/integerToEnglishWords/IntegerToEnglishWords.cpp",
    "content": "// Source : https://leetcode.com/problems/integer-to-english-words/\n// Author : Hao Chen\n// Date   : 2015-10-22\n\n/*************************************************************************************** \n *\n * Convert a non-negative integer to its english words representation. Given input is \n * guaranteed to be less than 231 - 1.\n * \n * For example,\n * \n * 123 -> \"One Hundred Twenty Three\"\n * 12345 -> \"Twelve Thousand Three Hundred Forty Five\"\n * 1234567 -> \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n * \n *   Did you see a pattern in dividing the number into chunk of words? For example, 123 \n * and 123000.\n *\n *   Group the number by thousands (3 digits). You can write a helper function that \n * takes a number less than 1000 and convert just that chunk to words.\n *\n *   There are many edge cases. What are some good test cases? Does your code work with \n * input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)\n *               \n ***************************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nstatic string dict1[] ={\"Zero\",\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\",\n                 \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \n                 \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n                 \nstatic string dict2[]={\"\",\"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\nstatic string dict3[]={\"Hundred\", \"Thousand\", \"Million\", \"Billion\" };\n\n\n// This function only converts the number which less than 1000\nstring numberLess1000ToWords(int num) {\n    //char n[3] = {0, 0, 0};\n    string result;\n\n    if (num == 0) {\n        return result;\n    }else if (num < 20) {\n        return dict1[num];\n    } else if (num < 100) {\n        result = dict2[num/10];\n        if (num%10 > 0) { \n            result += \" \" + dict1[num%10];\n        }\n    }else {\n        result = dict1[num/100] + \" \" + dict3[0];\n        if ( num % 100 > 0 ) {\n            result += \" \" + numberLess1000ToWords( num % 100 );\n        }\n    }\n    return result;\n}\n\nstring numberToWords(int num) {\n    //edge case\n    if (num ==0 ) return dict1[num];\n\n    vector<string> ret;\n    for( ;num > 0; num/=1000 ) {\n        ret.push_back( numberLess1000ToWords(num % 1000) );\n    }\n\n    string result=ret[0];\n    for (int i=1; i<ret.size(); i++){\n        if (ret[i].size() > 0 ){\n            if ( result.size() > 0 ) {\n                result = ret[i] + \" \" + dict3[i] + \" \" + result; \n            } else {\n                result = ret[i] + \" \" + dict3[i]; \n            }\n        }\n\n    }\n    return result;\n}\n\n\n#define TEST(num) cout << num << \" -> \\\"\" << numberToWords(num) << \"\\\"\" << endl\nint main(int argc, char** argv) \n{\n    int num = 123;\n    if (argc >1){\n        num = atoi(argv[1]);\n    }\n    TEST(num);\n\n    TEST(0);\n    TEST(1);\n    TEST(10);\n    TEST(11);\n    TEST(18);\n    TEST(20);\n    TEST(22);\n    TEST(30);\n    TEST(99);\n    TEST(100);\n    TEST(101);\n    TEST(110);\n    TEST(120);\n    TEST(256);\n    TEST(1000);\n    TEST(1001);\n    TEST(1010);\n    TEST(1110);\n    TEST(1111);\n    TEST(10000);\n    TEST(10001);\n    TEST(100000);\n    TEST(100001);\n    TEST(1000000);\n    TEST(1000001);\n    TEST(10000000);\n    TEST(10000001);\n    TEST(100000000);\n    TEST(100000001);\n    TEST(1000000000);\n    TEST(1000000001);\n    TEST(2147483647);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/integerToRoman/integerToRoman.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/integer-to-roman/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Given an integer, convert it to a roman numeral.\n* \n* Input is guaranteed to be within the range from 1 to 3999.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <string>\n#include <iostream>\nusing namespace std;\n\n//greeding algorithm\nstring intToRoman(int num) {\n    string symbol[] =   {\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"};    \n    int value[]     =   {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1}; \n    string result;\n\n    for(int i=0; num!=0; i++){\n        while(num >= value[i]){\n            num -= value[i];\n            result+=symbol[i];\n        }\n    }\n\n    return result;\n}\n\n\nint main(int argc, char** argv)\n{\n    int num = 1234;\n    if (argc>0){\n        num = atoi(argv[1]);\n    }    \n\n    cout << num << \" : \" << intToRoman(num) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/interleavingString/interleavingString.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/interleaving-string/\n// Author : Hao Chen\n// Date   : 2014-08-27\n\n/********************************************************************************** \n* \n* Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.\n* \n* For example,\n* Given:\n* s1 = \"aabcc\",\n* s2 = \"dbbca\",\n* \n* When s3 = \"aadbbcbcac\", return true.\n* When s3 = \"aadbbbaccc\", return false.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\n/*\nConsidering:\n\n    s1 = a1, a2 ........a(i-1), ai\n    s2 = b1, b2, .......b(j-1), bj\n    s3 = c1, c3, .......c(i+j-1), c(i+j)\n\n\nDefined \n    \n    match[i][j]  means   s1[0..i] and s2[0..j] is matched S3[0..i+j]\n\n    So, if ai == c(i+j), then match[i][j] = match[i-1][j], which means\n\n        s1 = a1, a2 ........a(i-1)\n        s2 = b1, b2, .......b(j-1), bj\n        s3 = c1, c3, .......c(i+j-1)\n\n    Same, if bj = c(i+j), then match[i][j] = match[i][j-1];\n\nFormula:\n\n    Match[i][j] = \n        (s3[i+j-1] == s1[i]) && match[i-1][j] || \n        (s3[i+j-1] == s2[j]) && match[i][j-1]\n\nInitialization:\n\n    i=0 && j=0, match[0][0] = true;\n\n    i=0,   s3[j] == s2[j], match[0][j] |= match[0][j-1]\n           s3[j] != s2[j], match[0][j] = false;\n\n    j=0,   s3[i] == s1[i], match[i][0] |= match[i-1][0]\n           s3[i] != s1[i], Match[i][0] = false;\n\n*/\n\n\n\n\n//Dynamic Programming\nbool isInterleave(string s1, string s2, string s3) {\n    \n    if (s1.size() + s2.size() != s3.size()) {\n        return false;\n    }\n\n    vector< vector<int> > match(s1.size()+1, vector<int>(s2.size()+1, false) );\n\n    match[0][0] = true;\n    for(int i=1; i<=s1.size(); i++) {\n        if (s1[i-1] == s3[i-1] ) {\n            match[i][0] = true;\n        }else{\n            break;\n        }\n    }\n    for(int i=1; i<=s2.size(); i++) {\n        if (s2[i-1] == s3[i-1] ) {\n            match[0][i] = true;\n        }else{\n            break;\n        }\n    }\n\n    \n    for(int i=1; i<=s1.size(); i++) {\n        for(int j=1; j<=s2.size(); j++) {\n            if (s1[i-1] == s3[i+j-1]) {\n                match[i][j] = match[i-1][j] || match[i][j];\n            }\n            if (s2[j-1] == s3[i+j-1]) {\n                match[i][j] = match[i][j-1] || match[i][j];\n            }\n        }\n    }\n    return match[s1.size()][s2.size()];\n}\n\n//Time Limit Exceeded\nbool isInterleave_dfs(string s1, string s2, string s3) {\n    if (s1.size() + s2.size() != s3.size()) {\n        return false;\n    }\n\n    const char *p1 = s1.c_str(), *p2 = s2.c_str(), *p3 = s3.c_str();\n    for (; *p3 != '\\0'; p3++){\n        if (*p3 == *p1 && *p3!=*p2) {\n            p1++;\n        }else if ( *p3 == *p2 && *p3 != *p1) {\n            p2++;\n        }else if (*p3==*p1 && *p3 ==*p2) {\n            if (isInterleave(p1+1, p2, p3+1) == false){\n                return isInterleave(p1, p2+1, p3+1);\n            }\n            return true;\n        }else{\n            return false;\n        }\n    }\n    return ( *p1 =='\\0' && *p2 =='\\0' && *p3 =='\\0' );\n}\n\n#define TEST(s1, s2, s3) cout << s1 << \", \" << s2 << \" = \" << s3 << \" : \" << isInterleave(s1,s2,s3) << endl;\nint main(int argc, char**argv)\n{\n    string s1=  \"aabcc\", s2 = \"dbbca\";\n    TEST(s1,s2, \"aadbbcbcac\");\n    TEST(s1,s2, \"aadbbbaccc\");\n\n    s1=\"c\"; s2=\"ca\";\n    TEST(s1, s2, \"cca\");\n    TEST(s1, s2, \"cac\");\n\n    s1 = \"bbbbbabbbbabaababaaaabbababbaaabbabbaaabaaaaababbbababbbbbabbbbababbabaabababbbaabababababbbaaababaa\";\n    s2 = \"babaaaabbababbbabbbbaabaabbaabbbbaabaaabaababaaaabaaabbaaabaaaabaabaabbbbbbbbbbbabaaabbababbabbabaab\";\n    string s3 = \"babbbabbbaaabbababbbbababaabbabaabaaabbbbabbbaaabbbaaaaabbbbaabbaaabababbaaaaaabababbababaababbababbbababbbbaaaabaabbabbaaaaabbabbaaaabbbaabaaabaababaababbaaabbbbbabbbbaabbabaabbbbabaaabbababbabbabbab\";\n    TEST(s1, s2, s3);\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp",
    "content": "// Source : https://leetcode.com/problems/intersection-of-two-arrays/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2016-05-20\n\n/*************************************************************************************** \n *\n * Given two arrays, write a function to compute their intersection.\n * \n * Example:\n * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].\n * \n * Note:\n * Each element in the result must be unique.\n * The result can be in any order.\n * \n ***************************************************************************************/\nclass Solution {\npublic:\n    set <int> inter1, inter2;//we use sets so as to avoid duplicates\n    vector <int> solution;\n    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n        for(int i = 0; i < nums1.size(); i++)\n            inter1.insert(nums1[i]);//get all of the unique elements in nums1 sorted\n        for(int i = 0; i < nums2.size(); i++)\n            if(inter1.find(nums2[i]) != inter1.end())//search inter1 in O(logN)\n                inter2.insert(nums2[i]);//populate the intersection set\n        for(set<int>::iterator it = inter2.begin(); it != inter2.end(); ++it)\n            solution.push_back(*it);//copy the set into a vector\n        return solution;\n    }\n};\n\n/*\n * This Solution use one unordered_set \n */\nclass Solution2 {\npublic:\n    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n        unordered_set<int> hash_set(nums1.begin(), nums1.end());\n        vector<int> res ;\n        for (auto it& : nums2) {\n            if (hash_set.count(it)) {\n                res.push_back(it);\n                hash_set.erase(it);\n            }\n        }\n        return res;\n    }\n};\n\n/*\n * This Solution use unordered_map, insert the data into a map is more efficent than set\n */\n\nclass Solution {\npublic:\n    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n        unordered_map<int, bool> m;\n        for (auto n : nums1) {\n            m[n] = true;\n        }\n        vector<int> result;\n        for (auto n : nums2){\n            if (m.find(n) != m.end() && m[n] ){\n                result.push_back(n);\n                m[n]=false;\n            }                    \n        }\n        return result;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp",
    "content": "// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2016-05-22\n\n/*************************************************************************************** \n *\n * Given two arrays, write a function to compute their intersection.\n * \n * Example:\n * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].\n * \n * Note:\n * Each element in the result should appear as many times as it shows in both arrays.\n * The result can be in any order.\n * \n * Follow up:\n * What if the given array is already sorted? How would you optimize your algorithm?\n * What if nums1's size is small compared to num2's size? Which algorithm is better?\n * What if elements of nums2 are stored on disk, and the memory is limited such that you\n * cannot load all elements into the memory at once?\n * \n ***************************************************************************************/\n \n /* Solution\n  * --------\n  *\n  * Follow up:\n  * \n  * 1)If the given array is already sorted we can skip the sorting.\n  * \n  * 2)If nums1 is significantly smaller than nums2 we can only sort nums1 and then binary\n  * search every element of nums2 in nums1 with a total complexity of (MlogN) or if nums2\n  * is already sorted we can search every element of nums1 in nums2 in O(NlogM)\n  *\n  * 3)Just like 2), we can search for every element in nums2, thus having an online\n  * algorithm.\n  */\n  \nclass Solution { // O(NlogN + MlogM)\npublic:\n    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {\n        sort(nums1.begin(), nums1.end());//we sort both vectors in order to intersect\n        sort(nums2.begin(), nums2.end());//them later in O(N + M), where N = nums1.size()\n        vector <int> solution;                                         //M = nums2.size() \n        int index = 0;\n        bool finished = false;\n        for(int i = 0; i < nums1.size() && !finished; i++)\n        {\n            while(index < nums2.size() && nums1[i] > nums2[index])//we skip over the\n                index++;//smaller elements in nums2\n            if(index == nums2.size())//we have reached the end of nums2 so we have no more\n                finished = true;//elements to add to the intersection\n            else if(nums1[i] == nums2[index])//we found a common element\n            {\n                solution.push_back(nums1[i]);\n                index++;\n            }\n        }\n        return solution;\n    }\n};\n\n\n\n/*\n * Just simply use the map can have O(M+N) time complexity.\n *\n */\n\n\nclass Solution {\npublic:\n    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {\n        unordered_map<int, int> m;\n        for (auto n: nums1) {\n            m[n]++;\n        }\n        vector<int> result;\n        for (auto n:nums2){\n            if (m.find(n) != m.end() && m[n]>0 ){\n                result.push_back(n);\n                m[n]--;\n            }                    \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/intersectionOfTwoLinkedLists/intersectionOfTwoLinkedLists.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/intersection-of-two-linked-lists/\n// Author : Hao Chen\n// Date   : 2014-12-01\n\n/********************************************************************************** \n * \n * Write a program to find the node at which the intersection of two singly linked lists begins.\n * \n * For example, the following two linked lists: \n * \n *\n *    A:          a1 → a2\n *                       ↘\n *                         c1 → c2 → c3\n *                       ↗            \n *    B:     b1 → b2 → b3\n * \n * begin to intersect at node c1.\n * \n * Notes:\n * \n * If the two linked lists have no intersection at all, return null.\n * The linked lists must retain their original structure after the function returns. \n * You may assume there are no cycles anywhere in the entire linked structure.\n * Your code should preferably run in O(n) time and use only O(1) memory.\n *               \n **********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\n    public:\n        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {\n\n            //caculate the length of each List\n            int lenA = getListLength(headA);\n            int lenB = getListLength(headB);\n\n            if (lenA<=0 || lenB<=0 ) return NULL;\n\n            //let List A is the longest List;\n            if (lenA < lenB){\n                swap(headA, headB);\n            }\n\n            //move head of List A, make both of Lists are same length \n            for (int i=0; i<abs(lenA-lenB); i++){\n                headA = headA->next;\n            }\n\n            //synced travel both of Lists and check their nodes are same or not \n            while (headA != headB){\n                headA = headA->next;\n                headB = headB->next;\n            }\n\n            return headA;\n        }\n    private:    \n        inline int getListLength(ListNode *head){\n            int len=0;\n            while(head!=NULL){\n                head = head->next;\n                len++;\n            }\n            return len;\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/intervalListIntersectons/IntervalListIntersections.cpp",
    "content": "// Source : https://leetcode.com/problems/interval-list-intersections/\n// Author : Hao Chen\n// Date   : 2019-02-05\n\n/***************************************************************************************************** \n *\n * Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted \n * order.\n * \n * Return the intersection of these two interval lists.\n * \n * (Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= \n * b.  The intersection of two closed intervals is a set of real numbers that is either empty, or can \n * be represented as a closed interval.  For example, the intersection of [1, 3] and [2, 4] is [2, 3].)\n * \n * Example 1:\n *    \n *             0   2     5      10     13           23 24 25\n *      A     +---+     +-------+     +-------------+  +--+\n *    \n *               1      5    8     12      15        24 25  26\n *      B        +------+    +------+      +----------+  +--+\n *    \n *              1  2    5    8  10         15      23 24 25\n *    Ans        ++     +    +--+          +--------+ +  +\n *    \n * \n * Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]\n * Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\n * Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.\n * \n * Note:\n * \n * \t0 <= A.length < 1000\n * \t0 <= B.length < 1000\n * \t0 <= A[i].start, A[i].end, B[i].start, B[i].end < 109\n * \n ******************************************************************************************************/\n\n/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n    //return true if lhs starts earlier than  rhs\n    bool compareInterval(Interval& lhs, Interval& rhs) {\n        return lhs.start < rhs.start;\n    }\n    //check two interval overlapped or not\n    bool overlapped(Interval& lhs, Interval& rhs) {\n        return (compareInterval(lhs, rhs)) ?\n                             lhs.end >= rhs.start:\n                             rhs.end >= lhs.start;\n\n    }\n    //merge two interval - return the intersections of two intervals\n    Interval mergeTwoInterval(Interval& lhs, Interval& rhs) {\n        Interval result;\n        result.start = max(lhs.start, rhs.start);\n        result.end = min(lhs.end, rhs.end);\n        return result;\n    }\n\n    vector<Interval> intervalIntersection(vector<Interval>& A, vector<Interval>& B) {\n        int lenA = A.size();\n        int lenB = B.size();\n\n        vector<Interval> result;\n        if (lenA <=0 || lenB<=0) return result; //edge case\n\n        int i=0, j=0;\n        while ( i < lenA && j < lenB ) {\n            if( overlapped(A[i], B[j]) ) {\n                result.push_back(mergeTwoInterval(A[i], B[j]));\n                // if the current interval is not overlapped with next one,\n                // then we move the next interval.\n                int nexti = i;\n                if ( j==lenB-1 || !overlapped(A[i], B[j+1]) ) nexti=i+1;\n                if ( i==lenA-1 || !overlapped(A[i+1], B[j]) ) j++;\n                i = nexti;\n            }else{\n                //if not overlapped, we just move the next one\n                compareInterval(A[i], B[j]) ? i++ : j++;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/invertBinaryTree/InvertBinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/invert-binary-tree/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Invert a binary tree.\n *      4\n *    /   \\\n *   2     7\n *  / \\   / \\\n * 1   3 6   9\n * \n * to\n *      4\n *    /   \\\n *   7     2\n *  / \\   / \\\n * 9   6 3   1\n * \n * Trivia:\n * This problem was inspired by this original tweet by Max Howell:\n * (https://twitter.com/mxcl/status/608682016205344768)\n *\n *  | Google: 90% of our engineers use the software you wrote (Homebrew), \n *  | but you can’t invert a binary tree on a whiteboard so fuck off.\n *               \n **********************************************************************************/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n\n    TreeNode* invertTree_recursive(TreeNode* root) {\n        if (root==NULL) return root;\n        TreeNode* node = invertTree_recursive(root->left);\n        root->left = invertTree_recursive(root->right);\n        root->right = node;\n        return root;\n    }\n    \n    TreeNode* invertTree_non_recursive(TreeNode* root) {\n        if (root==NULL) return root;\n        vector<TreeNode*> stack;\n        stack.push_back(root);\n        while (!stack.empty()) {\n            TreeNode* node = stack.back();\n            stack.pop_back();\n            swap(node->left, node->right);\n            if (node->left) stack.push_back(node->left);\n            if (node->right) stack.push_back(node->right);\n        }\n        return root;\n    }\n    \n    TreeNode* invertTree(TreeNode* root) {\n        if (rand()%2){\n            return invertTree_non_recursive(root);\n        }\n        return invertTree_recursive(root);    \n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/isSubsequence/IsSubsequence.cpp",
    "content": "// Source : https://leetcode.com/problems/is-subsequence/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * Given a string s and a string t, check if s is subsequence of t.\n * \n * You may assume that there is only lower case English letters in both s and t. t is \n * potentially a very long (length ~= 500,000) string, and s is a short string (\n * \n * A subsequence of a string is a new string which is formed from the original string \n * by deleting some (can be none) of the characters without disturbing the relative \n * positions of the remaining characters. (ie, \"ace\" is a subsequence of \"abcde\" while \n * \"aec\" is not).\n * \n * Example 1:\n * s = \"abc\", t = \"ahbgdc\"\n * \n * Return true.\n * \n * Example 2:\n * s = \"axc\", t = \"ahbgdc\"\n * \n * Return false.\n * \n * Follow up:\n * If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to \n * check one by one to see if T has its subsequence. In this scenario, how would you \n * change your code?\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    bool isSubsequence(string s, string t) {\n        if (s.size() <= 0) return true;\n        \n        int ps=0, pt=0;\n        while (pt < t.size()) {\n            if (s[ps] == t[pt]) {\n                ps++; pt++;\n                if (ps >= s.size()) return true;\n            }else {\n                pt++;\n            }\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/islandPerimeter/IslandPerimeter.cpp",
    "content": "// Source : https://leetcode.com/problems/island-perimeter/\n// Author : Hao Chen\n// Date   : 2019-02-04\n\n/***************************************************************************************************** \n *\n * You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 \n * represents water.\n * \n * Grid cells are connected horizontally/vertically (not diagonally). The grid is completely \n * surrounded by water, and there is exactly one island (i.e., one or more connected land cells).\n * \n * The island doesn't have \"lakes\" (water inside that isn't connected to the water around the island). \n * One cell is a square with side length 1. The grid is rectangular, width and height don't exceed \n * 100. Determine the perimeter of the island.\n * \n * Example:\n * \n * Input:\n * [[0,1,0,0],\n *  [1,1,1,0],\n *  [0,1,0,0],\n *  [1,1,0,0]]\n * \n * Output: 16\n * \n * Explanation: The perimeter is the 16 yellow stripes in the image below:\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    int edge(vector<vector<int>> &grid, int x, int y) {\n        int edge = 0;\n        \n        if (x==0 || (x>0 && grid[x-1][y] == 0 ) ) edge++; //up\n        if (y==0 || (y>0 && grid[x][y-1] == 0 ) ) edge++; //left\n        if (x == grid.size() - 1 || \n            (x < grid.size() - 1 && grid[x+1][y] == 0)) edge++; //down\n        if (y == grid[0].size() - 1 || \n            (y < grid[0].size() - 1 && grid[x][y+1] == 0)) edge++; //right\n        \n        return edge;\n    }\n            \n    int islandPerimeter(vector<vector<int>>& grid) {\n        int perimeter = 0;\n        for(int i=0; i<grid.size(); i++) {\n            for(int j=0; j<grid[0].size(); j++) {\n                if (grid[i][j] == 1) {\n                    perimeter += edge (grid, i, j);\n                }\n            }\n        }\n        return perimeter;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/isomorphicStrings/IsomorphicStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/isomorphic-strings/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Given two strings s and t, determine if they are isomorphic.\n * \n * Two strings are isomorphic if the characters in s can be replaced to get t.\n * \n * All occurrences of a character must be replaced with another character while preserving \n * the order of characters. No two characters may map to the same character but a character\n *  may map to itself.\n * \n * For example,\n *\n *     Given \"egg\", \"add\", return true.\n *     \n *     Given \"foo\", \"bar\", return false.\n *     \n *     Given \"paper\", \"title\", return true.\n * \n * Note:\n * You may assume both s and t have the same length.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    bool isIsomorphic(string s, string t) {\n        if (s.size()!=t.size()) return false;\n        \n        const int MAXCHAR = 256;\n        char maps[MAXCHAR]={0}, mapt[MAXCHAR]={0};\n        //memset(maps, 0, sizeof(maps));\n        //memset(mapt, 0, sizeof(mapt));\n        \n        for(int i=0; i<s.size(); i++){\n            if(maps[s[i]] == 0 && mapt[t[i]] == 0){\n                maps[s[i]] = t[i];\n                mapt[t[i]] = s[i];\n                continue;\n            }\n            if(maps[s[i]] == t[i] && mapt[t[i]] == s[i]) {\n                continue;\n            }\n            return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp",
    "content": "// Source : https://leetcode.com/problems/jewels-and-stones/description\n// Author : Hao Chen\n// Date   : 2018-06-23\n\n/*************************************************************************************** \n *\n * You're given strings J representing the types of stones that are jewels, and S \n * representing the stones you have.  Each character in S is a type of stone you have.  \n * You want to know how many of the stones you have are also jewels.\n * \n * The letters in J are guaranteed distinct, and all characters in J and S are letters. \n * Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\".\n * \n * Example 1:\n * \n * \n * Input: J = \"aA\", S = \"aAAbbbb\"\n * Output: 3\n * \n * \n * Example 2:\n * \n * \n * Input: J = \"z\", S = \"ZZ\"\n * Output: 0\n * \n * \n * Note:\n * \n * \n * \tS and J will consist of letters and have length at most 50.\n * \tThe characters in J are distinct.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    int numJewelsInStones(string J, string S) {\n        bool map[256] = {false};\n        for (auto c : J) {\n            map[c]=true;\n        }\n        int cnt=0;\n        for (auto c : S) {\n            if (map[c])  cnt++;\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/jumpGame/jumpGame.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/jump-game-ii/\n// Author : Hao Chen\n// Date   : 2014-07-18\n\n/********************************************************************************** \n* \n* Given an array of non-negative integers, you are initially positioned at the first index of the array.\n* \n* Each element in the array represents your maximum jump length at that position. \n* \n* Your goal is to reach the last index in the minimum number of jumps.\n* \n* For example:\n* Given array A = [2,3,1,1,4]\n* \n* The minimum number of jumps to reach the last index is 2. \n* (Jump 1 step from index 0 to 1, then 3 steps to the last index.)\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\nusing namespace std;\n\n//Acutally, using the Greedy algorithm can have the answer\nint jump(int A[], int n) {\n    if (n<=1) return 0;\n    \n    int steps = 0;\n    int coverPos = 0;\n    for (int i=0; i<=coverPos&& i<n; ){\n        if (A[i]==0) return -1; \n        if(coverPos < A[i]+i){\n            coverPos = A[i]+i;\n            steps++;\n        }\n        if (coverPos >= n-1){\n            return steps;\n        }\n        //Greedy: find the next place which can have biggest distance\n        int nextPos=0;\n        int maxDistance=0;\n        for(int j=i+1; j<=coverPos; j++){\n            if ( A[j]+j > maxDistance ) {\n                maxDistance = A[j]+j;\n                nextPos = j;\n            }\n        }\n        i = nextPos;\n    }\n    return steps;\n}\n\nvoid printArray(int a[], int n){\n    cout << \"{ \";\n    for(int i=0; i<n; i++){\n        if(i) cout << \", \";\n        cout << a[i];\n    }\n    cout << \" } \";\n}\nint main()\n{\n    #define TEST(a) printArray(a, sizeof(a)/sizeof(a[0])); cout<<jump(a, sizeof(a)/sizeof(a[0]))<<endl;\n\n    int a1[]={0};\n    TEST(a1);\n\n    int a2[]={1};\n    TEST(a2);\n\n    int a3[]={3,2,1,0,4};\n    TEST(a3);\n\n    int a4[]={2,3,1,1,4};\n    TEST(a4);\n\n    int a5[]={1,2,3};\n    TEST(a5);\n\n    // 0 -> 1 -> 4 -> end\n    int a6[]={2,3,1,1,4,0,1};\n    TEST(a6);\n\n    // 0 -> 1 -> 3 -> end\n    int a7[]={2,3,1,2,0,1};\n    TEST(a7);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/jumpGame/jumpGame.VII.cpp",
    "content": "// Source : https://leetcode.com/problems/jump-game-vii/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, \n * you are standing at index 0, which is equal to '0'. You can move from index i to index j if the \n * following conditions are fulfilled:\n * \n * \ti + minJump <= j <= min(i + maxJump, s.length - 1), and\n * \ts[j] == '0'.\n * \n * Return true if you can reach index s.length - 1 in s, or false otherwise.\n * \n * Example 1:\n * \n * Input: s = \"011010\", minJump = 2, maxJump = 3\n * Output: true\n * Explanation:\n * In the first step, move from index 0 to index 3. \n * In the second step, move from index 3 to index 5.\n * \n * Example 2:\n * \n * Input: s = \"01101110\", minJump = 2, maxJump = 3\n * Output: false\n * \n * Constraints:\n * \n * \t2 <= s.length <= 10^5\n * \ts[i] is either '0' or '1'.\n * \ts[0] == '0'\n * \t1 <= minJump <= maxJump < s.length\n ******************************************************************************************************/\n\n\n"
  },
  {
    "path": "algorithms/cpp/jumpGame/jumpGame.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/jump-game/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* Given an array of non-negative integers, you are initially positioned at the first index of the array.\n* \n* Each element in the array represents your maximum jump length at that position. \n* \n* Determine if you are able to reach the last index.\n* \n* For example:\n* A = [2,3,1,1,4], return true.\n* \n* A = [3,2,1,0,4], return false.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    bool canJump(int A[], int n) {\n        if (n<=0) return false;\n        \n        // the basic idea is traverse array, maintain the most far can go\n        int coverPos=0;\n        // the condition i<=coverPos means traverse all of covered position \n        for(int i=0; i<=coverPos && i<n; i++){\n            \n            if (coverPos < A[i] + i){\n                coverPos = A[i] + i;\n            }\n            \n            if (coverPos>=n-1){\n                return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/kthLargestElementInAnArray/KthLargestElementInAnArray.cpp",
    "content": "// Source : https://leetcode.com/problems/kth-largest-element-in-an-array/\n// Author : Hao Chen\n// Date   : 2015-06-11\n\n/********************************************************************************** \n * \n * Find the kth largest element in an unsorted array. \n * Note that it is the kth largest element in the sorted order, not the kth distinct element.\n * \n * For example,\n * Given [3,2,1,5,6,4] and k = 2, return 5.\n * \n * Note: \n * You may assume k is always valid, 1 ≤ k ≤ array's length.\n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\n\n\nclass Solution {\npublic:\n    //STL using qsort to solve this problem\n    int findKthLargest_buildin(vector<int>& nums, int k) {\n        int n=nums.size();\n        std::nth_element(nums.begin(),nums.end()-k,nums.end());\n        return nums[n-k];\n    }\n    \n    //qsort partition\n    int partition(vector<int>& nums, int left, int right) {\n        int pivot = nums[left];\n        int l = left + 1, r = right;\n        while (l <= r) {\n            if (nums[l] < pivot && nums[r] > pivot){\n                swap(nums[l++], nums[r--]);\n            }\n            if (nums[l] >= pivot) l++;\n            if (nums[r] <= pivot) r--;\n        }\n        swap(nums[left], nums[r]);\n        return r;\n    }\n    \n    int findKthLargest_qsort(vector<int>& nums, int k) {\n        int left = 0, right = nums.size() - 1;\n        while (true) {\n            int pos = partition(nums, left, right);\n            if (pos == k - 1){ \n                return nums[pos];\n            }\n            if (pos > k - 1) {\n                right = pos - 1;\n            }else{\n                left = pos + 1;  \n            }  \n        }\n    }\n    \n    \n    int findKthLargest(vector<int>& nums, int k) {\n        return findKthLargest_qsort(nums, k);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp",
    "content": "// Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/\n// Author : Hao Chen\n// Date   : 2015-07-03\n\n/********************************************************************************** \n * \n * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.\n * \n * Note: \n * You may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n * \n * Follow up:\n * What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? \n * How would you optimize the kthSmallest routine?\n * \n *   Try to utilize the property of a BST.\n *   What if you could modify the BST node's structure?\n *   The optimal runtime complexity is O(height of BST).\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n **********************************************************************************/\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    // in-order travel - recursive way\n    int kthSmallestHelper_recursive(TreeNode* root, int& k) {\n        if (root==NULL) return 0; //this behavior is undefined!\n        \n        //in-order travel\n        int result = kthSmallestHelper_recursive(root->left, k);\n        if (k==0) return result;\n        \n        k--;\n        if (k==0) return root->val;\n        \n        \n        return kthSmallestHelper_recursive(root->right, k);\n    }\n    // in-order travel - non-recursive way\n    int kthSmallestHelper_nonRecursive(TreeNode* root, int k){\n        stack<TreeNode*> s;\n        \n        while(!s.empty() || root){\n            \n            while (root) { \n                s.push(root);\n                root = root->left;\n            }\n            \n            k--;\n            root = s.top()->right;\n\n            if (k==0) return s.top()->val;\n            \n            s.pop();\n        }\n        return -1;\n    }\n    \n    int kthSmallest(TreeNode* root, int k) {\n        //return kthSmallestHelper_nonRecursive(root, k);\n        return kthSmallestHelper_recursive(root, k);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestColorValueInADirectedGraph/LargestColorValueInADirectedGraph.cpp",
    "content": "// Source : https://leetcode.com/problems/largest-color-value-in-a-directed-graph/\n// Author : Hao Chen\n// Date   : 2021-05-10\n\n/***************************************************************************************************** \n *\n * There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.\n * \n * You are given a string colors where colors[i] is a lowercase English letter representing the color \n * of the i^th node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = \n * [aj, bj] indicates that there is a directed edge from node aj to node bj.\n * \n * A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a \n * directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of \n * nodes that are colored the most frequently occurring color along that path.\n * \n * Return the largest color value of any valid path in the given graph, or -1 if the graph contains a \n * cycle.\n * \n * Example 1:\n * \n * Input: colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\n * Output: 3\n * Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored \"a\" (red in the above \n * image).\n * \n * Example 2:\n * \n * Input: colors = \"a\", edges = [[0,0]]\n * Output: -1\n * Explanation: There is a cycle from 0 to 0.\n * \n * Constraints:\n * \n * \tn == colors.length\n * \tm == edges.length\n * \t1 <= n <= 10^5\n * \t0 <= m <= 10^5\n * \tcolors consists of lowercase English letters.\n * \t0 <= aj, bj < n\n ******************************************************************************************************/\n\n\nconst int COLOR_CNT = 26;\n\nclass Node {\npublic:\n    Node(char c) {\n        incomming = 0;\n        color = c;\n        processed = false;\n        memset(colors, 0, sizeof(colors));\n    }\n    void AddMyColor() { colors[color]++; }\n    void Processed() { processed = true; }\n    bool isProcessed() { return processed; }\n    void AddIncomming(int n=1) { incomming += n;}\n    int Incomming() {return incomming;}\n    void AddChildNode(int n) { children.push_back(n); }\n    vector<int>& Children() { return children; }\n    int ChildrenCount() { return children.size(); }\n    int* Colors() {return colors;}\n    int MaxColorValue() {\n        int m = -1;\n        for(auto c: colors) {\n            m = max(m, c);\n        }\n        return m;\n    }\n    void MergeChildColors(Node& child){\n        int* c = child.Colors();\n        for(int i=0; i<COLOR_CNT; i++) {\n            colors[i] = max(colors[i], c[i]);\n        }\n    }\n\nprivate:\n    int incomming;          // incomming connection\n    char color;             // node's color\n    bool processed;         // if the node has been processed\n    int colors[COLOR_CNT];  // the colors count stastices \n    vector<int> children;   // children nodes\n};\n\n\nclass Solution {\nprivate:\n    void print(vector<int>& v) {\n        cout << \"[\";\n        int i = 0;\n        for(; i<v.size()-1; i++) {\n            cout << v[i] << \",\";\n        }\n        cout << v[i] << \"]\" << endl;\n    }\nprivate:\n    int nodes_cnt;\n    vector<Node> nodes;\npublic:\n    int largestPathValue(string colors, vector<vector<int>>& edges) {\n        \n        nodes_cnt = colors.size() ;\n        for(int i=0; i<nodes_cnt; i++) {\n            Node n( colors[i]-'a');\n            nodes.push_back(n);\n        }\n        for(auto& e : edges) {\n            nodes[e[0]].AddChildNode(e[1]);\n            nodes[e[1]].AddIncomming();\n        }\n        \n         vector<bool> visited(nodes_cnt, false);\n        \n        // We can do toplogical sort\n        // \n        //vector<int> topSort;\n        //for(int id=0; id <nodes_cnt; id++){\n        //    auto& n = nodes[id];\n        //    topologicalSort(id, topSort, visited);\n        //}\n        //print(topSort);\n        \n        int m = -1;\n        for (int i=0; i<nodes_cnt; i++) {\n            //int id = topSort[i];\n            int id = i;\n            auto& n = nodes[id];\n            \n            //using to check cycle.\n            std::fill(visited.begin(), visited.end(), false);\n            \n            bool succ = travel(id, visited);\n            if (!succ) return -1;\n           \n            m = max(m, nodes[id].MaxColorValue());\n        }\n        return m;\n    }\n    \n    void topologicalSort(int i, vector<int>& topSort, vector<bool>& visited) {\n        if (visited[i]) return;\n        visited[i] = true;\n        for(auto& id : nodes[i].Children()) {\n            if (!visited[id]) {\n                topologicalSort(id, topSort, visited);\n            }\n        }\n        topSort.push_back(i);\n    }\n    \n    //return true if it is successful\n    //return false if there is an error  - has cycle\n    bool travel(int i, vector<bool>& visited ) {\n        //this node has been processed already\n        if (nodes[i].isProcessed()) return true;\n        \n        //cycled \n        if (visited[i]) return false;\n        visited[i] = true;\n        \n        // leaf node\n        if (nodes[i].ChildrenCount() <= 0 ) {\n            nodes[i].AddMyColor();\n            nodes[i].Processed();\n            return true;\n        }\n      \n        for(auto& n : nodes[i].Children() ) {\n            bool succ = travel(n, visited);\n            if (!succ) return false;\n            nodes[i].MergeChildColors( nodes[n] );\n        }\n        \n        nodes[i].AddMyColor();\n        nodes[i].Processed();\n\n        //cout << \"[\"<< i << \"]: \" ;\n        //for(int k=0; k<26; k++) {\n        //    cout << nodes[i].colors[k] << \" \";\n        //}\n        //cout << endl;\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestMergeOfTwoStrings/LargestMergeOfTwoStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/largest-merge-of-two-strings/\n// Author : Hao Chen\n// Date   : 2021-02-11\n\n/***************************************************************************************************** \n *\n * You are given two strings word1 and word2. You want to construct a string merge in the following \n * way: while either word1 or word2 are non-empty, choose one of the following options:\n * \n * \tIf word1 is non-empty, append the first character in word1 to merge and delete it from \n * word1.\n * \n * \t\tFor example, if word1 = \"abc\" and merge = \"dv\", then after choosing this operation, \n * word1 = \"bc\" and merge = \"dva\".\n * \n * \tIf word2 is non-empty, append the first character in word2 to merge and delete it from \n * word2.\n * \n * \t\tFor example, if word2 = \"abc\" and merge = \"\", then after choosing this operation, \n * word2 = \"bc\" and merge = \"a\".\n * \n * Return the lexicographically largest merge you can construct.\n * \n * A string a is lexicographically larger than a string b (of the same length) if in the first \n * position where a and b differ, a has a character strictly larger than the corresponding character \n * in b. For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they \n * differ is at the fourth character, and d is greater than c.\n * \n * Example 1:\n * \n * Input: word1 = \"cabaa\", word2 = \"bcaaa\"\n * Output: \"cbcabaaaaa\"\n * Explanation: One way to get the lexicographically largest merge is:\n * - Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n * - Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n * - Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n * - Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n * - Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n * - Append the remaining 5 a's from word1 and word2 at the end of merge.\n * \n * Example 2:\n * \n * Input: word1 = \"abcabc\", word2 = \"abdcaba\"\n * Output: \"abdcabcabcaba\"\n * \n * Constraints:\n * \n * \t1 <= word1.length, word2.length <= 3000\n * \tword1 and word2 consist only of lowercase English letters.\n ******************************************************************************************************/\n\n\nclass Solution {\nprivate:\n    bool string_cmp(string& s1, int p1, string& s2, int p2) {\n        for (; p1 < s1.size() && p2 < s2.size() ; p1++, p2++) {\n            if (s1[p1] == s2[p2]) continue;\n            return s1[p1] > s2[p2];\n        }\n        return (s1.size() - p1 >  s2.size() - p2);\n    }\npublic:\n    string largestMerge(string word1, string word2) {\n        int p1 = 0, p2 = 0;\n        int len1 = word1.size(), len2 = word2.size();\n        string merge(len1+len2, '\\0');\n        int p = 0;\n\n        while (p1 < len1 && p2 < len2) {\n            if ( string_cmp(word1, p1, word2, p2) ){ // take char from `word1`\n                merge[p++] = word1[p1++];\n            }else{ //take char from `word2`\n                merge[p++] = word2[p2++];\n            }\n        }\n\n        while (p1 < len1) merge[p++] = word1[p1++];\n        while (p2 < len2) merge[p++] = word2[p2++];\n\n        return merge;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestNumber/largestNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/largest-number/\n// Author : Hao Chen\n// Date   : 2015-01-16\n\n/********************************************************************************** \n * \n * Given a list of non negative integers, arrange them such that they form the largest number.\n * \n * For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.\n * \n * Note: The result may be very large, so you need to return a string instead of an integer.\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\nclass Solution {\n    public:\n\n        //compare function\n        static bool comp (string& s1, string& s2) { return s1+s2 > s2+s1; }\n\n        string largestNumber(vector<int> &num) {\n\n            //convert int to string\n            vector<string> v;\n            for (int i=0; i<num.size(); i++) {\n                v.push_back(to_string(num[i]));\n            }\n\n            //sort the string\n            sort(v.begin(), v.end(), comp);\n\n            //generate the result\n            string result;\n            for(int i=0; i<v.size(); i++ ){\n                result+=v[i];\n            }\n\n            //special case: start with zero (e.g. [0, 0])\n            if (result[0]=='0') return \"0\";\n\n            return result;\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestNumberAfterMutatingSubstring/LargestNumberAfterMutatingSubstring.cpp",
    "content": "// Source : https://leetcode.com/problems/largest-number-after-mutating-substring/\n// Author : Hao Chen\n// Date   : 2021-11-12\n\n/***************************************************************************************************** \n *\n * You are given a string num, which represents a large integer. You are also given a 0-indexed \n * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d \n * maps to digit change[d].\n * \n * You may choose to mutate a single substring of num. To mutate a substring, replace each digit \n * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\n * \n * Return a string representing the largest possible integer after mutating (or choosing not to) a \n * single substring of num.\n * \n * A substring is a contiguous sequence of characters within the string.\n * \n * Example 1:\n * \n * Input: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\n * Output: \"832\"\n * Explanation: Replace the substring \"1\":\n * - 1 maps to change[1] = 8.\n * Thus, \"132\" becomes \"832\".\n * \"832\" is the largest number that can be created, so return it.\n * \n * Example 2:\n * \n * Input: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\n * Output: \"934\"\n * Explanation: Replace the substring \"021\":\n * - 0 maps to change[0] = 9.\n * - 2 maps to change[2] = 3.\n * - 1 maps to change[1] = 4.\n * Thus, \"021\" becomes \"934\".\n * \"934\" is the largest number that can be created, so return it.\n * \n * Example 3:\n * \n * Input: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\n * Output: \"5\"\n * Explanation: \"5\" is already the largest number that can be created, so return it.\n * \n * Constraints:\n * \n * \t1 <= num.length <= 10^5\n * \tnum consists of only digits 0-9.\n * \tchange.length == 10\n * \t0 <= change[d] <= 9\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string maximumNumber(string num, vector<int>& change) {\n        bool replace = false;\n        for(int i=0; i<num.size(); i++) {\n            char n = num[i] - '0';\n            if (n < change[n] ) {\n                num[i] = change[n] + '0';\n                replace = true;\n            }else if (n > change[n] && replace ) {\n                break;\n            }\n        }\n        return num;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestPerimeterTriangle/largestPerimeterTriangle.cpp",
    "content": "class Solution {\npublic:\n    int largestPerimeter(vector<int>& A) {\n        if (A.size() < 3) return 0;\n        sort(A.begin(), A.end(), greater<int>());\n        for (auto it = A.begin(); it != A.end() - 2; ++it) {\n            if (*it < *(it + 1) + *(it + 2))\n                return *it + *(it + 1) + *(it + 2);            \n        }\n        return 0;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/largestRectangleInHistogram/largestRectangleInHistogram.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/largest-rectangle-in-histogram/\n// Author : Hao Chen\n// Date   : 2014-07-20\n\n/********************************************************************************** \n * \n * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, \n * find the area of largest rectangle in the histogram.\n * \n *                    6          \n *                  +---+        \n *               5  |   |        \n *              +---+   |        \n *              |   |   |        \n *              |   |   |        \n *              |   |   |     3  \n *              |   |   |   +---+\n *        2     |   |   | 2 |   |\n *      +---+   |   |   +---+   |\n *      |   | 1 |   |   |   |   |\n *      |   +---+   |   |   |   |\n *      |   |   |   |   |   |   |\n *      +---+---+---+---+---+---+\n *      \n * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].\n *      \n *      \n *                    6          \n *                  +---+        \n *               5  |   |        \n *              +-------|        \n *              |-------|        \n *              |-------|        \n *              |-------|     3  \n *              |-------|   +---+\n *        2     |-------| 2 |   |\n *      +---+   |-------|---+   |\n *      |   | 1 |-------|   |   |\n *      |   +---|-------|   |   |\n *      |   |   |-------|   |   |\n *      +---+---+---+---+---+---+\n *      \n * \n * The largest rectangle is shown in the shaded area, which has area = 10 unit.\n * \n * For example,\n * Given height = [2,1,5,6,2,3],\n * return 10.\n * \n *               \n **********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n//Time Limit Exceeded\nint largestRectangleArea_01(vector<int>& heights) {\n    if (heights.size() == 0) return 0;\n\n    // idx of the first bar in the left or right that is lower than current bar\n    vector<int> left(heights.size()); \n    vector<int> right(heights.size());\n\n    right[heights.size() - 1] = heights.size();\n    left[0] = -1;\n\n    for (int i = 1; i < heights.size(); i++) {\n        int l = i - 1;\n        while (l >= 0 && heights[l] >= heights[i]) {\n            l--;\n        }\n        left[i] = l;\n    }\n\n    for (int i = heights.size() - 2; i >= 0; i--) {\n        int r = i + 1;\n        while (r < heights.size() && heights[r] >= heights[i]) {\n            r++;\n        }\n        right[i] = r;\n    }\n\n    int maxArea = 0;\n    for (int i = 0; i < heights.size(); i++) {\n        maxArea = max(maxArea, heights[i] * (right[i] - left[i] - 1));\n    }\n\n    return maxArea;        \n\n}\n\n\n// As we know, the area = width * height\n// For every bar, the 'height' is determined by the loweset bar.\n//\n// 1) We traverse all bars from left to right, maintain a stack of bars. Every bar is pushed to stack once. \n// 2) A bar is popped from stack when a bar of smaller height is seen. \n// 3) When a bar is popped, we calculate the area with the popped bar as smallest bar. \n// 4) How do we get left and right indexes of the popped bar – \n//    the current index tells us the ‘right index’ and index of previous item in stack is the ‘left index’. \n//\n//\n// In other word, the stack only stores the incresing bars, let's see some example  \n//\n// Example 1\n// ---------\n// height = [1,2,3,4]\n//\n//    stack[] = [ 0, 1, 2, 3 ], i=4\n//\n//    1) pop 3,  area = height[3] * 1 = 4\n//    2) pop 2,  area = height[2] * 2 = 4\n//    3) pop 1,  area = height[1] * 3 = 6\n//    4) pop 0,  area = height[0] * 4 = 4\n//\n//\n// Example 2\n// ---------\n// height = [2,1,2]\n//\n//    stack[] = [ 0 ], i=1\n//    1) pop 0,  area = height[0] * 1 = 2\n//\n//    stack[] = [ 1,2 ], i=3, meet the end\n//    1) pop 2,  area = height[2] * 1 = 2\n//    2) pop 1,  area = height[1] * 3 = 3\n//\n//\n// Example 3\n// ---------\n// height =  [4,2,0,3,2,5]  \n//\n//    stack[] = [ 0 ], i=1, height[1] goes down\n//    1) pop 0,  area = height[0] * 1 = 4\n//\n//    stack[] = [ 1 ], i=2, height[2] goes down\n//    1) pop 1,  area = height[1] * 2 = 4 // <- how do we know the left?\n//                                              start from the 0 ?? \n//\n//    stack[] = [ 2, 3 ], i=4, height[4] goes down\n//    1) pop 3,  area = height[3] * 1 = 3\n//    2) pop 2,  area = height[2] * ? = 0 // <- how do we know the left? \n//                                              start from the 0 ??\n//\n//    stack[] = [ 2,4,5 ], i=6,  meet the end\n//    1) pop 5,  area = height[5] * 1 = 5\n//    2) pop 4,  area = height[4] * 3 = 6 // <- how do we know the left?\n//                                              need check the previous item.\n//    3) pop 2,  area = height[2] * ? = 4 // <- how do we know the left?\n//                                              start from the 0 ??\n//\n//    so, we can see, when the stack pop the top, the area formular is \n//\n//          height[stack_pop] *  i - stack[current_top] - 1,   if stack is not empty\n//          height[stack_pop] *  i,                            if stack is empty\n//\nint largestRectangleArea(vector<int> &height) {\n    if (height.size()<=0) return 0;\n    //Create an empty stack.\n    vector<int> stack;\n    //add a flag as a trigger if the end bar is met, and need to check the stack is empty of not .\n    height.push_back(0);\n    int maxArea = 0;\n    for(int i=0; i<height.size(); i++){\n        //If stack is empty or height[i] is higher than the bar at top of stack, then push ‘i’ to stack.\n        if ( stack.size()<=0 || height[i] >= height[stack.back()] ) {\n            stack.push_back(i);\n            continue;\n        }\n        //If this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. \n        //Let the removed bar be height[top]. Calculate area of rectangle with height[top] as smallest bar. \n        //For height[top], the ‘left index’ is previous (previous to top) item in stack and ‘right index’ is ‘i’ (current index).\n        int topIdx = stack.back();\n        stack.pop_back();\n        int area = height[topIdx] * (stack.size()==0 ? i : i - stack.back() - 1 );\n        if ( area > maxArea ) {\n            maxArea = area;\n        }\n        //one more time. Because the stack might still have item.\n        i--;\n    }\n\n    return maxArea;\n}\n\nvoid printArray(vector<int> &v)\n{\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \"}\" << endl;\n}\nvoid test(int a[], int n)\n{\n    vector<int> v(a, a + n);\n    printArray(v);\n    cout << largestRectangleArea(v) << endl;\n}\n\nint main()\n{\n#define TEST(a) test(a, sizeof(a)/sizeof(int))\n\n    int a0[] = {2,1,3,1};\n    TEST(a0);\n    int a1[] = {2,1,5,6,2,3};\n    TEST(a1);\n\n    return 0;\n}\n\n/*int main()\n  {\n  int a[] = {2,1,5,6,2,3};\n  vector<int> v(a, a + sizeof(a)/sizeof(int));\n  printArray(v);\n  cout << largestRectangleArea(v) << endl;\n  return 0;\n  }*/\n"
  },
  {
    "path": "algorithms/cpp/largestSubmatrixWithRearrangements/LargestSubmatrixWithRearrangements.cpp",
    "content": "// Source : https://leetcode.com/problems/largest-submatrix-with-rearrangements/\n// Author : Hao Chen\n// Date   : 2021-05-06\n\n/***************************************************************************************************** \n *\n * You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of \n * the matrix in any order.\n * \n * Return the area of the largest submatrix within matrix where every element of the submatrix is 1 \n * after reordering the columns optimally.\n * \n * Example 1:\n * \n * Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]\n * Output: 4\n * Explanation: You can rearrange the columns as shown above.\n * The largest submatrix of 1s, in bold, has an area of 4.\n * \n * Example 2:\n * \n * Input: matrix = [[1,0,1,0,1]]\n * Output: 3\n * Explanation: You can rearrange the columns as shown above.\n * The largest submatrix of 1s, in bold, has an area of 3.\n * \n * Example 3:\n * \n * Input: matrix = [[1,1,0],[1,0,1]]\n * Output: 2\n * Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix \n * of 1s larger than an area of 2.\n * \n * Example 4:\n * \n * Input: matrix = [[0,0],[0,0]]\n * Output: 0\n * Explanation: As there are no 1s, no submatrix of 1s can be formed and the area is 0.\n * \n * Constraints:\n * \n * \tm == matrix.length\n * \tn == matrix[i].length\n * \t1 <= m * n <= 10^5\n * \tmatrix[i][j] is 0 or 1.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int largestSubmatrix(vector<vector<int>>& matrix) {\n        int rows = matrix.size();\n        int cols = matrix[0].size();\n        vector<int> height (cols, 0);\n        \n        int result = 0;\n        for(int r = 0; r < rows; r++) {\n            for(int c = 0; c < cols; c++) {\n                if (matrix[r][c] == 1) height[c]++;\n                else height[c] = 0;\n            }\n            \n            vector<int> h = height;\n            sort(h.begin(), h.end());\n            for(int i = 0; i < cols; i++) {\n                result = max(result, h[i] * ( cols - i)); \n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/largestSubstringBetweenTwoEqualCharacters/LargestSubstringBetweenTwoEqualCharacters.cpp",
    "content": "// Source : https://leetcode.com/problems/largest-substring-between-two-equal-characters/\n// Author : Hao Chen\n// Date   : 2021-03-24\n\n/***************************************************************************************************** \n *\n * Given a string s, return the length of the longest substring between two equal characters, \n * excluding the two characters. If there is no such substring return -1.\n * \n * A substring is a contiguous sequence of characters within a string.\n * \n * Example 1:\n * \n * Input: s = \"aa\"\n * Output: 0\n * Explanation: The optimal substring here is an empty substring between the two 'a's.\n * \n * Example 2:\n * \n * Input: s = \"abca\"\n * Output: 2\n * Explanation: The optimal substring here is \"bc\".\n * \n * Example 3:\n * \n * Input: s = \"cbzxy\"\n * Output: -1\n * Explanation: There are no characters that appear twice in s.\n * \n * Example 4:\n * \n * Input: s = \"cabbac\"\n * Output: 4\n * Explanation: The optimal substring here is \"abba\". Other non-optimal substrings include \"bb\" and \"\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 300\n * \ts contains only lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxLengthBetweenEqualCharacters(string s) {\n        int pos[26]={0};\n        \n        int longest = -1 ;\n        for (int i=0; i<s.size(); i++){\n            int idx = s[i] -'a';\n            if (pos[idx] == 0)  pos[idx] = i + 1; \n            else longest = max(longest, i - pos[idx]);\n        }\n        \n        return longest;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/latestTimeByReplacingHiddenDigits/LatestTimeByReplacingHiddenDigits.cpp",
    "content": "// Source : https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * You are given a string time in the form of  hh:mm, where some of the digits in the string are \n * hidden (represented by ?).\n * \n * The valid times are those inclusively between 00:00 and 23:59.\n * \n * Return the latest valid time you can get from time by replacing the hidden digits.\n * \n * Example 1:\n * \n * Input: time = \"2?:?0\"\n * Output: \"23:50\"\n * Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with \n * the digit '0' is 50.\n * \n * Example 2:\n * \n * Input: time = \"0?:3?\"\n * Output: \"09:39\"\n * \n * Example 3:\n * \n * Input: time = \"1?:22\"\n * Output: \"19:22\"\n * \n * Constraints:\n * \n * \ttime is in the format hh:mm.\n * \tIt is guaranteed that you can produce a valid time from the given string.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string maximumTime(string time) {\n        \n        if (time[0] == '?' ) {\n            time[0] = (time[1] == '?' || time[1] < '4') ?  '2' : '1';\n        }\n        if (time[1] == '?' ) {\n            time[1] = ( time[0] == '2' ) ? '3' : '9';\n        }\n        if (time[3] == '?') time[3] = '5';\n        if (time[4] == '?') time[4] = '9'; \n        return time;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/lengthOfLastWord/lengthOfLastWord.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/length-of-last-word/\n// Author : Hao Chen\n// Date   : 2014-07-01\n\n/********************************************************************************** \n* \n* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', \n* return the length of last word in the string.\n* \n* If the last word does not exist, return 0.\n* \n* Note: A word is defined as a character sequence consists of non-space characters only.\n* \n* For example, \n* Given s = \"Hello World\",\n* return 5.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <ctype.h>\n\nint lengthOfLastWord(const char *s) {\n\n    if ( !s ||!*s ) return 0;\n\n    int wordLen=0;\n    int cnt=0;\n\n    for (;*s!='\\0';s++) {\n        if (isalpha(*s)){\n            cnt++;\n        }\n        if (!isalpha(*s)){\n            if (cnt>0){\n                wordLen = cnt;\n            }\n            cnt=0;\n        }\n    }\n\n    return cnt>0 ? cnt : wordLen;\n}\n\n\nint main(int argc, char** argv)\n{\n    const char* p;\n    p = \"hello world\";\n    printf(\"%s, %d\\n\", p, lengthOfLastWord(p)); \n    p = \"a\";\n    printf(\"%s, %d\\n\", p, lengthOfLastWord(p)); \n    \n    if(argc>1){\n        p = argv[1];\n        printf(\"%s, %d\\n\", p, lengthOfLastWord(p)); \n    }\n}\n"
  },
  {
    "path": "algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Given a digit string, return all possible letter combinations that the number could represent.\n* \n* A mapping of digit to letters (just like on the telephone buttons) is given below.\n* \n* Input:Digit string \"23\"\n* Output: [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n* \n* Note:\n* Although the above answer is in lexicographical order, your answer could be in any order you want.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\nvector<string> letterCombinations(string digits) {\n    char  phone[10][4]={ {' ',  '\\0', '\\0', '\\0' }, //0\n                         {'\\0', '\\0', '\\0', '\\0' }, //1\n                         {'a',  'b',  'c',  '\\0' }, //2\n                         {'d',  'e',  'f',  '\\0' }, //3\n                         {'g',  'h',  'i',  '\\0' }, //4\n                         {'j',  'k',  'l',  '\\0' }, //5\n                         {'m',  'n',  'o',  '\\0' }, //6\n                         {'p',  'q',  'r',  's'  }, //7\n                         {'t',  'u',  'v',  '\\0' }, //8\n                         {'w',  'x',  'y',  'z'  }  //9\n                       };\n\n    vector<string> result;\n    if (digits.size()<=0){\n        result.push_back(\"\");\n        return result;\n    }\n    for( int i=0; i<digits.size(); i++ ) {\n        if (!isdigit(digits[i])) {\n            vector<string> r;\n            return r;\n        } \n        int d = digits[i] - '0';\n        if (result.size()<=0){\n            for( int j=0; j<4 && phone[d][j]!='\\0'; j++ ){\n                string s;\n                s += phone[d][j];\n                result.push_back(s);\n            }\n            continue;\n        }\n        vector<string> r;\n        for (int j=0; j<result.size(); j++){\n            for( int k=0; k<4 && phone[d][k]!='\\0'; k++ ){\n                string s = result[j] + phone[d][k];\n                //sort(s.begin(), s.end());\n                r.push_back(s); \n            }\n        }\n        result = r;\n    }\n    //sort(result.begin(), result.end());\n\n    return result; \n}\n\nvoid printVector(vector<string>& ss){\n    cout << \"{ \";\n    for(int i=0; i<ss.size(); i++){\n        if (i>0) cout << \", \"; \n        cout << ss[i];\n    }\n    cout << \" }\" << endl;\n}\n\nint main(int argc, char**argv)\n{\n    string s=\"23\";\n    if (argc>1){\n        s=argv[1];\n    }\n    vector<string> ss = letterCombinations(s);\n    printVector(ss);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/lexicographicalNumbers/LexicographicalNumbers.cpp",
    "content": "// Source : https://leetcode.com/problems/lexicographical-numbers/\n// Author : Hao Chen\n// Date   : 2016-08-23\n\n/*************************************************************************************** \n *\n * Given an integer n, return 1 - n in lexicographical order.\n * \n * For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].\n * \n * Please optimize your algorithm to use less time and space. The input size may be as \n * large as 5,000,000.\n ***************************************************************************************/\nclass Solution {\n    \n//Solution 1: convert the int to string for sort, Time complexity is high (Time Limited Error)\npublic:\n    vector<int> lexicalOrder01(int n) {\n        vector<int> result;\n        for (int i=1; i<=n; i++) {\n            result.push_back(i);\n        }\n        sort(result.begin(), result.end(), this->myComp);\n        return result;\n    }\nprivate:\n    static bool myComp(int i,int j) { \n        static char si[32]={0}, sj[32]={0};\n        sprintf(si, \"%d\\0\", i);\n        sprintf(sj, \"%d\\0\", j);\n        return (strcmp(si, sj)<0); \n    }\n    \n    \n//Solution 2 : using recursive way to solution the problem, 540ms\npublic:\n    vector<int> lexicalOrder02(int n) {\n        vector<int> result;\n        for (int i=1; i<=n && i<=9; i++) {\n            result.push_back(i);\n            lexicalOrder_helper(i, n, result);\n        }\n        return result;\n    }\n    \nprivate:\n    void lexicalOrder_helper(int num, int& n, vector<int>& result) {\n        for (int i=0; i<=9; i++) {\n            int tmp = num * 10 + i;\n            if (tmp > n) {\n                break;\n            }\n            result.push_back(tmp);\n            lexicalOrder_helper(tmp, n, result);\n        }\n    }\n\n//Solution 3: no recursive way, but the code is not easy to read\npublic :\n    vector<int> lexicalOrder03(int n) {\n        vector<int> result;\n        int curr = 1;\n        while (result.size()<n) {\n            // Step One\n            // ---------\n            //Adding all of the possible number which multiply 10 as much as possible \n            // such as: curr = 1, then 1, 10, 100, 1000 ...\n            //          curr = 12, then 12, 120, 1200, ...\n            for (; curr <= n; curr*=10 ) {\n                result.push_back(curr);\n            }\n            \n            // Step Two\n            // ---------\n            // After find the number which multiply 10 greater than `n`, then go back the previous one,\n            // and keep adding 1 until it carry on to next number\n            // for example:\n            //    curr = 100, then we need evalute:  11,12,13,14,15,16,17,18,19, but stop at 20\n            //    curr = 230, then we need evaluate: 24,25,26,27,28,29, but stop at 30.\n            curr = curr/10 + 1;\n            for (;  curr <= n &&  curr % 10 != 0; curr++) {\n                result.push_back(curr);\n            }\n\n            // Step Three\n            // ----------\n            // Now, we finished all of the number, we need go back for next number\n            // Here is a bit tricky.\n            // \n            // Assuming the n is 234, and Step One evaluted 190, and Step Two, evaluted 191,192,...,199\n            // Now, the `curr` is 200, and we need start from 2 instead of 20, that's why need keep dividing 10\n            for (; curr%10 == 0; curr/=10);\n           \n        }\n        return result;\n    }\n    \n    \n//start point\npublic:\n    vector<int> lexicalOrder(int n) {\n        srand(time(NULL));\n        if (rand()%2) \n            return lexicalOrder02(n); // recursive way  560ms\n        else \n            return lexicalOrder03(n); // non-recursive way, 460ms\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/lexicographicallySmallestStringAfterApplyingOperations/LexicographicallySmallestStringAfterApplyingOperations.cpp",
    "content": "// Source : https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/\n// Author : Hao Chen\n// Date   : 2021-03-24\n\n/***************************************************************************************************** \n *\n * You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\n * \n * You can apply either of the following two operations any number of times and in any order on s:\n * \n * \tAdd a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, \n * if s = \"3456\" and a = 5, s becomes \"3951\".\n * \tRotate s to the right by b positions. For example, if s = \"3456\" and b = 1, s becomes \n * \"6345\".\n * \n * Return the lexicographically smallest string you can obtain by applying the above operations any \n * number of times on s.\n * \n * A string a is lexicographically smaller than a string b (of the same length) if in the first \n * position where a and b differ, string a has a letter that appears earlier in the alphabet than the \n * corresponding letter in b. For example, \"0158\" is lexicographically smaller than \"0190\" because the \n * first position they differ is at the third letter, and '5' comes before '9'.\n * \n * Example 1:\n * \n * Input: s = \"5525\", a = 9, b = 2\n * Output: \"2050\"\n * Explanation: We can apply the following operations:\n * Start:  \"5525\"\n * Rotate: \"2555\"\n * Add:    \"2454\"\n * Add:    \"2353\"\n * Rotate: \"5323\"\n * Add:    \"5222\"\n * ​​​​​​​Add:    \"5121\"\n * ​​​​​​​Rotate: \"2151\"\n * ​​​​​​​Add:    \"2050\"​​​​​​​​​​​​\n * There is no way to obtain a string that is lexicographically smaller then \"2050\".\n * \n * Example 2:\n * \n * Input: s = \"74\", a = 5, b = 1\n * Output: \"24\"\n * Explanation: We can apply the following operations:\n * Start:  \"74\"\n * Rotate: \"47\"\n * ​​​​​​​Add:    \"42\"\n * ​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\n * There is no way to obtain a string that is lexicographically smaller then \"24\".\n * \n * Example 3:\n * \n * Input: s = \"0011\", a = 4, b = 2\n * Output: \"0011\"\n * Explanation: There are no sequence of operations that will give us a lexicographically smaller \n * string than \"0011\".\n * \n * Example 4:\n * \n * Input: s = \"43987654\", a = 7, b = 3\n * Output: \"00553311\"\n * \n * Constraints:\n * \n * \t2 <= s.length <= 100\n * \ts.length is even.\n * \ts consists of digits from 0 to 9 only.\n * \t1 <= a <= 9\n * \t1 <= b <= s.length - 1\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    unordered_map<string, bool> processed;\n    void rotate_str(string& s, int n) {\n        std::rotate(s.begin(), s.begin()+n, s.end());\n    }\n    void add_str(string& s, int n) {\n        for(int i=1; i<s.size(); i+=2) {\n            s[i] = (s[i] -'0' + n) % 10 +'0';\n        }\n    }\npublic:\n    string findLexSmallestString(string s, int a, int b) {\n        string result = s;\n        dfs(s, a, b, result);\n        return result;\n    }\n    \n    void dfs(string& s, int a, int b, string& result) {\n        \n        if (processed.find(s) != processed.end()) return;\n        processed[s] = true;\n        \n        if (s < result) result = s;\n        \n        string str = s;\n        rotate_str(str, b); \n        dfs(str, a, b, result);\n        \n        str = s;\n        add_str(str, a); \n        dfs(str, a, b, result);\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/linkedListCycle/linkedListCycle.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/linked-list-cycle-ii/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.\n* \n* Follow up:\n* Can you solve it without using extra space?\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\n    \nprivate:\n    ListNode *p1, *p2;\npublic:\n    bool hasCycle(ListNode *head) {\n        \n        if (head==NULL) return false;\n        p1=head;\n        p2=head;\n        \n        while (p1!=NULL && p2!=NULL){\n            \n            p1=p1->next;\n            \n            if (p2->next == NULL) return false;\n            \n            p2=p2->next->next;\n            \n            if (p1==p2) return true;\n        }\n        \n        return false;\n        \n    }  \n    \n    /* \n     * So, the idea is:\n     *   1) Using the cycle-chcking algorithm.\n     *   2) Once p1 and p1 meet, then reset p1 to head, and move p1 & p2 synchronously\n     *      until p1 and p2 meet again, that place is the cycle's start-point \n     */\n    ListNode *detectCycle(ListNode *head) {\n        \n        if (hasCycle(head)==false){\n            return NULL;\n        }\n        \n        p1 = head;\n        \n        while (p1!=p2) {\n            p1 = p1->next;\n            p2 = p2->next;\n        }\n        \n        return p1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/linkedListCycle/linkedListCycle.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/linked-list-cycle/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a linked list, determine if it has a cycle in it.\n* \n* Follow up:\n* Can you solve it without using extra space?\n* \n*               \n**********************************************************************************/\n\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool hasCycle(ListNode *head) {\n        return hasCycle04(head);\n        return hasCycle03(head);\n        return hasCycle02(head);\n        return hasCycle01(head);\n    }\n\n\n    // using a map to store the nodes we walked\n    bool hasCycle01(ListNode *head) {\n        unordered_map<ListNode*,bool > m;\n        ListNode* p = head;\n        m[(ListNode*)NULL] = true;\n        while( m.find(p) == m.end() ) {\n            m[p] = true;\n            p = p -> next;\n        }\n        return p != NULL;\n    }\n\n    // Change the node's of value, mark the footprint by a special value\n    bool hasCycle02(ListNode *head) {\n        ListNode* p = head;\n        // using INT_MAX as the mark could be a bug!\n        while( p &&  p->val != INT_MAX ) {\n            p->val = INT_MAX;\n            p = p -> next;\n        }\n        return p != NULL;\n    }\n\n    /*\n     * if there is a cycle in the list, then we can use two pointers travers the list.\n     * one pointer traverse one step each time, another one traverse two steps each time.\n     * so, those two pointers meet together, that means there must be a cycle inside the list.\n     */\n    bool hasCycle03(ListNode *head) {\n        if (head==NULL || head->next==NULL) return false;\n        ListNode* fast=head;\n        ListNode* slow=head;\n        do{\n            slow = slow->next;\n            fast = fast->next->next;\n        }while(fast != NULL && fast->next != NULL && fast != slow);\n        return fast == slow? true : false;\n    }\n\n    // broken all of nodes \n    bool hasCycle04(ListNode *head) {\n         ListNode dummy (0);\n        ListNode* p = NULL;\n\n        while (head != NULL) {\n            p = head;\n            head = head->next;\n\n            // Meet the old Node that next pointed to dummy\n            //This is cycle of linked list\n            if (p->next == &dummy) return true;\n\n            p->next = &dummy; // next point to dummy\n        }\n        return false;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/linkedListRandomNode/LinkedListRandomNode.cpp",
    "content": "// Source : https://leetcode.com/problems/linked-list-random-node/\n// Author : Hao Chen\n// Date   : 2016-08-24\n\n/*************************************************************************************** \n *\n * Given a singly linked list, return a random node's value from the linked list. Each \n * node must have the same probability of being chosen.\n * \n * Follow up:\n * What if the linked list is extremely large and its length is unknown to you? Could \n * you solve this efficiently without using extra space?\n * \n * Example:\n * \n * // Init a singly linked list [1,2,3].\n * ListNode head = new ListNode(1);\n * head.next = new ListNode(2);\n * head.next.next = new ListNode(3);\n * Solution solution = new Solution(head);\n * \n * // getRandom() should return either 1, 2, or 3 randomly. Each element should have \n * equal probability of returning.\n * solution.getRandom();\n ***************************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    /** @param head The linked list's head.\n        Note that the head is guaranteed to be not null, so it contains at least one node. */\n    Solution(ListNode* head) {\n        this->head = head;\n        this->len = 0;\n        for(ListNode*p = head; p!=NULL; p=p->next, len++);\n        srand(time(NULL));\n    }\n    \n    /** Returns a random node's value. */\n    int getRandom() {\n        int pos = rand() % len;\n        ListNode *p = head;\n        for (; pos > 0; pos--, p=p->next);\n        return p->val;\n    }\n    ListNode* head;\n    int len;\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(head);\n * int param_1 = obj.getRandom();\n */\n"
  },
  {
    "path": "algorithms/cpp/longerContiguousSegmentsOfOnesThanZeros/LongerContiguousSegmentsOfOnesThanZeros.cpp",
    "content": "// Source : https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer \n * than the longest contiguous segment of 0s in s. Return false otherwise.\n * \n * \tFor example, in s = \"110100010\" the longest contiguous segment of 1s has length 2, and the \n * longest contiguous segment of 0s has length 3.\n * \n * Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have \n * length 0. The same applies if there are no 1s.\n * \n * Example 1:\n * \n * Input: s = \"1101\"\n * Output: true\n * Explanation:\n * The longest contiguous segment of 1s has length 2: \"1101\"\n * The longest contiguous segment of 0s has length 1: \"1101\"\n * The segment of 1s is longer, so return true.\n * \n * Example 2:\n * \n * Input: s = \"111000\"\n * Output: false\n * Explanation:\n * The longest contiguous segment of 1s has length 3: \"111000\"\n * The longest contiguous segment of 0s has length 3: \"111000\"\n * The segment of 1s is not longer, so return false.\n * \n * Example 3:\n * \n * Input: s = \"110100010\"\n * Output: false\n * Explanation:\n * The longest contiguous segment of 1s has length 2: \"110100010\"\n * The longest contiguous segment of 0s has length 3: \"110100010\"\n * The segment of 1s is not longer, so return false.\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \ts[i] is either '0' or '1'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool checkZeroOnes(string s) {\n        int zeros = 0;\n        int ones = 0;\n        int i = 0;\n        while (i < s.size()) {\n            if(s[i] == '0') {\n                int cnt = 0;\n                for (;s[i] == '0' && i < s.size(); i++) cnt++;\n                zeros = max(zeros, cnt);\n            }else {\n                int cnt = 0;\n                for (;s[i] == '1'&& i < s.size(); i++) cnt++;\n                ones = max(ones, cnt);\n            }\n        }\n        return ones > zeros;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestAbsoluteFilePath/LongestAbsoluteFilePath.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-absolute-file-path/\n// Author : Hao Chen\n// Date   : 2016-08-23\n\n/*************************************************************************************** \n *\n * Suppose we abstract our file system by a string in the following manner:\n * \n * The string \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\" represents:\n * \n * dir\n *     subdir1\n *     subdir2\n *         file.ext\n * \n * The directory dir contains an empty sub-directory subdir1 and a sub-directory \n * subdir2 containing a file file.ext.\n * \n * The string \n * \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile\n * 2.ext\" represents:\n * \n * dir\n *     subdir1\n *         file1.ext\n *         subsubdir1\n *     subdir2\n *         subsubdir2\n *             file2.ext\n * \n * The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains \n * a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 \n * contains a second-level sub-directory subsubdir2 containing a file file2.ext.\n * \n * We are interested in finding the longest (number of characters) absolute path to a \n * file within our file system. For example, in the second example above, the longest \n * absolute path is \"dir/subdir2/subsubdir2/file2.ext\", and its length is 32 (not \n * including the double quotes).\n * \n * Given a string representing the file system in the above format, return the length \n * of the longest absolute path to file in the abstracted file system. If there is no \n * file in the system, return 0.\n * \n * Note:\n * \n * The name of a file contains at least a . and an extension.\n * The name of a directory or sub-directory will not contain a ..\n * \n * Time complexity required: O(n) where n is the size of the input string.\n * \n * Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another \n * path aaaaaaaaaaaaaaaaaaaaa/sth.png.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    // Solution\n    // --------\n    // We can see the input formation has the order\n    // so, we can maintain an array which states the current level's path length\n    //\n    // For example:\n    //    dir\n    //        subdir1            <- length[ level1 = len(\"dir\")+len(\"/\"), \n    //                                      level2 = len(\"dir\")+len(\"/\")+len(\"subdir1\")+len(\"/\") ] \n    //           file.ext\n    //        subdir2\n    //           file.ext\n    //           subsubdir1     <- length[ level1 = len(\"dir\")+len(\"/\"), \n    //                                     level2 = len(\"dir\")+len(\"/\")+len(\"subdir2\")+len(\"/\"), \n    //                                     level3 = len(\"dir\")+len(\"/\")+len(\"subdir2\")+len(\"/\")+len(\"subsubdir1\")+len(\"/\") ] \n    //               file.ext  \n    //\n    int lengthLongestPath(string input) {\n        \n         stringstream ss(input); \n         string line;\n         int result = 0;\n         \n         vector<int> length;\n         length.push_back(0); //initialize top dummy level's length is zero\n        \n         while (getline(ss, line, '\\n')) {\n             //get current level, start from 1\n             int level = 0;\n             while ( line[level++] == '\\t'); // get the level\n             int len = line.size() - level + 1;\n\n             //if is a file, then cacualte the total length.\n             if (line.find('.') != string::npos) { \n                 if ( length[level-1] + len > result ) {\n                    result = length[level-1] + len;\n                 }\n             } else {\n                \n                 if (length.size() <= level) {\n                     length.push_back(0); \n                 }\n                 \n                 // if it a folder, then update the current level's length\n                 length[level] = length[level-1] + len + 1; // 1 for \"/\" path delimiter\n             }\n             \n         }\n         return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-common-prefix/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Write a function to find the longest common prefix string amongst an array of strings.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\n\nstring longestCommonPrefix(vector<string> &strs) {\n    string word;\n    if (strs.size()<=0) return word;\n    for(int i=1; i<=strs[0].size(); i++){\n        string w = strs[0].substr(0, i);\n        bool match = true;\n        int j=1;\n        for(j=1; j<strs.size(); j++){\n            if (i>strs[j].size() || w!=strs[j].substr(0, i) ) {\n                match=false;\n                break;\n            }\n        }\n        if (!match) {\n            return word;\n        }\n        word = w;\n    }\n    return word;\n}\n\nint main()\n{\n    const char* s[]={\"abab\",\"aba\",\"abc\"};\n    vector<string> v(s, s+3);\n    cout << longestCommonPrefix(v) <<endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/longestConsecutiveSequence/longestConsecutiveSequence.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-consecutive-sequence/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.\n* \n* For example,\n* Given [100, 4, 200, 1, 3, 2],\n* The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.\n* \n* Your algorithm should run in O(n) complexity.\n* \n*               \n**********************************************************************************/\n\n//\n//  Obviously, the easist way is sort the array, however the run-time complexity is O(nlogn)\n//  \n//  If we cannot use the sort algorithm, then it seems we have to use O(n^2) solution.\n//\n//  That's fine, let's take a look the O(n^2) soultion\n//\n//      1) for each item num[i] in the array\n//      2) for loop to seach ...... num[i-2], num[i-1],  num[i]+1, num[i]+2 ......\n//  \n//  We can see, the search is really heavy, and the best data structure for seaching is HashMap.\n//  hash map is O(1) run-time complexity for seaching.\n//\n//  So, we can have the following solution by using Hash Map.\n//   \n\nclass Solution {\npublic:\n    int longestConsecutive(vector<int> &num) {\n        \n        map<int, int> m;\n        for (int i=0; i<num.size(); i++){\n            m[num[i]]=i;\n        }\n        \n        int max_seq=0; \n        for (int i=0; i<num.size(); i++){\n            int cnt=1;\n            \n            for(int n = num[i]+1;m.find(n)!=m.end();n++){\n                m.erase(m.find(n));\n                cnt++;\n                \n            }\n            for(int n = num[i]-1;m.find(n)!=m.end();n--){\n                m.erase(m.find(n));\n                cnt++;\n            }\n            if (max_seq < cnt){\n                max_seq = cnt;\n            }\n            if (m.size()==0){\n                break;\n            }\n        }\n        return max_seq;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-increasing-path-in-a-matrix/\n// Author : Hao Chen\n// Date   : 2016-01-21\n\n/*************************************************************************************** \n *\n * Given an integer matrix, find the length of the longest increasing path.\n * \n * From each cell, you can either move to four directions: left, right, up or down. You \n * may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not \n * allowed).\n * \n * Example 1:\n * \n * nums = [\n *   [>9, 9, 4],\n *   [>6, 6, 8],\n *   [>2,>1, 1]\n * ]\n * \n * Return 4\n * \n * The longest increasing path is [1, 2, 6, 9].\n * \n * Example 2:\n * \n * nums = [\n *   [>3,>4,>5],\n *   [ 3, 2,>6],\n *   [ 2, 2, 1]\n * ]\n * \n * Return 4\n * \n * The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    int longestIncreasingPath(vector<vector<int>>& matrix) {\n        int result = 0;\n        int row = matrix.size();\n        int col = row ? matrix[0].size() : 0;\n        vector<vector<int>> path = vector<vector<int>>(row, vector<int>(col, 0));\n        for (int r = 0; r < row; r++) {\n            for (int c = 0; c < col; c++) {\n                result = max(result, helper(matrix, path, row, col, r, c));\n            }\n        }\n        return result;\n    }\n    \n    int helper(vector<vector<int>>& matrix, vector<vector<int>>& path, const int row, const int col, int r, int c) {\n\n        if (path[r][c]>0) return path[r][c];\n        \n        int maxPath = 0;\n        \n        int tmp = matrix[r][c]; \n        matrix[r][c]=INT_MIN;  \n        if (r < row-1 && tmp < matrix[r+1][c]) {\n            maxPath = max(maxPath, helper(matrix, path, row, col, r+1, c));\n        }\n        if (c < col-1 && tmp < matrix[r][c+1]) {\n            maxPath = max(maxPath, helper(matrix, path, row, col, r, c+1));\n        }\n        if (r > 0 && tmp < matrix[r-1][c]) {\n            maxPath = max(maxPath, helper(matrix, path, row, col, r-1, c));\n        }\n        if (c > 0 && tmp < matrix[r][c-1]) {\n            maxPath = max(maxPath, helper(matrix, path, row, col, r, c-1));\n        }\n        matrix[r][c] = tmp;\n        path[r][c] = maxPath + 1;\n        return path[r][c];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestIncreasingSubsequence/longestIncreasingSubsequence.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-increasing-subsequence/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-11-06\n\n/*************************************************************************************** \n *\n * Given an unsorted array of integers, find the length of longest increasing\n * subsequence.\n *\n * For example,\n * Given [10, 9, 2, 5, 3, 7, 101, 18],\n * The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4.\n * Note that there may be more than one LIS combination, it is only necessary for yo\n * to return the length.\n * \n * Your algorithm should run in O(n2) complexity.\n * \n * Follow up: Could you improve it to O(n log n) time complexity?\n * \n * Credits:\n * Special thanks to @pbrother for adding this problem and creating all test cases.\n *               \n ***************************************************************************************/\n\n\n\n// O(n^2) - dynamic programming\nclass Solution {\npublic:\n    int lengthOfLIS(vector<int>& nums) {\n        \n        int len = nums.size();\n        int maxLen = 0;\n        vector<int> dp(len, 1);\n        \n        for (int i=0; i<len; i++) {\n            for(int j=0; j<i; j++) {\n                if ( nums[j] < nums[i] ) {\n                    dp[i] = max(dp[i], dp[j] + 1);\n                }\n            }\n            maxLen = max(maxLen, dp[i]);\n        }\n        return maxLen;\n    }\n};\n\n\nclass Solution {\npublic:\n    \n/* \n * Solution 1 - O(N^2)\n * =========\n *\n * LIS - longest increasing subsequence\n *\n * We iterate through the elements to find the LIS that ends with the current element. \n * To do that we need to look at all of the previous elements and find one smaller than\n * the current one so that we can add the current one to the sequence terminated in the \n * smaller one. The length of the LIS ending in the current element is the length of the\n * LIS ending in the smaller one + 1. To find the maximum current LIS we need to use the\n * maximum previous LIS that satisfies the conditions.\n * \n */\n    vector <int> longest_LIS;\n    int lengthOfLIS(vector<int>& nums) {\n        int answer = 0;\n        if(nums.size())\n        {   \n            longest_LIS.push_back(1);\n            answer = 1;\n            for(int i = 1; i < nums.size(); i++)\n            {\n                int maximum = 1;\n                for(int j = 0; j < longest_LIS.size(); j++)\n                    if(nums[i] > nums[j])\n                        maximum = max(maximum, longest_LIS[j] + 1);\n                longest_LIS.push_back(maximum);\n                answer = max(maximum, answer);\n            }\n        }\n        return answer;\n    }\n/* \n * Solution 2 - O(N * logN)\n * =========\n *\n * LIS - longest increasing subsequence\n * \n * We iterate through the elements to find the position of the current element in the\n * current LIS. After we find its position we change the LIS replacing the next biggest \n * element with the current one or increase the size of the sequence if the current element\n * is bigger than the biggest one. This way we keep the LIS with the smallest possible\n * elements. By keeping any other LIS we can encounter an element that could have been added\n * to the LIS with the smallest elements, but can't be added to the current one, therefore\n * missing the solution.\n * \n */\n    vector <int> longest_subsequence; // the LIS\n    vector <int> nums;\n    int binary_search(int number)\n    {\n        int start = 0, end = longest_subsequence.size() - 1;\n        if(start == end)\n        {\n            if(number > longest_subsequence[start])\n                return start + 1;\n            else\n                return start;\n        }\n        while(start < end)\n        {\n            if(start == end - 1)\n            {\n                if(number > longest_subsequence[start] && number <= longest_subsequence[end])\n                    return end;\n                else if(number <= longest_subsequence[start])\n                    return start;\n                else\n                    return end + 1;\n            }\n            int middle = (start + end + 1) / 2;\n            if(longest_subsequence[middle] < number)\n                start = middle;\n            else\n                end = middle;\n        }\n    }\n    int lengthOfLIS(vector<int>& nums) {\n        int answer = 0;\n        if(nums.size())\n        {   \n            answer = 1;\n            longest_subsequence.push_back(nums[0]);\n            for(int i = 1; i < nums.size(); i++)\n            {\n                int position = binary_search(nums[i]);\n                if(position == longest_subsequence.size())\n                    longest_subsequence.push_back(nums[i]);\n                else\n                    longest_subsequence[position] = nums[i];\n                answer = max(answer, position + 1);\n            }\n        }\n        return answer;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestNiceSubstring/LongestNiceSubstring.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-nice-substring/\n// Author : Hao Chen\n// Date   : 2021-03-08\n\n/***************************************************************************************************** \n *\n * A string s is nice if, for every letter of the alphabet that s contains, it appears both in \n * uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' \n * appear. However, \"abA\" is not because 'b' appears, but 'B' does not.\n * \n * Given a string s, return the longest substring of s that is nice. If there are multiple, return the \n * substring of the earliest occurrence. If there are none, return an empty string.\n * \n * Example 1:\n * \n * Input: s = \"YazaAay\"\n * Output: \"aAa\"\n * Explanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both \n * 'A' and 'a' appear.\n * \"aAa\" is the longest nice substring.\n * \n * Example 2:\n * \n * Input: s = \"Bb\"\n * Output: \"Bb\"\n * Explanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n * \n * Example 3:\n * \n * Input: s = \"c\"\n * Output: \"\"\n * Explanation: There are no nice substrings.\n * \n * Example 4:\n * \n * Input: s = \"dDzeE\"\n * Output: \"dD\"\n * Explanation: Both \"dD\" and \"eE\" are the longest nice substrings.\n * As there are multiple longest nice substrings, return \"dD\" since it occurs earlier.\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \ts consists of uppercase and lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\n    inline int getCharIndex(char c) {\n        return  (c >='A' && c <='Z') ? c - 'A' : c - 'a';\n    }\n    inline int getCaseIndex(char c) {\n         return (c >='A' && c <='Z') ? 1 : 0;\n    }\npublic:\n    string longestNiceSubstring(string s) {\n        vector<bitset<26>> check(2);\n        int start = 0, len = 0;\n        for (int i = 0; i < s.size() -1; i++){\n            for (int j = i+1; j < s.size(); j++) {\n                \n                check[0] = check[1] = 0;\n                for (int x=i; x<=j; x++){\n                    int i = getCaseIndex(s[x]);\n                    int j = getCharIndex(s[x]);\n                    check[i][j] = true;\n                }\n                \n                if ( (check[0] ^ check[1]) == 0 ) {\n                    if ( j - i + 1 > len ){\n                        start = i;\n                        len = j-i+1;\n                    }\n                }\n            }\n        }\n        \n        return s.substr(start, len);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestPalindrome/LongestPalindrome.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-palindrome/\n// Author : Hao Chen\n// Date   : 2016-11-13\n\n/*************************************************************************************** \n *\n * Given a string which consists of lowercase or uppercase letters, find the length of \n * the longest palindromes that can be built with those letters.\n * \n * This is case sensitive, for example \"Aa\" is not considered a palindrome here.\n * \n * Note:\n * Assume the length of given string will not exceed 1,010.\n * \n * Example: \n * \n * Input:\n * \"abccccdd\"\n * \n * Output:\n * 7\n * \n * Explanation:\n * One longest palindrome that can be built is \"dccaccd\", whose length is 7.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int longestPalindrome(string s) {\n        \n        int hashtable[128];\n        memset(hashtable, 0, sizeof(hashtable));\n        \n        for(char ch : s) {\n            hashtable[ch]++;\n        }\n        int result = 0;\n        bool hasOdd = false;\n        for (int n : hashtable) {\n            if ( n%2 == 0 ) {\n                result += n;\n            } else {\n                result += n -1;\n                hasOdd = true;\n            }\n        }\n        \n        return hasOdd ? result + 1 : result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestPalindromicSubsequence/LongestPalindromicSubsequence.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-palindromic-subsequence/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * Given a string s, find the longest palindromic subsequence's length in s.\n * \n * A subsequence is a sequence that can be derived from another sequence by deleting some or no \n * elements without changing the order of the remaining elements.\n * \n * Example 1:\n * \n * Input: s = \"bbbab\"\n * Output: 4\n * Explanation: One possible longest palindromic subsequence is \"bbbb\".\n * \n * Example 2:\n * \n * Input: s = \"cbbd\"\n * Output: 2\n * Explanation: One possible longest palindromic subsequence is \"bb\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 1000\n * \ts consists only of lowercase English letters.\n ******************************************************************************************************/\n\n/*\n\n   supposed s = \"abbcba\"\n   \n   we can have a matrix, \n  \n   - dp[start, end] is the longest from s[start] to s[end]\n  \n   - if (start == end) dp[statr, end] = 1, it means every char can be palindromic\n  \n            a b b c b a\n         a  1 0 0 0 0 0  \n         b  0 1 0 0 0 0 \n         b  0 0 1 0 0 0\n         c  0 0 0 1 0 0\n         b  0 0 0 0 1 0\n         a  0 0 0 0 0 1 \n  \n  \n  \n  calculating from the bottom to up. (Note: only care about the top-right trangle)\n  \n            a  b  b  c  b  a\n         a  1  1  2  2  3 [5]  <--  a == a , so \"abbcba\" comes from \"bbcb\" + 2 \n         b  0  1 [2] 2  3  3   <--  b == b , so \"bb\" comes from \"\" + 2\n         b  0  0  1  1 [3] 3   <--  b == b , so \"bcb\" comes from \"c\" + 2 \n         c  0  0  0  1  1 [1]  <--  c != a , so \"cba\" comes from max(\"cb\", \"a\") \n         b  0  0  0  0  1 [1]  <--  b != a , so \"ba\" comes from max (\"b\", \"a\")\n         a  0  0  0  0  0  1 \n         \n  So, we can have the following formular:\n  \n       s[start] != s[end]  ==> dp[start, end] = max (dp[start+1, end], dp[start, end-1]);\n       s[start] == s[end]  ==> dp[start, end] = dp[start+1, end-1] + 2;\n\n*/\n\n\nclass Solution {\npublic:\n    int longestPalindromeSubseq(string s) {\n        int n = s.size(); \n        vector<vector<int>> dp(n, vector<int>(n, 0));\n        \n        for (int start = n-1; start>=0; start--) {\n            for (int end = start ; end < n ; end++) {\n                if (start == end) {\n                    dp[start][end] = 1;\n                    continue;\n                }\n                if (s[start] == s[end]) {\n                    dp[start][end] = dp[start+1][end-1] + 2;\n                }else{\n                     dp[start][end] = max (dp[start+1][end], dp[start][end-1]);\n                }\n                \n            }\n        }\n        return dp[0][n-1];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-palindromic-substring/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Given a string S, find the longest palindromic substring in S. \n* You may assume that the maximum length of S is 1000, \n* and there exists one unique longest palindromic substring.\n*               \n**********************************************************************************/\n\n#include <string.h>\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nstring findPalindrome(string s, int left, int right)\n{\n    int n = s.size();\n    int l = left;\n    int r = right;\n    while (left>=0 && right<=n-1 && s[left] == s[right]) {\n        left--;\n        right++;\n    }\n    return s.substr(left+1, right-left-1);\n}\n\n\n// This is the common solution.\n// Actuatlly it's faster than DP solution under Leetcode's test\n// the below optimized DP solution need 700ms+, this needs around 250ms.\nstring longestPalindrome_recursive_way(string s) {\n    int n = s.size();\n    if (n<=1) return s;\n\n    string longest;\n    \n    string str;\n    for (int i=0; i<n-1; i++) {\n        str = findPalindrome(s, i, i);\n        if (str.size() > longest.size()){\n            longest = str;\n        } \n        str = findPalindrome(s, i, i+1);\n        if (str.size() > longest.size()){\n            longest = str;\n        } \n    }\n\n    return longest; \n}\n\n//================================================================================\n\n\nvoid findPalindrome(string s, int left, int right, int& start, int& len)\n{\n    int n = s.size();\n    int l = left;\n    int r = right;\n    while (left>=0 && right<=n-1 && s[left] == s[right]) {\n        left--;\n        right++;\n    }\n    if (right-left-1 > len){\n        len = right-left-1;\n        start = left+1;\n    }\n}\n\n//The following solution is better than previous solution.\n//Because it remove the sub-string return in findPalindrome().\nstring longestPalindrome_recursive_way2(string s) {\n    int n = s.size();\n    if (n<=1) return s;\n\n    int start=0, len=0; \n    string longest;\n\n    string str;\n    for (int i=0; i<n-1; i++) {\n        findPalindrome(s, i, i, start, len);\n        findPalindrome(s, i, i+1, start, len);\n    }\n\n    return s.substr(start, len);\n}\n\n//================================================================================\n\n// Time/Memory Limit Exceeded\nstring longestPalindrome_dp_way(string s) {\n\n    string longest;\n\n    int n = s.size();\n    if (n<=1) return s;\n    \n    //Construct a matrix, and consdier matrix[i][j] as s[i] -> s[j] is Palindrome or not.\n\n    //using char or int could cause the `Memory Limit Error`\n    //vector< vector<char> > matrix (n, vector<char>(n));\n\n    //using bool type could cause the `Time Limit Error`\n    vector< vector<bool> > matrix (n, vector<bool>(n));\n\n    // Dynamic Programming \n    //   1) if i == j, then matrix[i][j] = true;\n    //   2) if i != j, then matrix[i][j] = (s[i]==s[j] && matrix[i+1][j-1])\n    for (int i=n-1; i>=0; i--){\n        for (int j=i; j<n; j++){\n            // The following if statement can be broken to \n            //   1) i==j, matrix[i][j] = true\n            //   2) the length from i to j is 2 or 3, then, check s[i] == s[j]\n            //   3) the length from i to j > 3, then, check s[i]==s[j] && matrix[i+1][j-1]\n            if ( i==j || (s[i]==s[j] && (j-i<2 || matrix[i+1][j-1]) ) )  {\n                matrix[i][j] = true;\n                if (longest.size() < j-i+1){\n                    longest = s.substr(i, j-i+1);\n                }\n            }\n        }\n    }\n\n    return longest;\n}\n\n// Optimized DP soltuion can be accepted by LeetCode.\nstring longestPalindrome_dp_opt_way(string s) {\n\n    int n = s.size();\n    if (n<=1) return s;\n\n    //Construct a matrix, and consdier matrix[j][i] as s[i] -> s[j] is Palindrome or not.\n    //                                 ------^^^^^^\n    //                                 NOTE: it's [j][i] not [i][j]\n\n    //Using vector  could cause the `Time Limit Error`\n    //So, use the native array\n    bool **matrix  = (bool**)malloc(n*sizeof(bool*));\n    int start=0, len=0;\n    // Dynamic Programming\n    //   1) if i == j, then matrix[i][j] = true;\n    //   2) if i != j, then matrix[i][j] = (s[i]==s[j] && matrix[i-1][j+1])\n    for (int i=0; i<n; i++){\n        matrix[i] = (bool*)malloc((i+1)*sizeof(bool));\n        memset(matrix[i], false, (i+1)*sizeof(bool));\n        matrix[i][i]=true;\n        for (int j=0; j<=i; j++){\n            // The following if statement can be broken to\n            //   1) j==i, matrix[i][j] = true\n            //   2) the length from j to i is 2 or 3, then, check s[i] == s[j]\n            //   3) the length from j to i > 3, then, check s[i]==s[j] && matrix[i-1][j+1]\n            if ( i==j || (s[j]==s[i] && (i-j<2 || matrix[i-1][j+1]) ) )  {\n                matrix[i][j] = true;\n                if (len < i-j+1){\n                    start = j;\n                    len = i-j+1;\n                }\n            }\n        }\n    }\n\n    for (int i=0; i<n; i++) { \n        free (matrix[i]);\n    }\n    free(matrix);\n\n    return s.substr(start, len);\n}\n\n\nstring longestPalindrome(string s) {\n    return longestPalindrome_dp_way(s);\n    return longestPalindrome_dp_opt_way(s);\n    return longestPalindrome_recursive_way2(s);\n    return longestPalindrome_recursive_way(s);\n}\n\nint main(int argc, char**argv)\n{\n    string s = \"abacdfgdcaba\";\n    if (argc > 1){\n        s = argv[1];\n    }\n    cout <<  s << \" : \" << longestPalindrome(s) << endl;\n\n    s = \"321012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210012321001232100123210123210012321001232100123210123\";\n    cout <<  s << \" : \" << longestPalindrome(s) << endl;\n \n    //\"illi\"\n    s = \"iptmykvjanwiihepqhzupneckpzomgvzmyoybzfynybpfybngttozprjbupciuinpzryritfmyxyppxigitnemanreexcpwscvcwddnfjswgprabdggbgcillisyoskdodzlpbltefiz\";\n    cout <<  s << \" : \" << longestPalindrome(s) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/longestSubstringOfAllVowelsInOrder/LongestSubstringOfAllVowelsInOrder.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/\n// Author : Hao Chen\n// Date   : 2021-04-25\n\n/***************************************************************************************************** \n *\n * A string is considered beautiful if it satisfies the following conditions:\n * \n * \tEach of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.\n * \tThe letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's \n * before 'i's, etc.).\n * \n * For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", \n * and \"aaaeeeooo\" are not beautiful.\n * \n * Given a string word consisting of English vowels, return the length of the longest beautiful \n * substring of word. If no such substring exists, return 0.\n * \n * A substring is a contiguous sequence of characters in a string.\n * \n * Example 1:\n * \n * Input: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\n * Output: 13\n * Explanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\n * \n * Example 2:\n * \n * Input: word = \"aeeeiiiioooauuuaeiou\"\n * Output: 5\n * Explanation: The longest beautiful substring in word is \"aeiou\" of length 5.\n * \n * Example 3:\n * \n * Input: word = \"a\"\n * Output: 0\n * Explanation: There is no beautiful substring, so return 0.\n * \n * Constraints:\n * \n * \t1 <= word.length <= 5 * 10^5\n * \tword consists of characters 'a', 'e', 'i', 'o', and 'u'.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    enum Vowels{\n        A = 0,\n        E = 1,\n        I = 2,\n        O = 3,\n        U = 4,\n        INVAILD = -1,\n    };\n    \n    Vowels isVowels(char c) {\n        switch(c) {\n            case 'a' : return A;\n            case 'e' : return E;\n            case 'i' : return I;\n            case 'o' : return O;\n            case 'u' : return U;\n        }\n        return INVAILD;\n    }\npublic:\n    int longestBeautifulSubstring(string word) {\n        word += 'a';\n        int len = 0;\n        for(int i=0; i<word.size(); i++) {\n            if (word[i] != 'a') continue;\n            \n            int prevIdx = A;\n            int j=i;\n            for(; j<word.size(); j++) {\n                int currIdx = isVowels(word[j]);\n                // the current char is same as before.\n                if ( currIdx == prevIdx || currIdx == INVAILD) continue;\n                // the current char is the next vowel.\n                if ( currIdx == prevIdx + 1) { prevIdx++; continue;}\n                // the current char is not in order, \n                // and the previous char is the final vowel.\n                if ( prevIdx == U ){\n                    len = max(len, j-i);\n                }\n                break;\n            }\n            i = j-1;\n        }\n        return len;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * Find the length of the longest substring T of a given string (consists of lowercase \n * letters only) such that every character in T appears no less than k times.\n * \n * Example 1:\n * \n * Input:\n * s = \"aaabb\", k = 3\n * \n * Output:\n * 3\n * \n * The longest substring is \"aaa\", as 'a' is repeated 3 times.\n * \n * Example 2:\n * \n * Input:\n * s = \"ababbc\", k = 2\n * \n * Output:\n * 5\n * \n * The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 \n * times.\n ***************************************************************************************/\n\nconst int NO_OF_CHARS = 256;\n\n/* if every character appears at least k times, the whole string is ok. \n * Otherwise split by a least frequent character.\n * \n * Because it will always be too infrequent and thus can't be part of any ok substring\n * and make the most out of the splits.\n */\n\n\nclass Solution {\npublic:\n    int longestSubstring(string s, int k) {\n        \n        //deal with edge cases\n        if (s.size() == 0 || s.size() < k) return 0;\n        if (k==1) return s.size();\n\n        //declare a map for every char's counter\n        int count[NO_OF_CHARS];\n        memset(count , 0, sizeof(count));\n        \n        //counting every char\n        for (char ch : s) {\n            count[ch]++;\n        }\n        \n        int i=0;\n        for ( i=0; i<NO_OF_CHARS; i++) {\n            if (count[i] !=0 && count[i] < k) break;\n        }\n        //all of the chars meet the requirement\n        if ( i >= NO_OF_CHARS ) return s.size();\n        \n        // find the most infrequent char\n        char least = 0;\n        for (int c = 0; c < NO_OF_CHARS; c++) {\n            if (count[c] == 0) continue;\n            if (least == 0) {\n                least = c;\n            } else if ( count[c] < count[least]) {\n                least = c;\n            }\n        }\n        \n        //split the string and run them recursively\n        vector<string> subs;\n        split(s, least, subs);\n        \n        int res = 0;\n        for (string str: subs) {\n            res = max(res, longestSubstring(str, k));\n        }\n        return res;\n        return 0;\n    }\n    \nprivate:\n    \n    inline int max(int x, int y) { return x>y? x:y; }\n    \n    inline void split(const string &s, char delim, vector<string> &elems) {\n        stringstream ss;\n        ss.str(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            cout << item << endl;\n            elems.push_back(item);\n        }\n    }\n\n\n    inline vector<string> split(const string &s, char delim) {\n        vector<string> elems;\n        split(s, delim, elems);\n        return elems;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestSubstringWithAtMostTwoDistinctCharacters/longestSubstringWithAtMostTwoDistinctCharacters.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/\n// Author : Hao Chen\n// Date   : 2014-12-01\n\n/*\n * Given a string, find the length of the longest substring T that contains at most 2 distinct characters.\n * \n * For example, Given s = “eceba”,\n * \n * T is \"ece\" which its length is 3.\n */\n\n\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\n/*\n * Idea:\n *\n *    1) Using a map to count every char(s).\n *    2) Using a 'cnt' to count the current distinct chars.\n *    3) If `cnt > 2`, then go through the previous substring to decrease each char's count which stored in the map,\n *       if one of char's count decrease to zero, then the global distinct chars `cnt` decrease one.\n *       During the travel, maintain a pointer `start` to point the start position of sub-string.\n *\n * The following algorithm run-time complexity is O(n^2)\n *\n * This solution can be easy to extend to \"find the length of longest substring with at most K distinct char(s)\"\n */\nint lengthOfLongestSubstringTwoDistinct(string s) {\n    int maxLen = 0;\n    int charMap[256] = {0};\n    int wordCnt = 0;\n    int start = 0;\n\n    for(int i=0; i<s.size(); i++){\n        if ( charMap[s[i]]++ == 0 ){\n            wordCnt++;\n        }\n        while (wordCnt>2){\n            charMap[s[start]]--;\n            if (charMap[s[start]]==0){\n                wordCnt--;\n            }\n            start++;\n        }\n        maxLen = max(maxLen, i - start + 1);\n    }\n\n    return maxLen;\n}\n\n\nint main(int argc, char** argv)\n{\n    string s = \"eceba\";\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << s << \" : \" << lengthOfLongestSubstringTwoDistinct(s) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Given a string, find the length of the longest substring without repeating characters. \n* For example, the longest substring without repeating letters for \"abcabcbb\" is \"abc\", \n* which the length is 3. For \"bbbbb\" the longest substring is \"b\", with the length of 1.\n*               \n**********************************************************************************/\n\n#include <string.h>\n#include <iostream>\n#include <string>\n#include <map>\nusing namespace std;\n/*\n * Idea:\n * \n * Using a map store each char's index.\n * \n * So, we can be easy to know the when duplication and the previous duplicated char's index.\n * \n * Then we can take out the previous duplicated char, and keep tracking the maxiumn length. \n * \n */\nint lengthOfLongestSubstring1(string s) {\n    map<char, int> m;\n    int maxLen = 0;\n    int lastRepeatPos = -1;\n    for(int i=0; i<s.size(); i++){\n        if (m.find(s[i])!=m.end() && lastRepeatPos < m[s[i]]) {\n            lastRepeatPos = m[s[i]];\n        }\n        if ( i - lastRepeatPos > maxLen ){\n            maxLen = i - lastRepeatPos;\n        }\n        m[s[i]] = i;\n    }\n    return maxLen;\n}\n//don't use <map>\nint lengthOfLongestSubstring(string s) {\n    const int MAX_CHARS = 256;\n    int m[MAX_CHARS];\n    memset(m, -1, sizeof(m));\n\n    int maxLen = 0;\n    int lastRepeatPos = -1;\n    for(int i=0; i<s.size(); i++){\n        if (m[s[i]]!=-1 && lastRepeatPos < m[s[i]]) {\n            lastRepeatPos = m[s[i]];\n        }\n        if ( i - lastRepeatPos > maxLen ){\n            maxLen = i - lastRepeatPos;\n        }\n        m[s[i]] = i;\n    }\n    return maxLen;\n}\n\nint main(int argc, char** argv)\n{\n    string s = \"abcabcbb\";\n    cout << s << \" : \" << lengthOfLongestSubstring(s) << endl;\n\n    s = \"bbbbb\";\n    cout << s << \" : \" << lengthOfLongestSubstring(s) << endl;\n\n    s = \"bbabcdb\";\n    cout << s << \" : \" << lengthOfLongestSubstring(s) << endl;\n\n    if (argc>1){\n        s = argv[1];\n        cout << s << \" : \" << lengthOfLongestSubstring(s) << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/longestTurbulentSubarray/LongestTurbulentSubarray.cpp",
    "content": "// Source : https://leetcode.com/problems/longest-turbulent-subarray/\n// Author : Hao Chen\n// Date   : 2019-01-26\n\n/***************************************************************************************************** \n *\n * A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:\n * \n * \tFor i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;\n * \tOR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.\n * \n * That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of \n * elements in the subarray.\n * \n * Return the length of a maximum size turbulent subarray of A.\n * \n * Example 1:\n * \n * Input: [9,4,2,10,7,8,8,1,9]\n * Output: 5\n * Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])\n * \n * Example 2:\n * \n * Input: [4,8,12,16]\n * Output: 2\n * \n * Example 3:\n * \n * Input: [100]\n * Output: 1\n * \n * Note:\n * \n * \t1 <= A.length <= 40000\n * \t0 <= A[i] <= 109\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    \n    int maxTurbulenceSize_01(vector<int>& A) {\n        \n        if (A.size() <= 1) return A.size();\n        \n        // declare status to mark the current pair status is go up or go down.\n        enum Status {\n            up,\n            down,\n            none\n        } s = none;\n        \n        int maxlen = 1;\n        int len = 1;\n        \n        for (int i=1; i< A.size(); i++) {\n            \n            // if there is a pair is equal, reset the status\n            if ( A[i] == A[i-1] ) { \n                s = none;\n                continue;\n            }\n            \n            // init the first status\n            if ( s == none ) {\n                s = A[i] > A[i-1] ? up : down;\n                len = 2;\n                continue;\n            }\n            \n            // keep tracking the status\n            // make sure the status is zigzag pattern...up-down-up-down...\n            if ( s == up ) {\n                if ( A[i] < A[i-1] ) {\n                    len++;\n                    s = down;\n                }else{\n                    len=2;\n                }\n            }else{\n                if ( A[i] > A[i-1] ) {\n                    len++;\n                    s = up;\n                }else{\n                    len=2;\n                }\n            }\n            \n            maxlen = len > maxlen ? len : maxlen;\n            \n        }\n        return maxlen;\n    }\n    \n    // The previous solution is quite straight forward, but the code is a bit complcated \n    // the following solution tries to use another way to make the code simpler.\n    //\n    // Then, we need to tracking the previous length of the zigzag pattern.\n    //\n    // And we have to tacking the length for both UP and DOWN patterns \n    //\n    //   - UP means the previous status goes up. and the previous length of the zigzog pattern.\n    //   - DOWN is same.\n    //  \n    // So,  \n    //\n    //   - if the previous is UP, then the previous DWON must be 1, and vice versa.\n    //\n    //   - the current UP could be two values : 1 or DOWN + 1 , and vice versa. \n    //      - if A[k] > A[k-1], UP = DWON +1, otherwise UP = 1\n    //      - if A[K] < A[K-1], DOWN = UP + 1， otherise DOWN = 1\n    //\n    int maxTurbulenceSize_02(vector<int>& A) {\n        \n        if (A.size() <= 1) return A.size();\n        \n        int up = 1;\n        int down = 1;\n        int maxlen = 1;\n        \n        for (int k=1; k<A.size(); k++) {     \n            //memory the previous UP and Down\n            int u = up, d = down;\n            \n            up = (A[k] > A[k-1]) ? d + 1 : 1;\n            down =  (A[k] < A[k-1]) ? u + 1 : 1;\n\n            int len = down > up ? down : up;\n            maxlen = len > maxlen ? len : maxlen;\n        }\n        return maxlen;\n    }\n    \n    int maxTurbulenceSize(vector<int>& A) {\n        return maxTurbulenceSize_02(A);\n        return maxTurbulenceSize_01(A);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/longestValidParentheses/longestValidParentheses.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/longest-valid-parentheses/\n// Author : Hao Chen\n// Date   : 2014-07-18\n\n/********************************************************************************** \n* \n* Given a string containing just the characters '(' and ')', \n* find the length of the longest valid (well-formed) parentheses substring.\n* \n* For \"(()\", the longest valid parentheses substring is \"()\", which has length = 2.\n* \n* Another example is \")()())\", where the longest valid parentheses substring is \"()()\", \n* which has length = 4.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint longestValidParentheses(string s) {\n    int maxLen = 0;\n    int lastError = -1;\n    vector<int> stack;\n    for(int i=0; i<s.size(); i++){\n        if (s[i] == '('){\n            stack.push_back(i);\n        }else if (s[i] == ')') {\n            if (stack.size()>0 ){\n                stack.pop_back();\n                int len;\n                if (stack.size()==0){\n                    len = i - lastError;\n                } else {\n                    len = i - stack.back();\n                }\n                if (len > maxLen) {\n                    maxLen = len;\n                }\n            }else{\n                lastError = i;\n            }\n        }\n    }\n    return maxLen;\n}\n\n\nint main(int argc, char** argv)\n{\n    string s = \")()())\";\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << s << \" : \" << longestValidParentheses(s) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/lowestCommonAncestorOfABinarySearchTree/LowestCommonAncestorOfABinarySearchTree.cpp",
    "content": "// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given \n * nodes in the BST.\n * \n * According to the definition of LCA on Wikipedia: “The lowest common ancestor is \n * defined between two nodes v and w as the lowest node in T that has both v and w as \n * descendants (where we allow a node to be a descendant of itself).”\n * \n *         _______6______\n *        /              \\\n *     ___2__          ___8__\n *    /      \\        /      \\\n *    0      _4       7       9\n *          /  \\\n *          3   5\n * \n * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example \n * is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according \n * to the LCA definition.\n *               \n *               \n **********************************************************************************/\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n\n        while(root) {\n            if (p->val > root->val && q->val > root->val) {\n                root = root->right;\n                continue;\n            }\n            if (p->val < root->val && q->val < root->val) {\n                root = root->left;\n                continue;\n            }\n            return root;\n            \n        }\n        return NULL;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/lowestCommonAncestorOfABinaryTree/LowestCommonAncestorOfABinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the \n * tree.\n * \n * According to the definition of LCA on Wikipedia: “The lowest common ancestor is \n * defined between two nodes v and w as the lowest node in T that has both v and w as \n * descendants (where we allow a node to be a descendant of itself).”\n * \n *         _______3______\n *        /              \\\n *     ___5__          ___1__\n *    /      \\        /      \\\n *    6      _2       0       8\n *          /  \\\n *          7   4\n * \n * For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example \n * is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according \n * to the LCA definition.\n *               \n *               \n *               \n **********************************************************************************/\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool findPath(TreeNode* root, TreeNode* p, vector<TreeNode*>& path) {\n        if (root==NULL) return false;\n        if (root == p) {\n            path.push_back(p);\n            return true;\n        }\n        \n        path.push_back(root);\n        if (findPath(root->left, p, path)) return true;\n        if (findPath(root->right, p, path)) return true;\n        path.pop_back();\n        \n        return false;\n    }\n\n    //Ordinary way, find the path and comapre the path.\n    TreeNode* lowestCommonAncestor01(TreeNode* root, TreeNode* p, TreeNode* q) {\n        \n        vector<TreeNode*> path1, path2;\n        \n        if (!findPath(root, p, path1)) return NULL;\n        if (!findPath(root, q, path2)) return NULL;\n        \n        int len = path1.size() < path2.size() ? path1.size() : path2.size();\n        TreeNode* result = root;\n        for(int i=0; i<len; i++) {\n            if (path1[i] != path2[i]) {\n                return result;\n            }\n            result = path1[i];\n        }\n        return result;\n    }\n    \n    //Actually, we can do the recursive search in one time\n    TreeNode* lowestCommonAncestor02(TreeNode* root, TreeNode* p, TreeNode* q) {\n        \n        //return if found or not found, return NULL if not found\n        if (root==NULL || root == p || root == q) return root;\n        \n        //find the LCA in left tree\n        TreeNode* left = lowestCommonAncestor02(root->left, p, q);\n        //find the LCA in right tree\n        TreeNode* right = lowestCommonAncestor02(root->right, p, q);\n        \n        //left==NULL means both `p` and `q` are not found in left tree.\n        if (left==NULL) return right;\n        //right==NULL means both `p` and `q` are not found in right tree.\n        if (right==NULL) return left;\n        // left!=NULL && right !=NULL, which means `p` & `q` are seperated in left and right tree.\n        return root;\n    }\n    \n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        srand(time(0));\n        if (random()%2) {\n            return lowestCommonAncestor02(root, p, q);\n        }\n        return lowestCommonAncestor01(root, p, q);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/majorityElement/majorityElement.II.cpp",
    "content": "// Source : https://leetcode.com/problems/majority-element-ii/\n// Author : Hao Chen\n// Date   : 2015-07-03\n\n/********************************************************************************** \n * \n * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. \n * The algorithm should run in linear time and in O(1) space.\n * \n *   How many majority elements could it possibly have?\n *   Do you have a better hint? Suggest it!\n **********************************************************************************/\n\nclass Solution {\npublic:\n\n    //O(n) Space compexity\n    vector<int> majorityElement01(vector<int>& nums) {\n        vector<int> result;\n        unordered_map<int, int> counts;\n        int n = nums.size();\n        for(auto item : nums){\n            counts[item]++;\n            if (counts[item] > n/3 ){\n               result.push_back(item); \n               counts[item] = -n; // Tricky: make sure the item only can be put into result once.\n            } \n        }\n        return result;\n    }\n    //We know, there could be at most two numbers can be more than 1/3\n    //so, same as Majority Element I problem, we can have two counters.\n    vector<int> majorityElement02(vector<int>& nums) {\n        if(nums.size()<=1) return nums;\n        \n        //the same algorithm as Majority Element I problem\n        int majority1=0, majority2=0, cnt1=0, cnt2=0;\n        for(auto item: nums) {\n            if (cnt1 == 0 && majority2 != item ) {\n                majority1 = item;\n                cnt1 = 1;\n            } else if (majority1 == item) {\n                cnt1++;\n            } else if (cnt2 == 0) {\n                majority2 = item;\n                cnt2 = 1;\n            } else if (majority2 == item) {\n                cnt2++;\n            } else {\n                cnt1--;\n                cnt2--;\n            }\n        }\n        //re-check it again, in case there has less than two numbers of majority\n        cnt1 = cnt2 = 0;\n        for (auto item : nums) {\n            if (majority1 == item) cnt1++;\n            else if (majority2 == item) cnt2++;\n        }\n        vector<int> result;\n        if (cnt1 > nums.size()/3) result.push_back(majority1);\n        if (cnt2 > nums.size()/3) result.push_back(majority2);\n        return result;\n        \n    }\n    \n    vector<int> majorityElement(vector<int>& nums) {\n        return majorityElement02(nums);\n        return majorityElement01(nums);\n    }\n};\n\n\n"
  },
  {
    "path": "algorithms/cpp/majorityElement/majorityElement.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/majority-element/\n// Author : Hao Chen\n// Date   : 2014-12-25\n\n/********************************************************************************** \n * \n * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.\n * \n * You may assume that the array is non-empty and the majority element always exist in the array.\n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\nusing namespace std;\n\n\n// Moore Voting Algorithm\n// Refer to: \n// http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html\nint majorityElement(vector<int> &num) {\n    int majority;\n    int cnt = 0;\n    for(int i=0; i<num.size(); i++){\n        if ( cnt ==0 ){\n            majority = num[i];\n            cnt++;\n        }else{\n            majority == num[i] ? cnt++ : cnt --;\n            if (cnt > num.size()/2) return majority;\n        }\n    }\n    return majority;\n\n}\n\n\nvector<int> &split(const string &s, char delim, vector<int> &elems) {\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        elems.push_back(atoi(item.c_str()));\n    }\n    return elems;\n}\n\n\nvector<int> split(const string &s, char delim) {\n    vector<int> elems;\n    split(s, delim, elems);\n    return elems;\n}\n\n\nint main(int argc, char** argv)\n{\n    //string array = \"1,2,1,2,1,2,1,2,1,2,1\";\n    string array = \"2,2,1,1,1\";\n    if (argc > 1){\n        array = argv[1];\n    }\n\n    cout << \"[\" << array << \"]\" << endl;\n    vector<int> num = split(array, ',');\n    cout << majorityElement(num) <<endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/makeTheXorOfAllSegmentsEqualToZero/MakeTheXorOfAllSegmentsEqualToZero.cpp",
    "content": "// Source : https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/\n// Author : Hao Chen\n// Date   : 2021-03-20\n\n/***************************************************************************************************** \n *\n * You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left \n * <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] \n * XOR nums[left+1] XOR ... XOR nums[right].\n * \n * Return the minimum number of elements to change in the array such that the XOR of all segments of \n * size k​​​​​​ is equal to zero.\n * \n * Example 1:\n * \n * Input: nums = [1,2,0,3,0], k = 1\n * Output: 3\n * Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n * \n * Example 2:\n * \n * Input: nums = [3,4,5,2,1,7,3,4,7], k = 3\n * Output: 3\n * Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n * \n * Example 3:\n * \n * Input: nums = [1,2,4,1,2,5,1,2,6], k = 3\n * Output: 3\n * Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n * \n * Constraints:\n * \n * \t1 <= k <= nums.length <= 2000\n * \t​​​​​​0 <= nums[i] < 210\n ******************************************************************************************************/\n\n/*\n    First K length subarray: \n                            a1^a2^a3^.....^ak=0 ;\n\n    Second K length subarray :\n                            a2^a3^a4^....^ak+1=0 ; \n\n    On combining both : \n                            a1^(a2^a3^....^ak)^(a2^a3^....^ak)^a[k+1] =0 \n                            a1^a[k+1]=0\n    Therefore it is easy to see that for any i and j : \n\n                            a[i%k]^a[j%k] = 0 ;\n                        ->  a[i%k]=a[j%k] ;\n\n    Hence, a[1] = a[k+1] = a[2k+1] = ...\n           a[2] = a[k+2] = a[2k+2] = ...\n           a[3] = a[k+3] = a[2k+3] = ...\n           .\n           .\n           .\n           a[k] = a[2k] = a[3k] = ...\n\n    So we just need to obtain the first k length subarray and the rest would be determined by it.\n\n*/\n\n\nclass Solution {\npublic:\n    int minChanges(vector<int>& nums, int k) {\n        \n        const int max_value = 1024; //0 <= nums[i] < 2^10\n        int n = nums.size();\n        \n        //freq[i][v] means frequency of the number `v` at `i` position in [0, k-1];\n        vector<vector<int>> freq(k, vector<int>(max_value, 0));\n        for (int i=0; i<n; i++) {\n            freq[i%k][nums[i]]++;\n        }\n        \n        //dp[i][v] means minimum number of changes in first i elements such that the xor value is `v`\n        vector<vector<int>> dp(k, vector<int>(max_value, n+1));\n        \n        //initailization\n        int minChanges = n + 1;\n        for (int v = 0; v < max_value; v++) {\n            int cntOfPos = n / k + (((n % k) > 0) ? 1 : 0);\n            dp[0][v] = cntOfPos - freq[0][v];\n            minChanges = min(minChanges, dp[0][v]);\n        } \n        \n        for (int i=1; i<k; i++) {\n            // how many i indices exist in the array\n            int cntOfPos = n / k + (((n % k) > i) ? 1 : 0);\n\n            //track minimum changes\n            int m = n + 1;\n            \n            //for all of possible values\n            for (int v = 0; v < max_value; v++) {\n\n                for (int j = i; j < n; j += k) {\n                    int x = v ^ nums[j];\n                    dp[i][v] = min( dp[i][v], dp[i-1][x] + cntOfPos - freq[i][nums[j]]);\n                }\n                //for all of numbers don't occur at index i\n                dp[i][v] = min(dp[i][v], minChanges + cntOfPos);\n\n                m = min(m, dp[i][v]);\n            }\n            minChanges = m;\n        }   \n        return dp[k-1][0];\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/mapOfHighestPeak/MapOfHighestPeak.cpp",
    "content": "// Source : https://leetcode.com/problems/map-of-highest-peak/\n// Author : Hao Chen\n// Date   : 2021-03-26\n\n/***************************************************************************************************** \n *\n * You are given an integer matrix isWater of size m x n that represents a map of land and water cells.\n * \n * \tIf isWater[i][j] == 0, cell (i, j) is a land cell.\n * \tIf isWater[i][j] == 1, cell (i, j) is a water cell.\n * \n * You must assign each cell a height in a way that follows these rules:\n * \n * \tThe height of each cell must be non-negative.\n * \tIf the cell is a water cell, its height must be 0.\n * \tAny two adjacent cells must have an absolute height difference of at most 1. A cell is \n * adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., \n * their sides are touching).\n * \n * Find an assignment of heights such that the maximum height in the matrix is maximized.\n * \n * Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there \n * are multiple solutions, return any of them.\n * \n * Example 1:\n * \n * Input: isWater = [[0,1],[0,0]]\n * Output: [[1,0],[2,1]]\n * Explanation: The image shows the assigned heights of each cell.\n * The blue cell is the water cell, and the green cells are the land cells.\n * \n * Example 2:\n * \n * Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]\n * Output: [[1,1,0],[0,1,1],[1,2,2]]\n * Explanation: A height of 2 is the maximum possible height of any assignment.\n * Any height assignment that has a maximum height of 2 while still meeting the rules will also be \n * accepted.\n * \n * Constraints:\n * \n * \tm == isWater.length\n * \tn == isWater[i].length\n * \t1 <= m, n <= 1000\n * \tisWater[i][j] is 0 or 1.\n * \tThere is at least one water cell.\n ******************************************************************************************************/\n\nclass Cell{\npublic:\n    int x;\n    int y;\n    int height;\n};\n\nclass Solution {\nprivate:\n    void setHeight(vector<vector<int>>& height, \n                   queue<Cell>& q,\n                   int x, int y, int h, \n                   int m, int n) \n    {\n        if (x < 0 || y < 0 || x>=m || y>=n ) return;\n        if (height[x][y] == -1) {\n            height[x][y] = h;\n            q.push({x, y, h});\n        }\n    }\npublic:\n    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {\n        \n        int m = isWater.size();\n        int n = isWater[0].size();\n        \n        vector<vector<int>> height(m, vector(n, -1));\n        queue<Cell> q;\n        \n        for (int i=0; i<m; i++) {\n            for (int j=0; j<n; j++) {\n                if (isWater[i][j]) {\n                    height[i][j] = 0;\n                    q.push({i, j, 0});\n                }\n            }\n        }\n        \n        while(!q.empty()){\n            auto cell = q.front(); q.pop();\n            setHeight(height, q, cell.x-1, cell.y, cell.height+1,  m, n);\n            setHeight(height, q, cell.x+1, cell.y, cell.height+1,  m, n);\n            setHeight(height, q, cell.x, cell.y-1, cell.height+1,  m, n);\n            setHeight(height, q, cell.x, cell.y+1, cell.height+1,  m, n);\n        }\n        \n        return height;\n    }\n                        \n};\n"
  },
  {
    "path": "algorithms/cpp/matrixCellsInDistanceOrder/MatrixCellsInDistanceOrder.cpp",
    "content": "// Source : https://leetcode.com/problems/matrix-cells-in-distance-order/\n// Author : Hao Chen\n// Date   : 2019-04-21\n\n/***************************************************************************************************** \n *\n * We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 \n * <= r < R and 0 <= c < C.\n * \n * Additionally, we are given a cell in that matrix with coordinates (r0, c0).\n * \n * Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0) from \n * smallest distance to largest distance.  Here, the distance between two cells (r1, c1) and (r2, c2) \n * is the Manhattan distance, |r1 - r2| + |c1 - c2|.  (You may return the answer in any order that \n * satisfies this condition.)\n * \n * Example 1:\n * \n * Input: R = 1, C = 2, r0 = 0, c0 = 0\n * Output: [[0,0],[0,1]]\n * Explanation: The distances from (r0, c0) to other cells are: [0,1]\n * \n * Example 2:\n * \n * Input: R = 2, C = 2, r0 = 0, c0 = 1\n * Output: [[0,1],[0,0],[1,1],[1,0]]\n * Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2]\n * The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\n * \n * Example 3:\n * \n * Input: R = 2, C = 3, r0 = 1, c0 = 2\n * Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\n * Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3]\n * There are other answers that would also be accepted as correct, such as \n * [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].\n * \n * Note:\n * \n * \t1 <= R <= 100\n * \t1 <= C <= 100\n * \t0 <= r0 < R\n * \t0 <= c0 < C\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    void put(int R, int C, int r, int c, vector<vector<int>>& res) {\n        if (r>=0 && r < R && c>=0 && c<C ) {\n            res.push_back({r,c});\n        }\n    }\n    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {\n        int n =  R+C-2;\n        vector<vector<int>> result;\n        result.push_back({r0,c0});\n        for(int i=1; i<= n; i++) {\n            // from (r0-i, c0) to (r0, c0+i)\n            for(int r=r0-i,c=c0;r!=r0; r++, c++)  put (R, C, r ,c, result);\n\n            // from  (r0, c0+i) to (r0+i, c0)\n            for(int r=r0, c=c0+i; c!=c0; r++, c-- ) put (R, C, r, c, result);\n\n            // from (r0+i, c0) to (r0, c0-i)\n            for (int r=r0+i, c=c0; r!=r0; r--, c--) put (R, C, r, c, result);\n\n            // from (r0, c0-i) to (r0-i, c0)\n            for (int r=r0, c=c0-i; c!=c0; r--, c++) put (R, C, r, c, result);\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maxAreaOfIsland/MaxAreaOfIsland.cpp",
    "content": "// Source : https://leetcode.com/problems/max-area-of-island/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) \n * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are \n * surrounded by water.\n * \n * Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area \n * is 0.)\n * \n * Example 1:\n * \n * [[0,0,1,0,0,0,0,1,0,0,0,0,0],\n *  [0,0,0,0,0,0,0,1,1,1,0,0,0],\n *  [0,1,1,0,1,0,0,0,0,0,0,0,0],\n *  [0,1,0,0,1,1,0,0,1,0,1,0,0],\n *  [0,1,0,0,1,1,0,0,1,1,1,0,0],\n *  [0,0,0,0,0,0,0,0,0,0,1,0,0],\n *  [0,0,0,0,0,0,0,1,1,1,0,0,0],\n *  [0,0,0,0,0,0,0,1,1,0,0,0,0]]\n * \n * Given the above grid, return 6. Note the answer is not 11, because the island must be connected \n * 4-directionally.\n * \n * Example 2:\n * \n * [[0,0,0,0,0,0,0,0]]\n * Given the above grid, return 0.\n * \n * Note: The length of each dimension in the given grid does not exceed 50.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxAreaOfIsland(vector<vector<int>>& grid) {\n        int maxArea = 0;\n        for (int i=0; i<grid.size(); i++) {\n            for(int j=0; j<grid[0].size(); j++) {\n                if ( grid[i][j] == 1 ) {\n                    int area = 0;\n                    maxAreaOfIsland_DFS(grid, i, j, area);\n                    maxArea = max( maxArea, area );\n                }\n            }\n        }\n        return maxArea;\n    }\n\n    void maxAreaOfIsland_DFS( vector<vector<int>>& grid, int i, int j, int& area ) {\n        if (i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j] != 1 ) return;\n\n        area++;\n        grid[i][j] = -1;\n\n        maxAreaOfIsland_DFS(grid, i-1, j, area);\n        maxAreaOfIsland_DFS(grid, i+1, j, area);\n        maxAreaOfIsland_DFS(grid, i, j-1, area);\n        maxAreaOfIsland_DFS(grid, i, j+1, area);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maxPointsOnALine/maxPointsOnALine.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/max-points-on-a-line/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <map>\nusing namespace std;\n\nstruct Point {\n    int x;\n    int y;\n    Point() : x(0), y(0) {}\n    Point(int a, int b) : x(a), y(b) {}\n};\n\n// O(n^2) time complexity solution\nint maxPoints(vector<Point> &points) {\n\n    #define INT_MAX 2147483647\n    #define INT_MIN (-INT_MAX - 1)\n\n    if (points.size()<=0) return 0;\n    if (points.size()<=2) return points.size();\n    \n    int maxnum = 0;\n    //using a map to find the same slope line\n    map<double, int> slopeMap;\n\n    //The algorithm here is quite straight forward.\n    //   take each point in array to caculate with others\n    //\n    //Actually the algorithm here can be optimized.\n    //   there are many duplicated calculation. \n    //   considering two points A and B, (A,B) is same with (B,A), here re-calculated.\n    for(int i=0; i<points.size(); i++) {\n        //reset teh slope map.\n        slopeMap.clear();\n        slopeMap[INT_MIN] = 0;\n        int samePointCnt = 1;\n        for (int j=0; j<points.size(); j++) {\n            if (i==j) continue; //skip the same point\n            //Caculate the slope of two points\n            int delta_x = points[i].x - points[j].x;\n            int delta_y = points[i].y - points[j].y;\n            //Special case: two points are exactly at same place\n            if (delta_y == 0 && delta_x == 0){\n                samePointCnt++;\n                continue;\n            }\n            //Special case: delta_x == 0\n            double slope = INT_MAX;\n            if (delta_x!=0) {\n                slope = 1.0*delta_y / delta_x;\n            }\n            //Count the points is same line.\n            slopeMap[slope]++;\n        }\n        //find the max number of points located at same line with points[i]\n        map<double, int>::iterator it;\n        for (it = slopeMap.begin(); it != slopeMap.end(); it++) {\n            if (maxnum < it->second + samePointCnt) {\n                maxnum = it->second + samePointCnt;\n            }\n        }\n    }\n\n    return maxnum;\n}\n\nvoid generatePoints(vector<Point> &points, int n) {\n    srand(time(0));\n    Point p;\n    for(int i=0; i<n; i++) {\n        p.x = rand() % 1;\n        p.y = rand() % 1;\n        points.push_back(p);\n    }\n}\n\nvoid printPoints(vector<Point> &points) {\n    for(int i=0; i<points.size(); i++) {\n        cout << \"(\" << points[i].x << \",\" << points[i].y << \") \";\n    }\n    cout << endl;\n}\n\n\nint main(int argc, char** argv) \n{\n    int n = 20;\n    if ( argc > 1) {\n        n = atoi(argv[1]);\n    }\n    vector<Point> points;\n    generatePoints(points, n);\n    printPoints(points);\n    cout << maxPoints(points) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/maximalRectangle/maximalRectangle.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/maximal-rectangle/\n// Author : Hao Chen\n// Date   : 2014-07-21\n\n/********************************************************************************** \n* \n* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle \n* containing all ones and return its area.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n// The problem can be convert to the problem - \"Largest Rectangle in Histogram\"\n//   1) we can take each row to calculate each row's histogram.\n//   2) using the algorithm of \"Largest Rectangle in Histogram\" to find the largest area histogram.\n//   3) tracking the maximal area.\n//\n// For the 1), it's easy. \n//     heights[i][j] = 1,                     if (i==0)\n//     heights[i][j] = heights[i-1][j] + 1;,  if (i>0)\n//\n// For the 2), please referr to \"Largest Rectangle in Histogram\"\n// \n\nint largestRectangleArea(vector<int> &height) {\n\n    if (height.size()<=0) return 0;\n\n    height.push_back(0);\n    vector<int> stack;\n    int maxArea=0;\n\n    for(int i=0; i<height.size(); ){\n        if (stack.size()==0 || height[i] >= height[ stack.back() ] ){\n            stack.push_back(i);\n            i++;\n        }else{\n            int topIdx = stack.back();\n            stack.pop_back();\n            int area = height[topIdx] * ( stack.size()==0 ? i  : i - stack.back() - 1 );\n            if (area > maxArea){\n                maxArea = area;\n            }\n        }\n    }\n    return maxArea;\n}\n\nint maximalRectangle(vector<vector<char> > &matrix) {\n\n    if (matrix.size()<=0 || matrix[0].size()<=0) return 0;\n    int row = matrix.size();\n    int col = matrix[0].size();\n    vector< vector<int> > heights(row, vector<int>(col));\n\n    int maxArea = 0;\n    for(int i=0; i<row; i++){\n        for(int j=0; j<col; j++) {\n            if (matrix[i][j]=='1'){\n                heights[i][j] = (i==0 ? 1 : heights[i-1][j] + 1);\n            }\n        }\n        int area = largestRectangleArea(heights[i]);\n        if (area > maxArea){\n            maxArea = area;\n        }\n    }\n\n    return maxArea;\n\n}\n\nvoid printArray(vector<int> &v)\n{\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \"}\" << endl;\n}\n\nvoid test(int a[], int n)\n{\n    vector<int> v(a, a + n);\n    printArray(v);\n    cout << largestRectangleArea(v) << endl;\n}\n\nint main(int argc, char** argv)\n{\n    #define TEST(a) test(a, sizeof(a)/sizeof(int))\n\n    int a0[] = {2,1,3,1};\n    TEST(a0);\n    int a1[] = {2,1,5,6,2,3};\n    TEST(a1);\n\n\n\n    cout << \"------------------\" << endl; \n    srand(time(0));\n\n    int r = 3;\n    int c = 3;\n    if (argc>2){\n        r = atoi(argv[1]);\n        c = atoi(argv[2]);\n    }\n\n    vector< vector<char> > matrix;\n    for(int i=0; i<r; i++){\n        vector<char> v;\n        cout << \"[\";\n        for(int j=0; j<c; j++) {\n            char ch = random()%2+'0';\n            v.push_back(ch);\n            cout << \" \" << ch;\n        }\n        matrix.push_back(v);\n        cout << \" ]\" << endl;\n    }\n    cout << \"------------------\" << endl; \n    cout << \"maxArea = \" << maximalRectangle(matrix) << endl;\n\n    return 0;\n}\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/maximalSquare/MaximalSquare.cpp",
    "content": "// Source : https://leetcode.com/problems/maximal-square/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.\n * \n * For example, given the following matrix:\n * \n * 1 0 1 0 0\n * 1 0 1 1 1\n * 1 1 1 1 1\n * 1 0 0 1 0\n * \n * Return 4.\n * \n * Credits:Special thanks to @Freezen for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\n/*\n *  Dynamic Programming\n *\n *   1) P[0][j] = matrix[0][j] (topmost row);\n *   2) P[i][0] = matrix[i][0] (leftmost column);\n *   3) For i > 0 and j > 0: \n *       3.1) if matrix[i][j] = 0, P[i][j] = 0; \n *       3.2) if matrix[i][j] = 1, P[i][j] = min(P[i-1][j], P[i][j-1], P[i-1][j-1]) + 1.\n *\n *   The details of this algorithm has been well described here.\n *   https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space\n * \n *      \n *      Well, this problem desires for the use of dynamic programming. They key to any DP problem is to \n *      come up with the state equation. In this problem, we define the state to be the maximal size of\n *      the square that can be achieved at point (i, j), denoted as P[i][j]. Remember that we use size\n *      instead of square as the state (square = size^2).\n *      \n *      Now let's try to come up with the formula for P[i][j].\n *      \n *      First, it is obvious that for the topmost row (i = 0) and the leftmost column (j = 0), \n *      P[i][j] = matrix[i][j].  This is easily understood. Let's suppose that the topmost row \n *      of matrix is like [1, 0, 0, 1].  Then we can immediately know that the first and last point \n *      can be a square of size 1 while the two middle points cannot make any square, giving a size of 0. \n *      Thus, P = [1, 0, 0, 1], which is the same as matrix. The case is similar for the leftmost column. \n *      Till now, the boundary conditions of this DP problem are solved.\n *      \n *      Let's move to the more general case for P[i][j] in which i > 0 and j > 0. First of all, \n *      let's see another simple case in which matrix[i][j] = 0. It is obvious that P[i][j] = 0 too. \n *      Why? Well, since matrix[i][j] = 0, no square will contain matrix[i][j], according to our \n *      definition of P[i][j], P[i][j] is also 0.\n *      \n *      Now we are almost done. The only unsolved case is matrix[i][j] = 1. Let's see an example.\n *      \n *      Suppose matrix = [[0, 1], [1, 1]], it is obvious that P[0][0] = 0, P[0][1] = P[1][0] = 1, \n *      what about P[1][1]? Well, to give a square of size larger than 1 in P[1][1], all of its \n *      three neighbors (left, up, left-up) should be non-zero, right? In this case, the left-up \n *      neighbor P[0][0] = 0, so P[1][1] can only be 1, which means that it contains the square of itself.\n *      \n *      Now you are near the solution. In fact, P[i][j] = min(P[i-1][j], P[i][j-1], P[i-1][j-1]) + 1 in this case.\n *      \n *      \n */\n\nclass Solution {\npublic:\n    inline int min(int x, int y) {\n        return x<y? x:y;\n    }\n    inline int min(int x, int y, int z) {\n        return min(x, min(y, z));\n    }\n    int maximalSquare(vector<vector<char>>& matrix) {\n        int row = matrix.size();\n        if (row <=0) return 0;\n        int col = matrix[0].size();\n        \n        int maxSize = 0;\n        vector<vector<int>> dp(row, vector<int>(col));\n        \n        for (int i=0; i<matrix.size(); i++) {\n            for (int j=0; j<matrix[i].size(); j++){\n                //convert the `char` to `int`\n                dp[i][j] = matrix[i][j] -'0';\n                //for the first row and first column, or matrix[i][j], dp[i][j] is ZERO\n                //so, it's done during the previous conversion\n                \n                // i>0 && j>0 && matrix[i][j]=='1'\n                if (i!=0 && j!=0 & dp[i][j]!=0){\n                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;\n                }\n                \n                //tracking the maxSize\n                if (dp[i][j] > maxSize ){\n                    maxSize = dp[i][j];\n                }\n            }\n        }\n        \n        return maxSize*maxSize;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximizeNumberOfNiceDivisors/MaximizeNumberOfNiceDivisors.cpp",
    "content": "// Source : https://leetcode.com/problems/maximize-number-of-nice-divisors/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * You are given a positive integer primeFactors. You are asked to construct a positive integer n that \n * satisfies the following conditions:\n * \n *   The number of prime factors of n (not necessarily distinct) is at most primeFactors.\n *   The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is \n * divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], \n * then 6 and 12 are nice divisors, while 3 and 4 are not.\n * \n * Return the number of nice divisors of n. Since that number can be too large, return it modulo 10^9 \n * + 7.\n * \n * Note that a prime number is a natural number greater than 1 that is not a product of two smaller \n * natural numbers. The prime factors of a number n is a list of prime numbers such that their product \n * equals n.\n * \n * Example 1:\n * \n * Input: primeFactors = 5\n * Output: 6\n * Explanation: 200 is a valid value of n.\n * It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\n * There is not other value of n that has at most 5 prime factors and more nice divisors.\n * \n * Example 2:\n * \n * Input: primeFactors = 8\n * Output: 18\n * \n * Constraints:\n * \n * \t1 <= primeFactors <= 10^9\n ******************************************************************************************************/\n\n/*\n    considering `primeFactors = 5`\n    \n    So, we can have the following options:\n    1) [2,3,5,7,11] - all of factors are different, then we only can have 1 nice divisor\n    2) [2,2,3,5,7] - we can have 2*1*1*1 = 2 nice divisors: 2*3*5*7 and 2*2*3*5*7\n    3) [2,2,3,3,5] - we can have 2*2*1 = 4 nice divisors: 2*3*5， 2*2*3*5， 2*3*3*5， 2*2*3*3*5\n    4) [2,2,3,3,3] - we can have 2*3 = 6 nice divisors\n    5）[2,2,2,2,3] - we can have 4*1 =4 nice divisors: 2*3, 2*2*3, 2*2*2*3, 2*2*2*2*3\n    6) [2,2,2,2,2] - we can have 5 nice divisors: 2, 2*2, 2*2*2, 2*2*2*2, 2*2*2*2*2\n    \n    So, we can see we must have some duplicated factors.\n    \n    And what is the best number of duplication ?\n    primeFactors = 1, then 1        - example: [2]\n    primeFactors = 2, then 2        - example: [2,2]\n    primeFactors = 3, then 3        - example: [5,5,5]\n    primeFactors = 4, then 4 = 2*2  - example: [2,2,5,5])\n    primeFactors = 5, then 5 = 2*3  - example: [3,3,3,5,5])\n    primeFactors = 5, then 6 = 3*3  - example: [3,3,3,5,5,5])\n    primeFactors = 7, then 3*4 = 12 - example: [3,3,3,5,5,5,5])\n    primeFactors = 8, then 3*3*2 = 18  whcih > (2*2*2*2,  2*4*2, 3*5)\n    primeFactors = 9, then 3*3*3 = 27  \n    primeFactors = 10, then 3*3*4 = 36\n    \n    So, we can see the '3' & '4' are  specifial,\n    - most of case, we can be greedy for `3`\n    - but if the final rest is 4, then we need take 4.\n    \n */\n\nconst int mod = 1000000007;\n\nclass Solution {\npublic:\n    int maxNiceDivisors(int primeFactors) {\n        return maxNiceDivisors_03(primeFactors);\n        return maxNiceDivisors_02(primeFactors); //TLE\n        return maxNiceDivisors_01(primeFactors); //TLE\n    }\n    \n    int maxNiceDivisors_01(int primeFactors) {\n        int result = 1;\n        while ( primeFactors > 4 ) {\n            primeFactors -= 3;\n            result = (result * 3l) % mod;\n        }\n        result = (result * (long)primeFactors) % mod;\n        return result;\n    }\n    \n    int maxNiceDivisors_02(int primeFactors) {\n        if (primeFactors <= 4 ) return primeFactors;\n        int result = 1;\n        for (int i = 4; i > 0; i-- ){\n            if ((primeFactors - i) % 3 == 0){ \n                result = i;\n                primeFactors -= i;\n                // now, `primeFactors` is 3 times - 3X\n                // we need convert 3X to 3^X\n                for (int x = primeFactors/3; x > 0; x-- ) {\n                    result = (result * 3l) % mod;\n                }\n                break;\n            }\n        }\n        return result;\n    }\n    \n    int pow3(int x) {\n        long  result = 1;\n        long  factor = 3;\n        while(x > 0) {\n            if (x & 1) {\n                result = (result * factor) % mod;\n                \n            }\n            factor *= factor;\n            factor %= mod;\n            x /= 2;\n        }\n        return result % mod;\n    }\n    \n    int maxNiceDivisors_03(int primeFactors) {\n        \n        if (primeFactors <= 4 ) return primeFactors;\n        int result = 1;\n        for (int i = 4; i > 0; i-- ){\n            if ((primeFactors - i) % 3 == 0){ \n                primeFactors -= i;\n                // now, `primeFactors` is 3 times - 3X\n                // we need convert 3X to 3^X\n                int x = primeFactors / 3;\n                result = (long(i) * pow3(x)) % mod;\n                break;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximizePalindromeLengthFromSubsequences/MaximizePalindromeLengthFromSubsequences.cpp",
    "content": "// Source : https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * You are given two strings, word1 and word2. You want to construct a string in the following manner:\n * \n * \tChoose some non-empty subsequence subsequence1 from word1.\n * \tChoose some non-empty subsequence subsequence2 from word2.\n * \tConcatenate the subsequences: subsequence1 + subsequence2, to make the string.\n * \n * Return the length of the longest palindrome that can be constructed in the described manner. If no \n * palindromes can be constructed, return 0.\n * \n * A subsequence of a string s is a string that can be made by deleting some (possibly none) \n * characters from s without changing the order of the remaining characters.\n * \n * A palindrome is a string that reads the same forward as well as backward.\n * \n * Example 1:\n * \n * Input: word1 = \"cacb\", word2 = \"cbba\"\n * Output: 5\n * Explanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\n * \n * Example 2:\n * \n * Input: word1 = \"ab\", word2 = \"ab\"\n * Output: 3\n * Explanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\n * \n * Example 3:\n * \n * Input: word1 = \"aa\", word2 = \"bb\"\n * Output: 0\n * Explanation: You cannot construct a palindrome from the described method, so return 0.\n * \n * Constraints:\n * \n * \t1 <= word1.length, word2.length <= 1000\n * \tword1 and word2 consist of lowercase English letters.\n ******************************************************************************************************/\n\n/*\n    // The basic algorthim come from\n    // https://leetcode.com/problems/longest-palindromic-subsequence/\n    \n    int longestPalindromeSubseq(string& s) {\n        int n = s.size(); \n        vector<vector<int>> dp(n, vector<int>(n, 0));\n\n        for (int start = n-1; start>=0; start--) {\n            for (int end = start ; end < n ; end++) {\n                if (start == end) {\n                    dp[start][end] = 1;\n                    continue;\n                }\n                if (s[start] == s[end]) {\n                    dp[start][end] = dp[start+1][end-1] + 2;\n                }else{\n                     dp[start][end] = max (dp[start+1][end], dp[start][end-1]);\n                }\n\n            }\n        }\n        return dp[0][n-1];\n    }\n*/\n\n\nclass Solution {\n\npublic:\n    int longestPalindrome(string word1, string word2) {\n        \n        string s = word1 + word2;\n        int n = s.size(); \n        vector<vector<int>> dp(n, vector<int>(n, 0));\n        \n        int result = 0; \n        for (int start = n-1; start>=0; start--) {\n            for (int end = start ; end < n ; end++) {\n                if (start == end) {\n                    dp[start][end] = 1;\n                    continue;\n                }\n                if (s[start] == s[end]) {\n                    dp[start][end] = dp[start+1][end-1] + 2;\n                    // <-----------  different -----------> \n                    //only consider when `start` and `end` in different string.\n                    if (start < word1.size() && end >= word1.size()){\n                        result = max(result, dp[start][end]);\n                    }\n                    // <-----------  different -----------> \n                }else{\n                     dp[start][end] = max (dp[start+1][end], dp[start][end-1]);\n                }\n                \n            }\n        }  \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximizeScoreAfterNOperations/MaximizeScoreAfterNOperations.cpp",
    "content": "// Source : https://leetcode.com/problems/maximize-score-after-n-operations/submissions/\n// Author : Hao Chen\n// Date   : 2021-03-23\n\n/***************************************************************************************************** \n *\n * You are given nums, an array of positive integers of size 2 * n. You must perform n operations on \n * this array.\n * \n * In the i^th operation (1-indexed), you will:\n * \n * \tChoose two elements, x and y.\n * \tReceive a score of i * gcd(x, y).\n * \tRemove x and y from nums.\n * \n * Return the maximum score you can receive after performing n operations.\n * \n * The function gcd(x, y) is the greatest common divisor of x and y.\n * \n * Example 1:\n * \n * Input: nums = [1,2]\n * Output: 1\n * Explanation: The optimal choice of operations is:\n * (1 * gcd(1, 2)) = 1\n * \n * Example 2:\n * \n * Input: nums = [3,4,6,8]\n * Output: 11\n * Explanation: The optimal choice of operations is:\n * (1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n * \n * Example 3:\n * \n * Input: nums = [1,2,3,4,5,6]\n * Output: 14\n * Explanation: The optimal choice of operations is:\n * (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n * \n * Constraints:\n * \n * \t1 <= n <= 7\n * \tnums.length == 2 * n\n * \t1 <= nums[i] <= 10^6\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    // Euclidean algorithm\n    // https://en.wikipedia.org/wiki/Euclidean_algorithm\n    int gcd(int a, int b) {\n        while(a != b) {\n            if(a > b) a = a - b;\n            else b = b - a;\n        }\n        return a;\n    }\n    unordered_map<int, int> cache;\npublic:\n    int maxScore(vector<int>& nums) {\n        int n = nums.size();\n        \n        vector<vector<int>> pair_gcd(n, vector<int>(n, 0) );\n        \n        for (int i=0; i< n - 1; i++) {\n            for (int j=i+1; j < n; j++ ) {\n                pair_gcd[i][j] = gcd(nums[i], nums[j]);\n            }\n        }\n        \n        // used_mark[] - remember the num has been used.\n        return maxScore(pair_gcd, 0, n, n/2);\n    }\n    \n    int maxScore(vector<vector<int>>& pair_gcd, int mask, int n, int step) {\n        if (cache.find(mask) != cache.end()) {\n            return cache[mask];\n        }\n        int m = 0;\n        \n        for (int i=0; i< n - 1; i++) {\n            if ( (1<<i) & mask ) continue;\n            for (int j=i+1; j < n; j++ ) {\n                if ((1<<j) & mask) continue;\n                if (step == 1) {\n                    return pair_gcd[i][j];\n                }\n                \n                m = max(m, step * pair_gcd[i][j] + \n                        maxScore(pair_gcd, mask | (1<<i) | (1<<j), n, step-1));\n                \n            }\n        }\n        \n        cache[mask] = m;\n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumAbsoluteSumOfAnySubarray/MaximumAbsoluteSumOfAnySubarray.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/\n// Author : Hao Chen\n// Date   : 2021-02-12\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, \n * numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).\n * \n * Return the maximum absolute sum of any (possibly empty) subarray of nums.\n * \n * Note that abs(x) is defined as follows:\n * \n * \tIf x is a negative integer, then abs(x) = -x.\n * \tIf x is a non-negative integer, then abs(x) = x.\n * \n * Example 1:\n * \n * Input: nums = [1,-3,2,3,-4]\n * Output: 5\n * Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\n * \n * Example 2:\n * \n * Input: nums = [2,-5,1,-4,3,-2]\n * Output: 8\n * Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 105\n * \t-104 <= nums[i] <= 104\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxAbsoluteSum(vector<int>& nums) {\n        return maxAbsoluteSum02(nums); //56ms\n        return maxAbsoluteSum01(nums); //56ms\n    }\n    \n    \n    \n    int maxAbsoluteSum01(vector<int>& nums) {\n        return std::max(maxSumArray(nums), std::abs(minSumArray(nums)) );\n    }\n    \n    //https://en.wikipedia.org/wiki/Maximum_subarray_problem\n    int maxSumArray(vector<int>& nums) {\n        int max = nums[0];\n        int sum = nums[0];\n        for (int i = 1; i < nums.size(); i++) {\n            if (sum < 0 ) sum = nums[i];\n            else sum += nums[i];\n            if (max < sum) max = sum;\n        }\n        return max;\n    }\n    \n    int minSumArray(vector<int>& nums) {\n        int min = nums[0];\n        int sum = nums[0];\n        for (int i = 1; i < nums.size(); i++) {\n            if (sum > 0 ) sum = nums[i];\n            else sum += nums[i];\n            if (min > sum) min = sum;\n        }\n        return min;\n    }\n    \n    // Becasue maxSumArray() & minSumArray() are two similar,\n    // we can merge them together to save one loop\n    int maxAbsoluteSum02(vector<int>& nums) {\n        int max = nums[0];\n        int max_sum = nums[0];\n        \n        int min = nums[0];\n        int min_sum = nums[0];\n        \n        for (int i = 1; i < nums.size(); i++) {\n            \n            if (max_sum < 0 ) max_sum = nums[i];\n            else max_sum += nums[i];\n            if (max < max_sum) max = max_sum;\n            \n            \n            if (min_sum > 0 ) min_sum = nums[i];\n            else min_sum += nums[i];\n            if (min > min_sum) min = min_sum;\n            \n        }\n        \n        return std::max(max, abs(min));\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/maximumAscendingSubarraySum/MaximumAscendingSubarraySum.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-ascending-subarray-sum/\n// Author : Hao Chen\n// Date   : 2021-03-21\n\n/***************************************************************************************************** \n *\n * Given an array of positive integers nums, return the maximum possible sum of an ascending subarray \n * in nums.\n * \n * A subarray is defined as a contiguous sequence of numbers in an array.\n * \n * A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi  \n * < numsi+1. Note that a subarray of size 1 is ascending.\n * \n * Example 1:\n * \n * Input: nums = [10,20,30,5,10,50]\n * Output: 65\n * Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n * \n * Example 2:\n * \n * Input: nums = [10,20,30,40,50]\n * Output: 150\n * Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n * \n * Example 3:\n * \n * Input: nums = [12,17,15,13,10,11,12]\n * Output: 33\n * Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n * \n * Example 4:\n * \n * Input: nums = [100,10,1]\n * Output: 100\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 100\n * \t1 <= nums[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxAscendingSum(vector<int>& nums) {\n        int maxSum = nums[0];\n        int sum = maxSum;\n        for(int i=1; i<nums.size(); i++) {\n            if (nums[i] > nums[i-1]) {\n                sum += nums[i];\n            }else{\n                maxSum = maxSum < sum ? sum : maxSum;\n                sum = nums[i];\n            }\n        }\n        maxSum = maxSum < sum ? sum : maxSum;\n        return maxSum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumAveragePassRatio/MaximumAveragePassRatio.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-average-pass-ratio/\n// Author : Hao Chen\n// Date   : 2021-03-19\n\n/***************************************************************************************************** \n *\n * There is a school that has classes of students and each class will be having a final exam. You are \n * given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in \n * the ith class, there are totali total students, but only passi number of students will pass the \n * exam.\n * \n * You are also given an integer extraStudents. There are another extraStudents brilliant students \n * that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of \n * the extraStudents students to a class in a way that maximizes the average pass ratio across all the \n * classes.\n * \n * The pass ratio of a class is equal to the number of students of the class that will pass the exam \n * divided by the total number of students of the class. The average pass ratio is the sum of pass \n * ratios of all the classes divided by the number of the classes.\n * \n * Return the maximum possible average pass ratio after assigning the extraStudents students. Answers \n * within 10-5 of the actual answer will be accepted.\n * \n * Example 1:\n * \n * Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2\n * Output: 0.78333\n * Explanation: You can assign the two extra students to the first class. The average pass ratio will \n * be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\n * \n * Example 2:\n * \n * Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4\n * Output: 0.53485\n * \n * Constraints:\n * \n * \t1 <= classes.length <= 105\n * \tclasses[i].length == 2\n * \t1 <= passi <= totali <= 105\n * \t1 <= extraStudents <= 105\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    template<typename T>\n    void print_queue(T q) { // NB: pass by value so the print uses a copy\n        while(!q.empty()) {\n            auto [profit, c] = q.top();\n            auto [pass, total] = c;\n            cout <<  \"[\" << profit << \" - \" << pass << \", \" << total <<\"], \";\n            q.pop();\n        }\n        cout << '\\n';\n    }\n\n    //calculating ratio\n    double ratio(double pass, double total) {\n        return pass / total;\n    }\n    //calculating the profit\n    double profit(double pass, double total) {\n        return ratio(pass + 1, total + 1)  - ratio(pass, total);\n    }\n\npublic:\n    double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {\n        \n        priority_queue<pair<double, pair<int,int>> > q;\n        \n        double total_ratio = 0;\n        int cnt = 0;\n        for (auto& c : classes) {\n            total_ratio += ratio(c[0], c[1]);\n            q.push({profit(c[0], c[1]), {c[0],c[1]}});\n        }\n        //print_queue(q);\n        \n        while(extraStudents--){\n            auto [added_profit, c] = q.top();\n            auto [pass, total] = c;\n            q.pop();\n            \n            total_ratio += added_profit;\n            pass++; total++;\n            q.push({profit(pass, total), {pass, total}});\n        }\n        //print_queue(q);\n        \n        return total_ratio / classes.size();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-average-subarray-i/description/\n// Author : Hao Chen\n// Date   : 2018-04-19\n\n/*************************************************************************************** \n *\n * \n * Given an array consisting of n integers, find the contiguous subarray of given \n * length k that has the maximum average value. And you need to output the maximum \n * average value.\n * \n * \n * Example 1:\n * \n * Input: [1,12,-5,-6,50,3], k = 4\n * Output: 12.75\n * Explanation: aximum average is (12-5-6+50)/4 = 51/4 = 12.75\n * \n * \n * \n * Note:\n * \n * 1 k n \n * Elements of the given array will be in the range [-10,000, 10,000].\n * \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    double findMaxAverage(vector<int>& nums, int k) {\n        int sum=0;\n        for(int i=0; i<k; i++ ) {\n            sum += nums[i];\n        }\n        \n        int s = sum;\n        for (int i=k; i< nums.size(); i++) {\n            s += nums[i];\n            s -= nums[i-k];\n            \n            if (s > sum) {\n                sum = s;\n            }\n        }\n        return (double)sum/k;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/maximumBuildingHeight/MaximumBuildingHeight.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-building-height/\n// Author : Hao Chen\n// Date   : 2021-04-25\n\n/***************************************************************************************************** \n *\n * You want to build n new buildings in a city. The new buildings will be built in a line and are \n * labeled from 1 to n.\n * \n * However, there are city restrictions on the heights of the new buildings:\n * \n * \tThe height of each building must be a non-negative integer.\n * \tThe height of the first building must be 0.\n * \tThe height difference between any two adjacent buildings cannot exceed 1.\n * \n * Additionally, there are city restrictions on the maximum height of specific buildings. These \n * restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] \n * indicates that building idi must have a height less than or equal to maxHeighti.\n * \n * It is guaranteed that each building will appear at most once in restrictions, and building 1 will \n * not be in restrictions.\n * \n * Return the maximum possible height of the tallest building.\n * \n * Example 1:\n * \n * Input: n = 5, restrictions = [[2,1],[4,1]]\n * Output: 2\n * Explanation: The green area in the image indicates the maximum allowed height for each building.\n * We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\n * \n * Example 2:\n * \n * Input: n = 6, restrictions = []\n * Output: 5\n * Explanation: The green area in the image indicates the maximum allowed height for each building.\n * We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\n * \n * Example 3:\n * \n * Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\n * Output: 5\n * Explanation: The green area in the image indicates the maximum allowed height for each building.\n * We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a \n * height of 5.\n * \n * Constraints:\n * \n * \t2 <= n <= 10^9\n * \t0 <= restrictions.length <= min(n - 1, 10^5)\n * \t2 <= idi <= n\n * \tidi is unique.\n * \t0 <= maxHeighti <= 10^9\n ******************************************************************************************************/\n\n/* \n\nAt first , it's not difficult to work out the max height between two buildings.\n\n**Case study**\n\nconsidering the following restractions:\n\n1) Building #1 `max-height = 1`, Building #5 `max-height = 1`\n     then we can have the building height list - `[1,2,3,2,1] `\n\n2) Building #1 `max-height = 3`, Building #5 `max-height = 1`\n     then we can have the building height list - `[3,4,3,2,1]` \n\n3) Building #1 `max-height = 1`, Building #5 `max-height = 9`\n     then we can have the building height list - `[1,2,3,4,5]`\n\nSo, we can figure out the following rules :\n\n1) if two restraction has same limited height, suppose we have `[n .........  n]`, \n     then we can have the building height list   `[n, n+1, n+2, ... n+m-1, n+m, n+m-1 ..., n+2, n+1, n]`\n\t \n\t So, **`m = width /2`**  - the `width` is the  number of buildings. \n\t \n2) if two restraction has different limited height, suppose we have `[n ...... n+x]`\n    then we still can have the building height list like 1) - we just add some buildings behind `[n .... n+x, (n+x-1... n) ]`\n\t\n\tSo, **`m = (width+x)/2`** - we need to extend x buildings\n\n3) if there hasn't enough buildings between two restractions. then,  the max height we can make is **`width`**.  For examples:\n    - Building#1 max-height  = 2,  building#3 max-height = 5 : then, we only can make `[2,3,4]`\n    - Building#1 max-height  = 2,  building#2 max-height = 9 : then, we only can make `[2,3]`\n\nSo, we can have the following source code to calculate the max height between two restractions.\n\n```\n    int getMaxHeight(vector<int>& left, vector<int>& right) {\n        \n        int width = right[0] - left[0];\n        int height_delta = abs(right[1] - left[1]);\n        int min_height = min (left[1], right[1]);\n        \n        //if the `width` is enough to have `height_delta`\n        if (width >= height_delta) return min_height + (width + height_delta) / 2;\n        \n        // if the `width` is not enought have `height_delta`\n        // then, the `width` is the max height we can make\n        int max_height =  min_height + width;\n        \n        return max_height;\n    }\n```\n\nBUT, we still have a case need to deal with, considering we have the following restractions:\n\n`[1,1], [2,2] ,[3,3], [4,0]`\n\nwe can process them couple by couple.\n\n- step 1: `[1,1], [2,2]` : max-height = 2\n- step 2: `[2,2] ,[3,3]` : max-height = 3\n- step 3: `[3,3], [4,0]` : max-height = 1\n\nfor the last couple of restractions, we can see the building#3 max-height is 1, so we have go backwards to recaluate the building#2 and building#1.\n\n- step 3: `[3,1], [4,0]` : max-height = 1  (change the `[3,3]` to `[3,1]` )\n- step:4: `[2,2] ,[3,1]` : max-height = 2\n- step 5: `[1,1], [2,2]` : max-height = 2\n\nSo, the correct answer of max height is `2`\n\nfinally, we have the whole source code with debug code inside.\n*/\n\nclass Solution {\nprivate:\n    void print(vector<vector<int>>& vv){\n        cout << \"[\" ;\n        for(int i = 0; i < vv.size()-1; i++) {\n            cout << \"[\" <<vv[i][0] << \",\" << vv[i][1] << \"],\";\n        }\n        int i = vv.size()  - 1;\n        cout << \"[\" << vv[i][0] << \",\" << vv[i][1] << \"]]\" << endl;\n    }\n\npublic:\n    int getMaxHeight(vector<int>& left, vector<int>& right) {\n\n        int width = right[0] - left[0];\n        int height_delta = abs(right[1] - left[1]);\n        int min_height = min (left[1], right[1]);\n\n        //if the `width` is enough to have `height_delta`\n        if (width >= height_delta) return min_height + (width + height_delta) / 2;\n\n        // if the `width` is not enought have `height_delta`\n        // then, the `width` is the max height we can make\n        int max_height =  min_height + width;\n\n        // if the restriction is higher then make it to right limitation.\n        left[1] = min (left[1], max_height);\n        right[1] = min (right[1], max_height);\n\n        return max_height;\n    }\n\n    int maxBuilding(int n, vector<vector<int>>& restrictions) {\n        restrictions.push_back({1,0});\n        restrictions.push_back({n, n-1});\n        sort(restrictions.begin(), restrictions.end());\n\n        //print(restrictions);\n\n        for(int i=0; i<restrictions.size()-1; i++){\n            int height = getMaxHeight(restrictions[i], restrictions[i+1]);\n            //cout << \"[\" << restrictions[i][0] << \",\" << restrictions[i][1]<< \"] - \"\n            //     << \"[\" << restrictions[i+1][0] << \",\" << restrictions[i+1][1]<< \"] = \"\n            //     << height << endl;\n        }\n        cout << endl;\n        int maxHeight = 0;\n        for(int i= restrictions.size()-1; i>0; i--){\n            int height = getMaxHeight(restrictions[i-1], restrictions[i]);\n            //cout << \"[\" << restrictions[i-1][0] << \",\" << restrictions[i-1][1]<< \"] - \"\n            //     << \"[\" << restrictions[i][0] << \",\" << restrictions[i][1]<< \"] = \"\n            //     << height << endl;\n            maxHeight = max(maxHeight, height);\n\n        }\n        // cout << endl;\n        return maxHeight;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a binary tree, find its maximum depth.\n* \n* The maximum depth is the number of nodes along the longest path from the root node \n* down to the farthest leaf node.\n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int maxDepth(TreeNode *root) {\n        if (root==NULL){\n            return 0;\n        }\n        if (!root->left && !root->right){\n            return 1;\n        }\n        int left=1, right=1;\n        if (root->left){\n            left += maxDepth(root->left);\n        }\n        if (root->right){\n            right += maxDepth(root->right);\n        }\n        return left>right?left:right;\n    }\n    \n};\n\nclass Solution2 {\npublic:\n    int maxDepth(TreeNode *root) {\n        if (root==NULL) return 0;\n        return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumDistanceBetweenAPairOfValues/MaximumDistanceBetweenAPairOfValues.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/\n// Author : Hao Chen\n// Date   : 2021-05-09\n\n/***************************************************************************************************** \n *\n * You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​.\n * \n * A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i \n * <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​.\n * \n * Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\n * \n * An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.\n * \n * Example 1:\n * \n * Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\n * Output: 2\n * Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\n * The maximum distance is 2 with pair (2,4).\n * \n * Example 2:\n * \n * Input: nums1 = [2,2,2], nums2 = [10,10,1]\n * Output: 1\n * Explanation: The valid pairs are (0,0), (0,1), and (1,1).\n * The maximum distance is 1 with pair (0,1).\n * \n * Example 3:\n * \n * Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\n * Output: 2\n * Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\n * The maximum distance is 2 with pair (2,4).\n * \n * Example 4:\n * \n * Input: nums1 = [5,4], nums2 = [3,2]\n * Output: 0\n * Explanation: There are no valid pairs, so return 0.\n * \n * Constraints:\n * \n * \t1 <= nums1.length <= 10^5\n * \t1 <= nums2.length <= 10^5\n * \t1 <= nums1[i], nums2[j] <= 10^5\n * \tBoth nums1 and nums2 are non-increasing.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxDistance(vector<int>& nums1, vector<int>& nums2) {\n        return maxDistance2(nums1, nums2);\n        return maxDistance1(nums1, nums2);\n    }\n    \n    \n    int binary_search(vector<int>& nums, int start, int target) {\n        int end = nums.size() - 1;\n        while (start <= end) {\n            int mid = start + (end - start) /2;\n            if(nums[mid] < target) end = mid - 1;\n            else start = mid+1;\n        }\n        return end;\n    }\n\n    int maxDistance1(vector<int>& nums1, vector<int>& nums2) {\n        int mDist=0;\n        int right = nums2.size() - 1;\n        for(int i=0; i<nums1.size(); i++) {\n            int j = binary_search(nums2, i, nums1[i]);\n            mDist = max(mDist, j-i);\n        }\n        return mDist;\n    }\n    \n    int maxDistance2(vector<int>& nums1, vector<int>& nums2) {\n        int i=0, j=0, dist = 0;\n        while (i < nums1.size() && j < nums2.size() ){\n            if ( nums1[i] > nums2[j] ) i++;\n            else dist = max(dist, j++ - i);\n        }\n        return dist;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumElementAfterDecreasingAndRearranging/MaximumElementAfterDecreasingAndRearranging.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * You are given an array of positive integers arr. Perform some operations (possibly none) on arr so \n * that it satisfies these conditions:\n * \n * \tThe value of the first element in arr must be 1.\n * \tThe absolute difference between any 2 adjacent elements must be less than or equal to 1. In \n * other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) \n * is the absolute value of x.\n * \n * There are 2 types of operations that you can perform any number of times:\n * \n * \tDecrease the value of any element of arr to a smaller positive integer.\n * \tRearrange the elements of arr to be in any order.\n * \n * Return the maximum possible value of an element in arr after performing the operations to satisfy \n * the conditions.\n * \n * Example 1:\n * \n * Input: arr = [2,2,1,2,1]\n * Output: 2\n * Explanation: \n * We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].\n * The largest element in arr is 2.\n * \n * Example 2:\n * \n * Input: arr = [100,1,1000]\n * Output: 3\n * Explanation: \n * One possible way to satisfy the conditions is by doing the following:\n * 1. Rearrange arr so it becomes [1,100,1000].\n * 2. Decrease the value of the second element to 2.\n * 3. Decrease the value of the third element to 3.\n * Now arr = [1,2,3], which satisfies the conditions.\n * The largest element in arr is 3.\n * \n * Example 3:\n * \n * Input: arr = [1,2,3,4,5]\n * Output: 5\n * Explanation: The array already satisfies the conditions, and the largest element is 5.\n * \n * Constraints:\n * \n * \t1 <= arr.length <= 10^5\n * \t1 <= arr[i] <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n        sort(arr.begin(), arr.end());\n        int m = arr[0] = 1;\n        for(int i=0; i<arr.size()-1; i++) {\n            if (abs(arr[i] - arr[i+1]) <= 1) {\n                m = max(arr[i], arr[i+1]);\n                continue;\n            }\n            arr[i+1] = arr[i] + 1;\n            m = arr[i+1];\n        }\n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumErasureValue/MaximumErasureValue.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-erasure-value/\n// Author : Hao Chen\n// Date   : 2021-05-07\n\n/***************************************************************************************************** \n *\n * You are given an array of positive integers nums and want to erase a subarray containing unique \n * elements. The score you get by erasing the subarray is equal to the sum of its elements.\n * \n * Return the maximum score you can get by erasing exactly one subarray.\n * \n * An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if \n * it is equal to a[l],a[l+1],...,a[r] for some (l,r).\n * \n * Example 1:\n * \n * Input: nums = [4,2,4,5,6]\n * Output: 17\n * Explanation: The optimal subarray here is [2,4,5,6].\n * \n * Example 2:\n * \n * Input: nums = [5,2,1,2,5,2,1,2,5]\n * Output: 8\n * Explanation: The optimal subarray here is [5,2,1] or [1,2,5].\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t1 <= nums[i] <= 10^4\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maximumUniqueSubarray(vector<int>& nums) {\n        //unordered_map<int, int> pos;\n        const int NIL = -1;\n        int pos[10001];\n        memset(pos, NIL, sizeof(pos));\n        \n        int start=0;\n        int max_sum =0, sum = 0;\n \n        for(int i = 0; i < nums.size(); i++) {\n            int n = nums[i];\n            // if find duplicated number\n            if ( pos[n] != NIL) {\n                max_sum = max(max_sum, sum);\n                //remove the previous numbers until to duplicatied position \n                for(;start <= pos[n]; start++){\n                    sum -= nums[start];\n                    pos[nums[start]] = NIL;\n                }\n            }\n            sum += n;\n            pos[n] = i;\n        }\n        max_sum = max( max_sum , sum );\n        return max_sum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumGap/maximumGap.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/maximum-gap/\n// Author : Hao Chen\n// Date   : 2014-12-17\n\n/********************************************************************************** \n * \n * Given an unsorted array, find the maximum difference between the successive elements in its sorted form.\n * \n * Try to solve it in linear time/space.\n * \n * Return 0 if the array contains less than 2 elements.\n * \n * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.\n * \n * Credits:Special thanks to @porker2008 for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nint maximumGap(vector<int> &num) {\n\n    if (num.size() < 2) return 0;\n\n    //find the max & min element\n    int min=num[0], max=num[0];\n    for(int i=1; i<num.size(); i++){\n        min = min > num[i] ? num[i] : min;\n        max = max < num[i] ? num[i] : max;\n    }\n\n    //Divide the interval [min, max] into n \"buckets\" of equal size = (max -min)/n\n    int bucket_size = (max - min)/num.size() + 1;\n\n    //For each of the remaining n-2 numbers, determin in which bucket it falls .\n    //The number num[i] belongs to the kth bucket B[k] if and only if (num[i]-min)/m = k-1\n\n    vector< vector<int> > buckets ( (max-min)/bucket_size + 1);\n    //For each bucket B[k], compute its max & min among the numbers which falls in B[k].\n    //if the bucket is empty, remain it nothing.\n    //if the bucket has one number, make this number as both max & min \n    for(int i=0; i<num.size(); i++){\n        int idx = (num[i] - min) / bucket_size ;\n        if (buckets[idx].empty()){\n            buckets[idx].push_back(num[i]);\n            buckets[idx].push_back(num[i]);\n        }else{\n            buckets[idx][0] = buckets[idx][0] > num[i] ? num[i] : buckets[idx][0];\n            buckets[idx][1] = buckets[idx][1] < num[i] ? num[i] : buckets[idx][1];\n        }\n    }\n\n    //calculate the max gap\n    int maxGap = 0;\n    int prev = 0;\n    for (int i = 1; i < buckets.size(); i++) {\n        if (buckets[i].empty()) continue;\n        int gap = buckets[i][0] - buckets[prev][1];\n        maxGap = maxGap > gap ? maxGap : gap;\n        prev = i;\n    }\n    return maxGap;\n}\n\nint main()\n{\n    //int a[] = {3, 6, 19, 1};\n    int a[] = {1,1,1,1,1,5,5,5,5,5};\n    vector<int> num(a, a+sizeof(a)/sizeof(a[0]));\n    cout << maximumGap(num) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/maximumIceCreamBars/MaximumIceCreamBars.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-ice-cream-bars/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * It is a sweltering summer day, and a boy wants to buy some ice cream bars.\n * \n * At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] \n * is the price of the i^th ice cream bar in coins. The boy initially has coins coins to spend, and he \n * wants to buy as many ice cream bars as possible. \n * \n * Return the maximum number of ice cream bars the boy can buy with coins coins.\n * \n * Note: The boy can buy the ice cream bars in any order.\n * \n * Example 1:\n * \n * Input: costs = [1,3,2,4,1], coins = 7\n * Output: 4\n * Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = \n * 7.\n * \n * Example 2:\n * \n * Input: costs = [10,6,8,7,7,8], coins = 5\n * Output: 0\n * Explanation: The boy cannot afford any of the ice cream bars.\n * \n * Example 3:\n * \n * Input: costs = [1,6,3,1,2,5], coins = 20\n * Output: 6\n * Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n * \n * Constraints:\n * \n * \tcosts.length == n\n * \t1 <= n <= 10^5\n * \t1 <= costs[i] <= 10^5\n * \t1 <= coins <= 10^8\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxIceCream(vector<int>& costs, int coins) {\n        sort(costs.begin(), costs.end());\n        int cnt = 0;\n        for(int i=0; i<costs.size() && costs[i] <= coins; i++) {\n            cnt++;\n            coins -= costs[i];\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfBallsInABox/MaximumNumberOfBallsInABox.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-balls-in-a-box/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit \n * inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to \n * infinity.\n * \n * Your job at this factory is to put each ball in the box with a number equal to the sum of digits of \n * the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and \n * the ball number 10 will be put in the box number 1 + 0 = 1.\n * \n * Given two integers lowLimit and highLimit, return the number of balls in the box with the most \n * balls.\n * \n * Example 1:\n * \n * Input: lowLimit = 1, highLimit = 10\n * Output: 2\n * Explanation:\n * Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...\n * Ball Count:  2 1 1 1 1 1 1 1 1 0  0  ...\n * Box 1 has the most number of balls with 2 balls.\n * \n * Example 2:\n * \n * Input: lowLimit = 5, highLimit = 15\n * Output: 2\n * Explanation:\n * Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...\n * Ball Count:  1 1 1 1 2 2 1 1 1 0  0  ...\n * Boxes 5 and 6 have the most number of balls with 2 balls in each.\n * \n * Example 3:\n * \n * Input: lowLimit = 19, highLimit = 28\n * Output: 2\n * Explanation:\n * Box Number:  1 2 3 4 5 6 7 8 9 10 11 12 ...\n * Ball Count:  0 1 1 1 1 1 1 1 1 2  0  0  ...\n * Box 10 has the most number of balls with 2 balls.\n * \n * Constraints:\n * \n * \t1 <= lowLimit <= highLimit <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int sum(int n) {\n        int s = 0;\n        for(; n > 0; n /= 10){\n            s += n % 10;\n        }\n        return s;\n    }\npublic:\n    int countBalls(int lowLimit, int highLimit) {\n        int cnt[46] ={0}; //10^5 means 9+9+9+9+9 = 45\n        int m = 0;\n        for (int n = lowLimit; n<=highLimit; n++) {\n            int box = sum(n);\n            cnt[box]++;\n            m = max(m, cnt[box]);\n        }\n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfConsecutiveValuesYouCanMake/MaximumNumberOfConsecutiveValuesYouCanMake.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/submissions/\n// Author : Hao Chen\n// Date   : 2021-03-22\n\n/***************************************************************************************************** \n *\n * You are given an integer array coins of length n which represents the n coins that you own. The \n * value of the i^th coin is coins[i]. You can make some value x if you can choose some of your n \n * coins such that their values sum up to x.\n * \n * Return the maximum number of consecutive integer values that you can make with your coins starting \n * from and including 0.\n * \n * Note that you may have multiple coins of the same value.\n * \n * Example 1:\n * \n * Input: coins = [1,3]\n * Output: 2\n * Explanation: You can make the following values:\n * - 0: take []\n * - 1: take [1]\n * You can make 2 consecutive integer values starting from 0.\n * \n * Example 2:\n * \n * Input: coins = [1,1,1,4]\n * Output: 8\n * Explanation: You can make the following values:\n * - 0: take []\n * - 1: take [1]\n * - 2: take [1,1]\n * - 3: take [1,1,1]\n * - 4: take [4]\n * - 5: take [4,1]\n * - 6: take [4,1,1]\n * - 7: take [4,1,1,1]\n * You can make 8 consecutive integer values starting from 0.\n * \n * Example 3:\n * \n * Input: nums = [1,4,10,3,1]\n * Output: 20\n * \n * Constraints:\n * \n * \tcoins.length == n\n * \t1 <= n <= 4 * 10^4\n * \t1 <= coins[i] <= 4 * 10^4\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int getMaximumConsecutive(vector<int>& coins) {\n        \n        int maxNum = 1; //at least, we can make 0\n        \n        //sort the coins\n        sort(coins.begin(), coins.end());\n        \n        //If we can make X, it means we can make [1,2,3,4,...X]\n        //So, if Y <= X, then we can make [Y+1, Y+2, Y+3.... Y+X]\n        //It meas we can make X+Y\n        for (auto& c : coins) {\n            if (c > maxNum) break;\n            maxNum += c;\n        }\n        return maxNum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.II.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/\n// Author : Hao Chen\n// Date   : 2021-02-16\n\n/***************************************************************************************************** \n *\n * You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event \n * starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of \n * valuei. You are also given an integer k which represents the maximum number of events you can \n * attend.\n * \n * You can only attend one event at a time. If you choose to attend an event, you must attend the \n * entire event. Note that the end day is inclusive: that is, you cannot attend two events where one \n * of them starts and the other ends on the same day.\n * \n * Return the maximum sum of values that you can receive by attending events.\n * \n * Example 1:\n * \n * Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\n * Output: 7\n * Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n * \n * Example 2:\n * \n * Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\n * Output: 10\n * Explanation: Choose event 2 for a total value of 10.\n * Notice that you cannot attend any other event as they overlap, and that you do not have to attend k \n * events.\n * \n * Example 3:\n * \n * Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\n * Output: 9\n * Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest \n * valued three.\n * \n * Constraints:\n * \n * \t1 <= k <= events.length\n * \t1 <= k * events.length <= 106\n * \t1 <= startDayi <= endDayi <= 109\n * \t1 <= valuei <= 106\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    static const bool comp_start(vector<int>& x, vector<int>& y) {\n        if ( x[0] != y[0] ) return x[0] < y[0];\n        return x[1] < y[1];\n    }\n    static const bool comp_end(vector<int>& x, vector<int>& y) {\n        if ( x[1] != y[1] ) return x[1] < y[1];\n        return x[0] < y[0];\n    }\n    void print(vector<vector<int>>& events){\n        cout << \"[\" ;\n        for(int i = 0; i<events.size(); i++) {\n            cout << \"[\"; \n            for (int j = 0; j < events[i].size(); j++) {\n                cout << events[i][j] << (j == events[i].size() - 1 ? \"\":\",\") ;\n            }\n            cout <<  (i == events.size()-1 ? \"]\": \"],\") ;\n        }\n\n        cout << \"]\" << endl;\n    }\npublic:\n    int maxValue(vector<vector<int>>& events, int k) {\n        \n        //Solution3 - DP\n        std::sort(events.begin(), events.end(), comp_end);\n        return maxValueDP(events, k); \n    \n        std::sort(events.begin(), events.end(), comp_start);\n        //Solution 2 - DFS with cache --> Time Limit Exceeded\n        vector<vector<int>> cache(events.size()+1, vector<int>(k+1, -1));\n        return maxValueDFS(events, 0, k, cache);\n        \n        //Solution 1 - DFS --> Time Limit Exceeded\n        return maxValueDFS(events, 0, k); \n    }\n    \n    //binary search to find the first event which start day is greater than the `day`\n    /* \n     * for (int i = low; i < events.size(); i++) {\n     *   if ( events[i][0] > day ) break;\n     * }\n     */\n    int findNextEvent(vector<vector<int>>& events, int low, int day) {\n\n        int high = events.size() - 1;\n        while (low < high) {\n            int mid = low + (high - low) / 2;\n            if ( events[mid][0] <= day) {\n                low = mid + 1;\n            }else{\n                high = mid;\n            }\n        }\n        return ( events[low][0] > day ) ? low : low+1;\n    }\n    \n    int maxValueDFS(vector<vector<int>>& events, int current, int k) {\n        if (current >= events.size() || k == 0 ) return 0;\n        \n        // if we select the events[index], then find the next events\n        int next = findNextEvent(events, current, events[current][1]);\n        \n        // we have two choice, attend the event or not\n        int attend = events[current][2] + maxValueDFS(events, next, k-1);\n        int skip = maxValueDFS(events, current + 1, k);\n        \n        return std::max(attend, skip);\n    }\n    \n    int maxValueDFS(vector<vector<int>>& events, int current, int k, vector<vector<int>>& cache) {\n        if (current >= events.size() || k == 0 ) return 0;\n        \n        //if find in cache, then return\n        if (cache[current][k] != -1) return cache[current][k];\n        \n        // if we select the events[index], then find the next events\n        int next = findNextEvent(events, current, events[current][1]);\n        \n        // we have two choice, attend the event or not\n        int attend = events[current][2] + maxValueDFS(events, next, k-1);\n        int skip = maxValueDFS(events, current + 1, k);\n        \n        return cache[current][k] =  std::max(attend, skip);\n        \n    }\n    \n    \n    //binary search to find the nearest previous event which ending day is less than the `day`\n    /* \n     * for (int i = high; i >= 0; i++) {\n     *   if ( events[i][1] < day ) break;\n     * }\n     */\n    int findPrevEvent(vector<vector<int>>& events, int high, int day) {\n        int low = 0;\n        while (low < high) {\n            int mid = low + (high - low) / 2;\n            if ( events[mid][1] < day) {\n                low = mid + 1;\n            }else{\n                high = mid;\n            }\n        }\n        return low - 1;\n    }\n    \n    int maxValueDP(vector<vector<int>>& events, int k) {\n        // for each event, find the previous nearest event which \n        // ending day is less than its starting day\n        \n        for (int i = 0; i < events.size(); i++) {\n            events[i].push_back( findPrevEvent(events, i, events[i][0]));\n        }\n        //print(events);\n        \n        vector<vector<int>> dp(events.size(), vector<int>(k, 0));\n        \n        //---== initial the dp table ==---\n        //if we only have first event\n        for(int i = 0; i<k; i++) {\n            dp[0][i] = events[0][2];\n        }\n        //if we only can attend one event.\n        for (int i = 1; i < events.size(); i++) {\n            dp[i][0] = max(dp[i-1][0], events[i][2]);\n        }\n\n        for (int times = 1; times<k; times++) {\n            for (int current = 1; current < events.size(); current++) {\n                \n                int prev = events[current][3];\n                \n                int attend = (prev == -1) ? \n                        events[current][2]: // not found the previous event\n                        dp[prev][times-1] + events[current][2]; //found previouse event\n                \n                int skip =  dp[current-1][times];\n                \n                dp[current][times] = max (attend, skip );\n            \n            }\n            \n        }\n        //print (dp);\n        return dp.back().back();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/\n// Author : Hao Chen\n// Date   : 2021-02-13\n\n/***************************************************************************************************** \n *\n * Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi \n * and ends at endDayi.\n * \n * You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only \n * attend one event at any time d.\n * \n * Return the maximum number of events you can attend.\n * \n * Example 1:\n * \n * Input: events = [[1,2],[2,3],[3,4]]\n * Output: 3\n * Explanation: You can attend all the three events.\n * One way to attend them all is as shown.\n * Attend the first event on day 1.\n * Attend the second event on day 2.\n * Attend the third event on day 3.\n * \n * Example 2:\n * \n * Input: events= [[1,2],[2,3],[3,4],[1,2]]\n * Output: 4\n * \n * Example 3:\n * \n * Input: events = [[1,4],[4,4],[2,2],[3,4],[1,1]]\n * Output: 4\n * \n * Example 4:\n * \n * Input: events = [[1,100000]]\n * Output: 1\n * \n * Example 5:\n * \n * Input: events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]\n * Output: 7\n * \n * Constraints:\n * \n * \t1 <= events.length <= 105\n * \tevents[i].length == 2\n * \t1 <= startDayi <= endDayi <= 105\n ******************************************************************************************************/\n\n\nclass Solution {\nprivate:\n    static const bool comp_start(vector<int>& x, vector<int>& y) {\n        if ( x[0] != y[0] ) return x[0] < y[0];\n        return x[1] < y[1];\n    }\n    static const bool comp_end(vector<int>& x, vector<int>& y) {\n        if ( x[1] != y[1] ) return x[1] < y[1];\n        return x[0] < y[0];\n    }\n\n\n    //union find\n    int find(int x, vector<int>& f) {\n        if(f[x] == x) {\n            return x;\n        } else {\n            return f[x] = find(f[x], f);\n        }\n    }\n    void print(vector<vector<int>>& events){\n        cout << \"[\" ;\n        for(auto e: events) {\n            cout << \"[\" << e[0] << \",\" << e[1] << \"],\" ;\n        }\n        cout << \"]\" << endl;\n    }\npublic:\n    int maxEvents(vector<vector<int>>& events) {\n        return maxEvents_priority_queue(events);//332ms\n        return maxEvents_union_find(events); // 336ms\n    }\n\n    int maxEvents_priority_queue(vector<vector<int>>& events) {\n        std::sort(events.begin(), events.end(), comp_start);\n        //print(events);\n\n        int start = events[0][0];\n        int end = 0;\n        for(auto& e:events){\n            end = max(end, e[1]);\n        }\n\n        int result = 0;\n        int i = 0;\n        priority_queue<int, vector<int>, greater<int>> pq;\n\n        for (int day = start; day <= end; day++) {\n            while (i<events.size() && events[i][0]==day) {\n                pq.push(events[i][1]); //push the ending day\n                i++;\n            }\n            //remove out-of-date event\n            while(!pq.empty() && pq.top() < day)  {\n                pq.pop();\n            }\n\n            //if there still has event, then choose current day.\n            if (!pq.empty()){\n                pq.pop();\n                result++;\n            }\n\n            //no more date need to process\n            if (pq.empty() && i >= events.size()) break;\n        }\n        return result;\n    }\n\n    int maxEvents_union_find(vector<vector<int>>& events) {\n        std::sort(events.begin(), events.end(), comp_end);\n\n\n        int end = events[events.size()-1][1];\n        int start = end;\n        for(auto& e:events){\n            start = min(start, e[0]);\n        }\n\n        vector<int> dict;\n        for (int i=0; i<=end-start+1; i++){\n            dict.push_back(i);\n        }\n\n        int result = 0;\n\n        for(auto& e : events) {\n\n            int x = find(e[0]-start, dict);\n            if ( x <= e[1]-start ){\n                result++;\n                dict[x] = find(x+1, dict);\n            }\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfGroupsGettingFreshDonuts/MaximumNumberOfGroupsGettingFreshDonuts.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/\n// Author : Hao Chen\n// Date   : 2021-04-08\n\n/***************************************************************************************************** \n *\n * There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must \n * serve all of the donuts of a batch before serving any donuts of the next batch. You are given an \n * integer batchSize and an integer array groups, where groups[i] denotes that there is a group of \n * groups[i] customers that will visit the shop. Each customer will get exactly one donut.\n * \n * When a group visits the shop, all customers of the group must be served before serving any of the \n * following groups. A group will be happy if they all get fresh donuts. That is, the first customer \n * of the group does not receive a donut that was left over from the previous group.\n * \n * You can freely rearrange the ordering of the groups. Return the maximum possible number of happy \n * groups after rearranging the groups.\n * \n * Example 1:\n * \n * Input: batchSize = 3, groups = [1,2,3,4,5,6]\n * Output: 4\n * Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1^st, 2^nd, 4^th, and 6^th \n * groups will be happy.\n * \n * Example 2:\n * \n * Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\n * Output: 4\n * \n * Constraints:\n * \n * \t1 <= batchSize <= 9\n * \t1 <= groups.length <= 30\n * \t1 <= groups[i] <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxHappyGroups(int batchSize, vector<int>& groups) {\n        vector<int> reminder(batchSize, 0);\n        for(auto& g : groups) {\n            reminder[g % batchSize]++;\n        }\n        \n        // greedy for reminder is zero and two groups reminder is zero.\n        // for example: batchSize = 3, groups = [1,2,3,4,5,6]\n        // then we will find: (3) (6) (1,5) (2,4) \n        \n        // greedy for one group\n        int result = reminder[0]; \n        //greedy for two groups\n        for (int i=1; i<=batchSize/2; i++){\n            if (reminder[i] == 0 || reminder[batchSize-i] == 0 ) continue;\n            \n            int m = (i == batchSize-i) ? \n                reminder[i]/2 :\n                min(reminder[i], reminder[batchSize-i]);\n            \n            reminder[i] -= m;\n            reminder[batchSize-i] -= m;\n            result += m;\n        }\n        \n        map<vector<int>, int> cache;\n        //DFS for the rest groups\n        result += dfs(reminder, batchSize, 0, cache);\n        return result;\n    }\n    \n    int dfs(vector<int>& reminder, int batchSize, int sum, map<vector<int>, int>& cache) {\n        if (cache.find(reminder) != cache.end()) return cache[reminder];\n        int ret = 0; \n        int bonus = sum == 0 ? 1: 0;\n        for(int i=1; i<batchSize; i++) {\n            if (reminder[i] <= 0)  continue;\n            reminder[i]--;\n            ret = max(ret, bonus + dfs(reminder, batchSize, (sum + i) % batchSize, cache));\n            reminder[i]++;\n        }\n        cache[reminder] = ret;\n        return ret;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumNumberOfWordsYouCanType/MaximumNumberOfWordsYouCanType.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-number-of-words-you-can-type/\n// Author : Hao Chen\n// Date   : 2021-07-22\n\n/***************************************************************************************************** \n *\n * There is a malfunctioning keyboard where some letter keys do not work. All other keys on the \n * keyboard work properly.\n * \n * Given a string text of words separated by a single space (no leading or trailing spaces) and a \n * string brokenLetters of all distinct letter keys that are broken, return the number of words in \n * text you can fully type using this keyboard.\n * \n * Example 1:\n * \n * Input: text = \"hello world\", brokenLetters = \"ad\"\n * Output: 1\n * Explanation: We cannot type \"world\" because the 'd' key is broken.\n * \n * Example 2:\n * \n * Input: text = \"leet code\", brokenLetters = \"lt\"\n * Output: 1\n * Explanation: We cannot type \"leet\" because the 'l' and 't' keys are broken.\n * \n * Example 3:\n * \n * Input: text = \"leet code\", brokenLetters = \"e\"\n * Output: 0\n * Explanation: We cannot type either word because the 'e' key is broken.\n * \n * Constraints:\n * \n * \t1 <= text.length <= 10^4\n * \t0 <= brokenLetters.length <= 26\n * \ttext consists of words separated by a single space without any leading or trailing spaces.\n * \tEach word only consists of lowercase English letters.\n * \tbrokenLetters consists of distinct lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int canBeTypedWords(string text, string brokenLetters) {\n        vector<bool> borken(26, false);\n        \n        for (auto ch : brokenLetters) {\n            borken[ch - 'a'] = true;\n        }\n        \n        text += ' ';\n        int cnt = 0;\n        for (int i = 0; i < text.size(); i++ ) {\n            if ( text[i] == ' ') continue;\n            \n            bool skip = false;\n            for (; text[i] != ' '; i++ ) {\n                if (borken[text[i] - 'a'] == true ) skip = true;\n            }\n            if ( !skip ) cnt++;\n        }\n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumPopulationYear/MaximumPopulationYear.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-population-year/\n// Author : Hao Chen\n// Date   : 2021-05-09\n\n/***************************************************************************************************** \n *\n * You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and \n * death years of the i^th person.\n * \n * The population of some year x is the number of people alive during that year. The i^th person is \n * counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the \n * person is not counted in the year that they die.\n * \n * Return the earliest year with the maximum population.\n * \n * Example 1:\n * \n * Input: logs = [[1993,1999],[2000,2010]]\n * Output: 1993\n * Explanation: The maximum population is 1, and 1993 is the earliest year with this population.\n * \n * Example 2:\n * \n * Input: logs = [[1950,1961],[1960,1971],[1970,1981]]\n * Output: 1960\n * Explanation: \n * The maximum population is 2, and it had happened in years 1960 and 1970.\n * The earlier year between them is 1960.\n * \n * Constraints:\n * \n * \t1 <= logs.length <= 100\n * \t1950 <= birthi < deathi <= 2050\n ******************************************************************************************************/\n\nclass Solution {\n\npublic:\n    int maximumPopulation(vector<vector<int>>& logs) {\n        vector<vector<int>> year;\n        \n        for(auto& log : logs) {\n            year.push_back({log[0], 1});\n            year.push_back({log[1], -1});\n        }\n        sort(year.begin(), year.end());\n        \n        int x = year[0][0];\n        int cnt = 0, max_cnt = 0;\n        for(int i=0; i< year.size(); i++) {\n            cnt += year[i][1];\n            if (max_cnt < cnt) {\n                max_cnt = cnt;\n                x = year[i][0];\n            }\n        }\n        return x;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumProductOfTwoElementsInAnArray/MaximumProductOfTwoElementsInAnArray.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/\n// Author : Hao Chen\n// Date   : 2020-10-02\n\n/***************************************************************************************************** \n *\n * Given the array of integers nums, you will choose two different indices i and j of that array. \n * Return the maximum value of (nums[i]-1)*(nums[j]-1).\n * \n * Example 1:\n * \n * Input: nums = [3,4,5,2]\n * Output: 12 \n * Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum \n * value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \n * \n * Example 2:\n * \n * Input: nums = [1,5,4,5]\n * Output: 16\n * Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of \n * (5-1)*(5-1) = 16.\n * \n * Example 3:\n * \n * Input: nums = [3,7]\n * Output: 12\n * \n * Constraints:\n * \n * \t2 <= nums.length <= 500\n * \t1 <= nums[i] <= 10^3\n ******************************************************************************************************/\nclass Solution {\npublic:\n    int maxProduct(vector<int>& nums) {\n        int max1=max(nums[0], nums[1]);\n        int max2=min(nums[0], nums[1]);\n        \n        for (int i=2; i< nums.size(); i++) {\n            if (nums[i] > max1) {\n                max2 = max1;\n                max1 = nums[i];\n                continue;\n            }else if (nums[i] > max2) {\n                max2 = nums[i];\n            }\n        }\n        return (max1-1)*(max2-1);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumProductOfWordLengths/MaximumProductOfWordLengths.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-product-of-word-lengths/\n// Author : Hao Chen\n// Date   : 2017-01-02\n\n/*************************************************************************************** \n *\n * Given a string array words, find the maximum value of length(word[i]) * \n * length(word[j]) where the two words do not share common letters.\n *     You may assume that each word will contain only lower case letters.\n *     If no such two words exist, return 0.\n * \n *     Example 1:\n * \n *     Given [\"abcw\", \"baz\", \"foo\", \"bar\", \"xtfn\", \"abcdef\"]\n *     Return 16\n *     The two words can be \"abcw\", \"xtfn\".\n * \n *     Example 2:\n * \n *     Given [\"a\", \"ab\", \"abc\", \"d\", \"cd\", \"bcd\", \"abcd\"]\n *     Return 4\n *     The two words can be \"ab\", \"cd\".\n * \n *     Example 3:\n * \n *     Given [\"a\", \"aa\", \"aaa\", \"aaaa\"]\n *     Return 0\n *     No such pair of words.    \n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    //\n    // there are two algorithms:\n    //\n    // 1) compare two words is same or not \n    //    - we can use bit-mask to solve that. \n    //    - we need be careful about one word is subset of another one, such as: \"abc\" is subset of \"abcabc\"\n    //\n    // 2) find out the max product - that needs O(N^2) time complexity algorithm.\n    //\n\n    int maxProduct(vector<string>& words) {\n        //Key is the word's bitmask, and the value the max length of that bit mask\n        unordered_map<int, int> maxLens;\n        //constructing the bitmask.\n        for(auto& w: words) {\n            int mask = 0;\n            for (auto& c: w) {\n                mask = mask | ( 1 << (c-'a') );\n            }\n            if ( maxLens.find(mask) == maxLens.end() || maxLens[mask] < w.size() ) {\n                maxLens[mask] = w.size();\n            }\n        }\n        \n        //find out the max product\n        int result = 0;\n        for (auto a : maxLens) {\n            for (auto b: maxLens) {\n                // if `a` and `b` is same, then just simply continue\n                if (a.first & b.first) continue; // there are common letters\n                result = max( result, a.second * b.second );\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumProductSubarray/maximumProductSubarray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/maximum-product-subarray/\n// Author : Hao Chen\n// Date   : 2014-10-09\n\n/********************************************************************************** \n* \n* Find the contiguous subarray within an array (containing at least one number) \n* which has the largest product.\n* \n* For example, given the array [2,3,-2,4],\n* the contiguous subarray [2,3] has the largest product = 6.\n* \n* More examples:\n*   \n*   Input: arr[] = {6, -3, -10, 0, 2}\n*   Output:   180  // The subarray is {6, -3, -10}\n*   \n*   Input: arr[] = {-1, -3, -10, 0, 60}\n*   Output:   60  // The subarray is {60}\n*   \n*   Input: arr[] = {-2, -3, 0, -2, -40}\n*   Output:   80  // The subarray is {-2, -40}\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nint max(int x, int y) {\n    return x>y?x:y;\n}\nint min(int x, int y){\n    return x<y?x:y;\n}\nint max(int x, int y, int z) {\n    return max(x, max(y,z));\n}\nint min(int x, int y, int z) {\n    return min(x, min(y, z));\n}\n\n// The idea is similar with \"Find the subarray wich has the largest sum\"\n// (See: http://en.wikipedia.org/wiki/Maximum_subarray_problem)\n// \n// The only thing to note here is, maximum product can also be obtained by minimum (negative) product \n// ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, \n// when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2.\n//\nint maxProduct(int A[], int n) {\n\n    // To remember the max/min product for previous position\n    int maxPrev = A[0], minPrev = A[0];\n    // To remember the max/min product for current position\n    int maxHere = A[0], minHere = A[0];\n    // Overall maximum product\n    int maxProd = A[0];\n\n    for (int i=1; i<n; i++){\n        maxHere = max( maxPrev * A[i], minPrev * A[i], A[i] );\n        minHere = min( maxPrev * A[i], minPrev * A[i], A[i] );\n        //Keep tracking the overall maximum product\n        maxProd = max(maxHere, maxProd);\n        //Shift the current max/min product to previous variables\n        maxPrev = maxHere;\n        minPrev = minHere;\n    }\n    return maxProd;    \n}\n\n\n#define TEST(a)    cout << maxProduct( a, sizeof(a)/sizeof(int)) << endl\nint main()\n{\n    int o[] = {2,3,-2,4};\n    TEST(o);\n\n    int a[] = {-4,-3};\n    TEST(a);\n\n    int b[] = {-1, -1};\n    TEST(b);\n\n    int c[] = {-1, 0, -2};\n    TEST(c);\n}\n"
  },
  {
    "path": "algorithms/cpp/maximumScoreFromPerformingMultiplicationOperations/MaximumScoreFromPerformingMultiplicationOperations.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/\n// Author : Hao Chen\n// Date   : 2021-04-01\n\n/***************************************************************************************************** \n *\n * You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. \n * The arrays are 1-indexed.\n * \n * You begin with a score of 0. You want to perform exactly m operations. On the i^th operation \n * (1-indexed), you will:\n * \n * \tChoose one integer x from either the start or the end of the array nums.\n * \tAdd multipliers[i] * x to your score.\n * \tRemove x from the array nums.\n * \n * Return the maximum score after performing m operations.\n * \n * Example 1:\n * \n * Input: nums = [1,2,3], multipliers = [3,2,1]\n * Output: 14\n * Explanation: An optimal solution is as follows:\n * - Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n * - Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n * - Choose from the end, [1], adding 1 * 1 = 1 to the score.\n * The total score is 9 + 4 + 1 = 14.\n * \n * Example 2:\n * \n * Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\n * Output: 102\n * Explanation: An optimal solution is as follows:\n * - Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n * - Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n * - Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n * - Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n * - Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \n * The total score is 50 + 15 - 9 + 4 + 42 = 102.\n * \n * Constraints:\n * \n * \tn == nums.length\n * \tm == multipliers.length\n * \t1 <= m <= 10^3\n * \tm <= n <= 10^5 \n * \t-1000 <= nums[i], multipliers[i] <= 1000\n ******************************************************************************************************/\n\nconst int MAX_SIZE = 1000;\nclass Solution {\nprivate:\n    int cache[MAX_SIZE][MAX_SIZE]; // num of left picked, num of right picked.\n    int m, n;\npublic:\n    int maximumScore(vector<int>& nums, vector<int>& multipliers) {\n        memset(cache, -1, sizeof(cache));\n        n = nums.size();\n        m = multipliers.size();\n        return maximumScoreDFS(nums, 0, n-1, multipliers, 0 );\n    }\n    \n    int maximumScoreDFS(vector<int>& nums, int left, int right, \n                        vector<int>& multipliers, int midx) {\n        \n        if(midx >= m )  return 0;\n        \n        int nLeft = left; // num of left nums[] picked.\n        int nRight = (n-1)-right; // num of right nums[] picked.\n        if (cache[nLeft][nRight]!=-1) return cache[nLeft][nRight];\n        \n        int pickLeft = maximumScoreDFS(nums, left+1, right, multipliers, midx+1) +\n            multipliers[midx] * nums[left];\n        \n        int pickRight = maximumScoreDFS(nums, left, right-1, multipliers, midx+1) +\n            multipliers[midx] * nums[right];\n        \n        cache[nLeft][nRight] = max(pickLeft, pickRight);\n        return cache[nLeft][nRight];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumScoreFromRemovingStones/MaximumScoreFromRemovingStones.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-score-from-removing-stones/\n// Author : Hao Chen\n// Date   : 2021-02-11\n\n/***************************************************************************************************** \n *\n * You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ \n * respectively. Each turn you choose two different non-empty piles, take one stone from each, and add \n * 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there \n * are no more available moves).\n * \n * Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.\n * \n * Example 1:\n * \n * Input: a = 2, b = 4, c = 6\n * Output: 6\n * Explanation: The starting state is (2, 4, 6). One optimal set of moves is:\n * - Take from 1st and 3rd piles, state is now (1, 4, 5)\n * - Take from 1st and 3rd piles, state is now (0, 4, 4)\n * - Take from 2nd and 3rd piles, state is now (0, 3, 3)\n * - Take from 2nd and 3rd piles, state is now (0, 2, 2)\n * - Take from 2nd and 3rd piles, state is now (0, 1, 1)\n * - Take from 2nd and 3rd piles, state is now (0, 0, 0)\n * There are fewer than two non-empty piles, so the game ends. Total: 6 points.\n * \n * Example 2:\n * \n * Input: a = 4, b = 4, c = 6\n * Output: 7\n * Explanation: The starting state is (4, 4, 6). One optimal set of moves is:\n * - Take from 1st and 2nd piles, state is now (3, 3, 6)\n * - Take from 1st and 3rd piles, state is now (2, 3, 5)\n * - Take from 1st and 3rd piles, state is now (1, 3, 4)\n * - Take from 1st and 3rd piles, state is now (0, 3, 3)\n * - Take from 2nd and 3rd piles, state is now (0, 2, 2)\n * - Take from 2nd and 3rd piles, state is now (0, 1, 1)\n * - Take from 2nd and 3rd piles, state is now (0, 0, 0)\n * There are fewer than two non-empty piles, so the game ends. Total: 7 points.\n * \n * Example 3:\n * \n * Input: a = 1, b = 8, c = 8\n * Output: 8\n * Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they \n * are empty.\n * After that, there are fewer than two non-empty piles, so the game ends.\n * \n * Constraints:\n * \n * \t1 <= a, b, c <= 105\n ******************************************************************************************************/\n\n\nclass Solution {\nprivate:\n    bool can_move(int a, int b, int c) {\n        int cnt = 0 ;\n        if ( a > 0 ) cnt++;\n        if ( b > 0 ) cnt++;\n        if ( c > 0 ) cnt++;\n        return cnt >= 2;\n    }\n\n    void swap(int& x, int& y){\n        int t = x;\n        x = y;\n        y = t;\n    }\n\n    void sort(int& a, int& b, int& c) {\n\n        if (a < b) swap(a, b);\n        if (b < c) swap(b, c);\n        if (a < b) swap(a, b);\n\n    }\npublic:\n    int maximumScore(int a, int b, int c) {\n        return maximumScore_math(a, b, c); //0\n        return maximumScore_loop(a, b, c); //20ms\n    }\n    int maximumScore_loop(int a, int b, int c) {\n        //the optimal way it always remove one stone from the biggest 2 piles\n        int score = 0;\n        while ( can_move(a, b ,c) ) {\n            score++;\n            sort(a, b ,c);\n             a--; b--;\n        }\n        return score;\n\n    }\n\n    int maximumScore_math(int a, int b, int c) {\n        // sort a > b > c\n        sort(a, b, c);\n\n        // if `a` is large enough which always has stone for `b` and `c`\n        if ( b+c <= a ) return b+c;\n\n        //if b+c > a, which means we always can find two stones, so the score is (a+b+c)/2\n        return (a+b+c)/2;\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumScoreFromRemovingSubstrings/MaximumScoreFromRemovingSubstrings.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-score-from-removing-substrings/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * You are given a string s and two integers x and y. You can perform two types of operations any \n * number of times.\n * \n * \tRemove substring \"ab\" and gain x points.\n * \n * \t\tFor example, when removing \"ab\" from \"cabxbae\" it becomes \"cxbae\".\n * \n * \tRemove substring \"ba\" and gain y points.\n * \n * \t\tFor example, when removing \"ba\" from \"cabxbae\" it becomes \"cabxe\".\n * \n * Return the maximum points you can gain after applying the above operations on s.\n * \n * Example 1:\n * \n * Input: s = \"cdbcbbaaabab\", x = 4, y = 5\n * Output: 19\n * Explanation:\n * - Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the \n * score.\n * - Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the \n * score.\n * - Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n * - Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\n * Total score = 5 + 4 + 5 + 5 = 19.\n * \n * Example 2:\n * \n * Input: s = \"aabbaaxybbaabb\", x = 5, y = 4\n * Output: 20\n * \n * Constraints:\n * \n * \t1 <= s.length <= 10^5\n * \t1 <= x, y <= 10^4\n * \ts consists of lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maximumGain(string s, int x, int y) {\n        char key[] =\"ab\";\n        if (y > x) { key[0] = 'b'; key[1]='a';}\n        \n        int high = max(x,y);\n        int low = min(x,y);\n        \n        //greedy for high score\n        int score = 0;\n        stack<char> left_stack;\n        for (int i=0; i<s.size(); i++) {\n            char c = s[i];\n            if (  left_stack.empty()  ||  //stack is empty, just push directly\n                 ( c != key[0] && c != key[1] ) ) { // not the score char, just tpush cirectory\n                left_stack.push(c);\n                continue;\n            }\n\n            // if we meet the high score pattern\n            if ( c == key[1] && left_stack.top() == key[0]){\n                //cout << key << endl;\n                left_stack.pop();\n                score += high;\n                continue;\n            }\n            left_stack.push(c);\n        }\n        \n        //process the low score\n        stack<char> right_stack;\n        while(!left_stack.empty()) {\n            char c = left_stack.top();  left_stack.pop();\n            if (right_stack.empty() || c != key[0] && c != key[1]) {\n                right_stack.push(c);\n                continue;\n            }\n            // if we meet the low score pattern\n            if ( c == key[1] && right_stack.top() == key[0]){\n                right_stack.pop();\n                score += low;\n                continue;\n            }\n            \n            right_stack.push(c);\n        }\n        return score;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumScoreOfAGoodSubarray/MaximumScoreOfAGoodSubarray.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-score-of-a-good-subarray/\n// Author : Hao Chen\n// Date   : 2021-03-19\n\n/***************************************************************************************************** \n *\n * You are given an array of integers nums (0-indexed) and an integer k.\n * \n * The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A \n * good subarray is a subarray where i <= k <= j.\n * \n * Return the maximum possible score of a good subarray.\n * \n * Example 1:\n * \n * Input: nums = [1,4,3,7,4,5], k = 3\n * Output: 15\n * Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n * \n * Example 2:\n * \n * Input: nums = [5,5,4,5,4,1,1,1], k = 0\n * Output: 20\n * Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 105\n * \t1 <= nums[i] <= 2 * 104\n * \t0 <= k < nums.length\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maximumScore(vector<int>& nums, int k) {\n        int score = nums[k];\n        int m = score;\n        int left = k, right = k;\n        int l = left, r = right;\n        while (left>0 || right < nums.size()-1){\n            \n            if ( left > 0 && right < nums.size()-1 ) {\n                if (nums[left-1] > nums[right+1]) {\n                    left--;\n                } else if (nums[left-1] < nums[right+1]) {\n                    right++;\n                } else {\n                    left--;right++;\n                }\n            }else if ( left <= 0 ) {\n                right++;\n            }else if ( right >= nums.size() -1 ) { \n                left--;\n            }else {\n                break;\n            }\n            \n            m = min(m, min( nums[left], nums[right]));\n            int s = m * (right - left + 1);\n            if ( s > score) {\n                score = s;\n                l = left;  r = right;\n            }\n        }\n        \n        //cout << \"[\" << l << \",\" << r << \"] = \" << score << endl;\n        \n        return score;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumSubArray/maximumSubArray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/maximum-subarray/\n// Author : Hao Chen\n// Date   : 2014-06-20\n\n/********************************************************************************** \n* \n* Find the contiguous subarray within an array (containing at least one number) \n* which has the largest sum.\n* \n* For example, given the array [−2,1,−3,4,−1,2,1,−5,4],\n* the contiguous subarray [4,−1,2,1] has the largest sum = 6.\n* \n* More practice:\n* \n* If you have figured out the O(n) solution, try coding another solution using \n* the divide and conquer approach, which is more subtle.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define INT_MIN     (-2147483647 - 1)\n\nint maxSubArray1(int A[], int n);\nint maxSubArray2(int A[], int n); \n\nint max(int x, int y){\n    return x>y?x:y;\n}\n\nint maxSubArray(int A[], int n) {\n    if (random()%2){\n        return maxSubArray1(A, n);\n    }\n    return maxSubArray2(A, n);\n}\n\nint maxSubArray1(int A[], int n) {\n    int *sum = new int[n];\n    sum[0] = A[0];\n    int m = A[0]; \n    for (int i=1; i<n; i++){\n        sum[i] = max(A[i], A[i] + sum[i-1]);\n        m = max(m, sum[i]);\n    }\n    delete[] sum;\n    return m;\n}\n\nint maxSubArray2(int A[], int n) {\n    int m=INT_MIN;\n    int sum=0;\n    for (int i=0; i<n; i++){\n        sum += A[i];\n        m = max(sum, m);\n        if (sum<0){\n            sum = 0;\n        }\n    }\n    return m;\n}\n\nint main()\n{\n    srand(time(NULL));\n    int a[]= {-2,1,-3,4,-1,2,1,-5,4};\n    printf(\"%d\\n\", maxSubArray(a, sizeof(a)/sizeof(int)));\n    printf(\"%d\\n\", maxSubArray(a, sizeof(a)/sizeof(int)));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/maximumSubarrayMinProduct/MaximumSubarrayMinProduct.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-subarray-min-product/\n// Author : Hao Chen\n// Date   : 2021-05-09\n\n/***************************************************************************************************** \n *\n * The min-product of an array is equal to the minimum value in the array multiplied by the array's \n * sum.\n * \n * \tFor example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * \n * 10 = 20.\n * \n * Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. \n * Since the answer may be large, return it modulo 10^9 + 7.\n * \n * Note that the min-product should be maximized before performing the modulo operation. Testcases are \n * generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.\n * \n * A subarray is a contiguous part of an array.\n * \n * Example 1:\n * \n * Input: nums = [1,2,3,2]\n * Output: 14\n * Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n * 2 * (2+3+2) = 2 * 7 = 14.\n * \n * Example 2:\n * \n * Input: nums = [2,3,3,1,2]\n * Output: 18\n * Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n * 3 * (3+3) = 3 * 6 = 18.\n * \n * Example 3:\n * \n * Input: nums = [3,1,5,6,4,2]\n * Output: 60\n * Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n * 4 * (5+6+4) = 4 * 15 = 60.\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t1 <= nums[i] <= 10^7\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int maxSumMinProduct(vector<int>& nums) {\n        nums.push_back(0); //edge case\n        \n        //prefix sum\n        vector<long> sums(nums.size(), 0);\n        // sums[i] = sum (num[0], num[1], num[2], ... num[n-1])\n        // sums[m] - sums[n] = sum (num[n], sum[n+1] .... nums[m-1]);  m > n\n        for(int i=0; i<nums.size()-1; i++) {\n            sums[i+1] = sums[i] + nums[i];\n        }\n        \n        stack<int> s;\n        long m = 0;\n        for(int i=0; i<nums.size(); i++) {\n            while( !s.empty() && nums[s.top()] > nums[i]) {\n                int min = nums[s.top()]; s.pop();\n                int start = s.empty() ? 0 : s.top() + 1;\n                int end = i;\n                m = max(m , min * (sums[end] - sums[start]));\n                \n                // cout << \"[\";\n                // for(int k = start; k < end-1; k++) {\n                //    cout << nums[k] << \",\";\n                // }\n                // cout << nums[end-1] << \"], \" << min << \"*\" << (sums[end] - sums[start]) \n                //     << \"=\" << min * (sums[end] - sums[start]) << endl;\n                \n            }\n            // if the num is increasing, then push into stack\n            s.push(i);\n        }\n        //cout << endl;\n        return m % 1000000007;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumUnitsOnATruck/MaximumUnitsOnATruck.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-units-on-a-truck/\n// Author : Hao Chen\n// Date   : 2021-03-30\n\n/***************************************************************************************************** \n *\n * You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, \n * where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:\n * \n * \tnumberOfBoxesi is the number of boxes of type i.\n * \tnumberOfUnitsPerBoxi is the number of units in each box of the type i.\n * \n * You are also given an integer truckSize, which is the maximum number of boxes that can be put on \n * the truck. You can choose any boxes to put on the truck as long as the number of boxes does not \n * exceed truckSize.\n * \n * Return the maximum total number of units that can be put on the truck.\n * \n * Example 1:\n * \n * Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\n * Output: 8\n * Explanation: There are:\n * - 1 box of the first type that contains 3 units.\n * - 2 boxes of the second type that contain 2 units each.\n * - 3 boxes of the third type that contain 1 unit each.\n * You can take all the boxes of the first and second types, and one box of the third type.\n * The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.\n * \n * Example 2:\n * \n * Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\n * Output: 91\n * \n * Constraints:\n * \n * \t1 <= boxTypes.length <= 1000\n * \t1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000\n * \t1 <= truckSize <= 10^6\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    void print(vector<vector<int>>& boxes) {\n        cout << \"{ \";\n        for(int i=0; i<boxes.size()-1; i++){\n            cout << \"[\" << boxes[i][0] << \",\"<< boxes[i][1] << \"], \";\n        }\n        int i=boxes.size()-1;\n        cout << \"[\" << boxes[i][0] << \", \"<< boxes[i][1] << \"] } \"<< endl;\n    }\npublic:\n    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {\n        sort(boxTypes.begin(), boxTypes.end(), \n             [&](vector<int>& lhs, vector<int>& rhs){return lhs[1] > rhs[1]; });\n        //print(boxTypes);\n        int units = 0;\n        for(auto& box : boxTypes) {\n            if (truckSize >= box[0]) {\n                units += box[0] * box[1];\n            }else{\n                units += truckSize * box[1];\n            }\n            truckSize -= box[0];\n            if (truckSize <= 0 ) break;\n        }\n        return units;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumValueAfterInsertion/MaximumValueAfterInsertion.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-value-after-insertion/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * You are given a very large integer n, represented as a string, and an integer digit x. The \n * digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative \n * number.\n * \n * You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n\n * . You cannot insert x to the left of the negative sign.\n * \n * \tFor example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n =  763.\n * \tIf n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.\n * \n * Return a string representing the maximum value of n after the insertion.\n * \n * Example 1:\n * \n * Input: n = \"99\", x = 9\n * Output: \"999\"\n * Explanation: The result is the same regardless of where you insert 9.\n * \n * Example 2:\n * \n * Input: n = \"-13\", x = 2\n * Output: \"-123\"\n * Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n * \n * Constraints:\n * \n * \t1 <= n.length <= 10^5\n * \t1 <= x <= 9\n * \tThe digits in n are in the range [1, 9].\n * \tn is a valid representation of an integer.\n * \tIn the case of a negative n, it will begin with '-'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string maxValue(string n, int x) {\n        bool neg = false;\n        if (n[0] == '-') neg = true;\n        \n        int i;\n        \n        for( i=neg?1:0; i<n.size(); i++){\n            if (neg == true) {\n                if ( n[i]-'0' > x) break;\n            }else{ \n                if (n[i]-'0' < x) break; \n            }\n        }\n     \n        n.insert(n.begin()+i, x+'0');\n        return n;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumValueAtAGivenIndexInABoundedArray/MaximumValueAtAGivenIndexInABoundedArray.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/\n// Author : Hao Chen\n// Date   : 2021-03-21\n\n/***************************************************************************************************** \n *\n * You are given three positive integers n, index and maxSum. You want to construct an array nums \n * (0-indexed) that satisfies the following conditions:\n * \n * \tnums.length == n\n * \tnums[i] is a positive integer where 0 <= i < n.\n * \tabs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.\n * \tThe sum of all the elements of nums does not exceed maxSum.\n * \tnums[index] is maximized.\n * \n * Return nums[index] of the constructed array.\n * \n * Note that abs(x) equals x if x >= 0, and -x otherwise.\n * \n * Example 1:\n * \n * Input: n = 4, index = 2,  maxSum = 6\n * Output: 2\n * Explanation: The arrays [1,1,2,1] and [1,2,2,1] satisfy all the conditions. There are no other \n * valid arrays with a larger value at the given index.\n * \n * Example 2:\n * \n * Input: n = 6, index = 1,  maxSum = 10\n * Output: 3\n * \n * Constraints:\n * \n * \t1 <= n <= maxSum <= 109\n * \t0 <= index < n\n ******************************************************************************************************/\n\n/*\n\nThis problem can be treat as a pyramid which shaped by 1, it looks like below:\n\n        1\n      1 1 1\n    1 1 1 1 1\n  1 1 1 1 1 1 1\nSo, from the top, for each layer, we need the 1,3,5,7,9.... 2*n-1 ONE(s).\n\nBut we need to deal with the edge case - it could be out of the array boundary\n\nFor example: index=2, lenght=3, maxSum=18\n\n      1) at first, we put  `1 1 1` on bottom layer - Array[2] = 1\n\n      2) then we start from the top \n\n                1   <-- the top first layer\n            1 1 1   <-- bottom \n            \n         now, we have Array[2] is 2\n\n      3) we keep doing tthe 2nd layer - Array[2] = 3\n                1      <-- the 1st layer\n              1 1 [1]  <-- the 2nd layer, which has 1 out of the boundary\n            1 1 1      <-- bottom \n            \n         now, we have Array[2] is 3\n\n      4) the 3rd layer  -  Array[2] = 4 \n                1         <-- the 1st layer\n              1 1 [1]     <-- the 2nd layer, which has 1 out of the boundary\n            1 1 1 [1] [1] <-- the 3rd layer, which has 2 out of the boundary\n            1 1 1         <-- bottom \n            \n         now, we have Array[2] is 4\n   \t\t \n      5) Now, the rest layers no need to be cacluated, they all are `3`.\n         Since 4), we spent 9 of `1`,  we still have 18 - 9 = 9 of `1`\n         So, we can have 9/3 = 3 layer.\n         \n      6) Finally, the maximum of Array[2] = 4 + 3 = 7\n*/\n\nclass Solution {\npublic:\n    int maxValue(int n, int index, int maxSum) {\n        // at least, put the bottom layer\n        int maxValue = 1;\n        maxSum -= n;\n        int layer = 1;\n        \n        int points;\n        while ( maxSum > 0 ) {\n            // how many 1 we need\n            points = (2 * layer - 1);\n            \n            // how many 1 exceed the right bound\n            int right = (index + layer-1) - (n-1);\n            if (right > 0)  points -= right;\n            // how many 1 exceed the left bound\n            int left = (layer - index - 1);\n            if (left > 0)  points -= left;\n           \n            //  points >= n  -  we just need `n` for the rest layers \n            //  maxSum < points -  if we  haven't enough points \n            if (points >= n || maxSum < points) break;\n            \n            \n            maxSum -= points;\n            layer++;\n            maxValue++;\n        }\n        // maxSum/n - we just need `n` for the rest layers\n        return maxValue += (maxSum/n);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/maximumXorForEachQuery/MaximumXorForEachQuery.cpp",
    "content": "// Source : https://leetcode.com/problems/maximum-xor-for-each-query/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to \n * perform the following query n times:\n * \n * \tFind a non-negative integer k < 2^maximumBit such that nums[0] XOR nums[1] XOR ... XOR \n * nums[nums.length-1] XOR k is maximized. k is the answer to the i^th query.\n * \tRemove the last element from the current array nums.\n * \n * Return an array answer, where answer[i] is the answer to the i^th query.\n * \n * Example 1:\n * \n * Input: nums = [0,1,1,3], maximumBit = 2\n * Output: [0,3,2,3]\n * Explanation: The queries are answered as follows:\n * 1^st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n * 2^nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n * 3^rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n * 4^th query: nums = [0], k = 3 since 0 XOR 3 = 3.\n * \n * Example 2:\n * \n * Input: nums = [2,3,4,7], maximumBit = 3\n * Output: [5,2,6,5]\n * Explanation: The queries are answered as follows:\n * 1^st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n * 2^nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n * 3^rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n * 4^th query: nums = [2], k = 5 since 2 XOR 5 = 7.\n * \n * Example 3:\n * \n * Input: nums = [0,1,2,2,5,7], maximumBit = 3\n * Output: [4,3,6,4,6,7]\n * \n * Constraints:\n * \n * \tnums.length == n\n * \t1 <= n <= 10^5\n * \t1 <= maximumBit <= 20\n * \t0 <= nums[i] < 2^maximumBit\n * \tnums​​​ is sorted in ascending order.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n\n        const int size = nums.size();\n        const int max = (1 << maximumBit) - 1;\n\n        int all = 0;\n        vector<int> result(size);\n        for(int i = 0; i < size; i++) {\n            all ^= nums[i];\n            result[size-i-1] = all ^ max;\n        }\n\n        return result;\n    }\n\n    vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n        int all = 0;\n        for(auto& n : nums) {\n            all ^= n;\n        }\n        \n        int max = (1 << maximumBit) - 1; \n        vector<int> result;\n        for(int i = nums.size()-1; i>=0; i--) {\n            result.push_back(all ^ max);\n            all ^= nums[i];\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/median-of-two-sorted-arrays/\n// Author : Hao Chen\n// Date   : 2014-07-22\n\n/********************************************************************************** \n* \n* There are two sorted arrays A and B of size m and n respectively. \n* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\n// Classical binary search algorithm, but slightly different\n// if cannot find the key, return the position where can insert the key \nint binarySearch(int A[], int low, int high, int key){\n    while(low<=high){\n        int mid = low + (high - low)/2;\n        if (key == A[mid]) return mid;\n        if (key > A[mid]){\n            low = mid + 1;\n        }else {\n            high = mid -1;\n        }\n    }\n    return low;\n}\n\n//Notes:\n// I feel the following methods is quite complicated, it should have a better high clear and readable solution\ndouble findMedianSortedArrayHelper(int A[], int m, int B[], int n, int lowA, int highA, int lowB, int highB) {\n\n    // Take the A[middle], search its position in B array\n    int mid = lowA + (highA - lowA)/2;\n    int pos = binarySearch(B, lowB, highB, A[mid]);\n    int num = mid + pos;\n    // If the A[middle] in B is B's middle place, then we can have the result\n    if (num == (m+n)/2){\n        // If two arrays total length is odd, just simply return the A[mid]\n        // Why not return the B[pos] instead ? \n        //   suppose A={ 1,3,5 } B={ 2,4 }, then mid=1, pos=1\n        //   suppose A={ 3,5 }   B={1,2,4}, then mid=0, pos=2\n        //   suppose A={ 1,3,4,5 }   B={2}, then mid=1, pos=1\n        // You can see, the `pos` is the place A[mid] can be inserted, so return A[mid]\n        if ((m+n)%2==1){\n            return A[mid];\n        }\n        \n        // If tow arrys total length is even, then we have to find the next one.\n        int next;\n\n        // If both `mid` and `pos` are not the first postion.\n        // Then, find max(A[mid-1], B[pos-1]). \n        // Because the `mid` is the second middle number, we need to find the first middle number\n        // Be careful about the edge case\n        if (mid>0 && pos>0){ \n            next = A[mid-1]>B[pos-1] ? A[mid-1] : B[pos-1];\n        }else if(pos>0){\n            next = B[pos-1];\n        }else if(mid>0){\n            next = A[mid-1];\n        }\n        \n        return (A[mid] + next)/2.0;\n    }\n    // if A[mid] is in the left middle place of the whole two arrays\n    //\n    //         A(len=16)        B(len=10)\n    //     [................] [...........]\n    //            ^             ^\n    //           mid=7         pos=1\n    //\n    //  move the `low` pointer to the \"middle\" position, do next iteration.\n    if (num < (m+n)/2){\n        lowA = mid + 1;\n        lowB = pos; \n        if ( highA - lowA > highB - lowB ) {\n            return findMedianSortedArrayHelper(A, m, B, n, lowA, highA, lowB, highB);\n        }\n        return findMedianSortedArrayHelper(B, n, A, m, lowB, highB, lowA, highA);\n    }\n    // if A[mid] is in the right middle place of the whole two arrays\n    if (num > (m+n)/2) {\n        highA = mid - 1;\n        highB = pos-1;\n        if ( highA - lowA > highB - lowB ) {\n            return findMedianSortedArrayHelper(A, m, B, n, lowA, highA, lowB, highB);\n        }\n        return findMedianSortedArrayHelper(B, n, A, m, lowB, highB, lowA, highA);\n    }\n\n}\n\ndouble findMedianSortedArrays(int A[], int m, int B[], int n) {\n\n    //checking the edge cases\n    if ( m==0 && n==0 ) return 0.0;\n\n    //if the length of array is odd, return the middle one\n    //if the length of array is even, return the average of the middle two numbers\n    if ( m==0 ) return n%2==1 ? B[n/2] : (B[n/2-1] + B[n/2])/2.0;\n    if ( n==0 ) return m%2==1 ? A[m/2] : (A[m/2-1] + A[m/2])/2.0;\n    \n    \n    //let the longer array be A, and the shoter array be B\n    if ( m > n ){\n        return findMedianSortedArrayHelper(A, m, B, n, 0, m-1, 0, n-1);\n    }\n        \n    return findMedianSortedArrayHelper(B, n, A, m, 0, n-1, 0, m-1);\n}\n\n\nint main()\n{\n    int r1[] = {1};\n    int r2[] = {2};\n \n    int n1 = sizeof(r1)/sizeof(r1[0]);\n    int n2 = sizeof(r2)/sizeof(r2[0]);\n\n    printf(\"Median is 1.5 = %f\\n\", findMedianSortedArrays(r1, n1, r2, n2));\n\n    int ar1[] = {1, 12, 15, 26, 38};\n    int ar2[] = {2, 13, 17, 30, 45, 50};\n \n    n1 = sizeof(ar1)/sizeof(ar1[0]);\n    n2 = sizeof(ar2)/sizeof(ar2[0]);\n\n    printf(\"Median is 17 = %f\\n\", findMedianSortedArrays(ar1, n1, ar2, n2));\n\n    int ar11[] = {1, 12, 15, 26, 38};\n    int ar21[] = {2, 13, 17, 30, 45 };\n \n    n1 = sizeof(ar11)/sizeof(ar11[0]);\n    n2 = sizeof(ar21)/sizeof(ar21[0]);\n\n    printf(\"Median is 16 = %f\\n\", findMedianSortedArrays(ar11, n1, ar21, n2));\n\n    int a1[] = {1, 2, 5, 6, 8 };\n    int a2[] = {13, 17, 30, 45, 50};\n \n    n1 = sizeof(a1)/sizeof(a1[0]);\n    n2 = sizeof(a2)/sizeof(a2[0]);\n\n    printf(\"Median is 10.5 = %f\\n\", findMedianSortedArrays(a1, n1, a2, n2));\n\n    int a10[] = {1, 2, 5, 6, 8, 9, 10 };\n    int a20[] = {13, 17, 30, 45, 50};\n \n    n1 = sizeof(a10)/sizeof(a10[0]);\n    n2 = sizeof(a20)/sizeof(a20[0]);\n\n    printf(\"Median is 9.5 = %f\\n\", findMedianSortedArrays(a10, n1, a20, n2));\n\n    int a11[] = {1, 2, 5, 6, 8, 9 };\n    int a21[] = {13, 17, 30, 45, 50};\n \n    n1 = sizeof(a11)/sizeof(a11[0]);\n    n2 = sizeof(a21)/sizeof(a21[0]);\n\n    printf(\"Median is 9 = %f\\n\", findMedianSortedArrays(a11, n1, a21, n2));\n\n    int a12[] = {1, 2, 5, 6, 8 };\n    int a22[] = {11, 13, 17, 30, 45, 50};\n \n    n1 = sizeof(a12)/sizeof(a12[0]);\n    n2 = sizeof(a22)/sizeof(a22[0]);\n\n    printf(\"Median is 11 = %f\\n\", findMedianSortedArrays(a12, n1, a22, n2));\n\n    int b1[] = {1 };\n    int b2[] = {2,3,4};\n \n    n1 = sizeof(b1)/sizeof(b1[0]);\n    n2 = sizeof(b2)/sizeof(b2[0]);\n\n    printf(\"Median is 2.5 = %f\\n\", findMedianSortedArrays(b1, n1, b2, n2));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/mergeIntervals/mergeIntervals.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/merge-intervals/\n// Author : Hao Chen\n// Date   : 2014-08-26\n\n/********************************************************************************** \n* \n* Given a collection of intervals, merge all overlapping intervals.\n* \n* For example,\n* Given [1,3],[2,6],[8,10],[15,18],\n* return [1,6],[8,10],[15,18].\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Interval {\n    int start;\n    int end;\n    Interval() : start(0), end(0) {}\n    Interval(int s, int e) : start(s), end(e) {}\n};\n\n//Two factos sorting [start:end]\nbool compare(const Interval& lhs, const Interval& rhs){\n    return (lhs.start==rhs.start) ? lhs.end < rhs.end : lhs.start < rhs.start;\n}\n\nvector<Interval> merge(vector<Interval> &intervals) {\n\n    vector<Interval> result;\n\n    if (intervals.size() <= 0) return result;\n    //sort the inervals. Note: using the customized comparing function.\n    sort(intervals.begin(), intervals.end(), compare);\n    for(int i=0; i<intervals.size(); i++) { \n        int size = result.size();\n        // if the current intervals[i] is overlapped with previous interval.\n        // merge them together\n        if( size>0 && result[size-1].end >= intervals[i].start) {\n            result[size-1].end = max(result[size-1].end, intervals[i].end); \n        }else{\n            result.push_back(intervals[i]);\n        }\n    }\n    \n    return result;\n}\n\n\nint main(int argc, char**argv)\n{\n    Interval i1(1,4);\n    Interval i2(0,2);\n    Interval i3(3,5);\n    Interval i4(15,18);\n    vector<Interval> intervals;\n    intervals.push_back(i1);\n    intervals.push_back(i2);\n    intervals.push_back(i3);\n    intervals.push_back(i4);\n    \n    vector<Interval> r = merge(intervals);\n    \n    for(int i=0; i<r.size(); i++){\n        cout << \"[ \" << r[i].start << \", \" << r[i].end << \" ] \";\n    }\n    cout <<endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/mergeKSortedLists/mergeKSortedLists.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/merge-k-sorted-lists/\n// Author : Hao Chen\n// Date   : 2014-07-06\n\n/********************************************************************************** \n* \n* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *mergeTwoLists(ListNode* head1, ListNode* head2);\nListNode *mergeTwoLists01(ListNode* head1, ListNode* head2);\nListNode *mergeTwoLists02(ListNode* head1, ListNode* head2);\n\nListNode *mergeKLists(vector<ListNode *> &lists) {\n    ListNode *p, *p1, *p2;\n    while(lists.size()>1){\n        p1 = lists.back();    \n        lists.pop_back();\n        p2 = lists.back();    \n        lists.pop_back();\n        p = mergeTwoLists(p1, p2);\n        lists.insert(lists.begin(), p);\n    }\n    return lists.size()==1 ? lists[0] : NULL;\n\n    /* the following method is not fast enough! */\n    /*\n    ListNode* pHead = NULL;\n    for (int i=0; i<lists.size(); i++){\n        pHead = mergeTwoLists(pHead, lists[i]);\n    }\n    return pHead;\n    */\n}\n\nstatic int n=0;\nListNode *mergeTwoLists(ListNode* head1, ListNode* head2){\n    if (n){\n        //cout << \"------ method 01 ------\" <<endl;\n        return mergeTwoLists01(head1, head2);\n    }\n    //cout << \"------ method 02 ------\" <<endl;\n    return mergeTwoLists02(head1, head2);\n}\n/*======================================================================*/\n/*                            Method One                                */\n/*======================================================================*/\n\n//#define INT_MAX   2147483647\n//#define INT_MIN   (-INT_MAX - 1)\n\nListNode *mergeTwoLists01(ListNode* head1, ListNode* head2){\n    ListNode *p1 = head1,  *p2=head2;\n    static ListNode dummy(0);\n\n    dummy.next = p1;\n    ListNode *prev = &dummy;\n\n    while(p1 && p2){\n        if(p1->val < p2->val){\n            prev = p1;\n            p1 = p1->next;\n        }else{\n            prev->next = p2;\n            p2 = p2->next;\n            prev = prev->next;\n            prev->next = p1;\n        }\n    }\n    if (p2){\n        prev->next = p2;\n    }\n\n    return dummy.next;\n}\n\n/*======================================================================*/\n/*                            Method Two                                */\n/*======================================================================*/\n\n\nvoid TakeOutNode(ListNode*& head, ListNode*& tail, ListNode*& p);\n\nListNode *mergeTwoLists02(ListNode* head1, ListNode* head2) {\n    ListNode *p1 = head1,  *p2=head2;\n\n    ListNode *pHead = NULL, *pTail=NULL;\n    while(p1 && p2){\n        if(p1->val < p2->val){\n            TakeOutNode(pHead, pTail, p1);\n        }else{\n            TakeOutNode(pHead, pTail, p2);\n        }\n    }\n\n    ListNode *p=NULL;\n    if (p1){\n        p = p1;\n    }else if (p2){\n        p = p2;\n    }\n    if (pHead==NULL){\n        return p;\n    }\n    pTail->next = p;\n    return pHead;\n}\n\nvoid TakeOutNode(ListNode*& head, ListNode*& tail, ListNode*& p){\n    ListNode *pNext = p->next;\n    if (head==NULL){\n        head = tail = p;\n    }else{\n        tail->next = p;\n        tail = p;\n    }\n    p->next = NULL;\n    p = pNext;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main(int argc, char**argv)\n{\n    srand(time(0));\n    if (argc>1){\n        n = atoi(argv[1]) % 2;\n    }\n\n    int a[] = {1,3,5,6,7,10};\n    int b[] = {0,4,6,8,9,11,20,30,40};\n    ListNode* p1 = createList(a, sizeof(a)/sizeof(int));\n    ListNode* p2 = createList(b, sizeof(b)/sizeof(int));\n\n    printList( mergeTwoLists(p1,p2) );\n    //mergeTwoLists(p1,p2) ;\n\n\n    vector<ListNode*> v;\n    for(int i=0; i<10240; i++) {\n        v.push_back(new ListNode(random()%100));\n    }\n    printList( mergeKLists(v) );\n    //mergeKLists(v);\n\n\n    cout << \"method \" << n+1 << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/mergeStringsAlternately/MergeStringsAlternately.cpp",
    "content": "// Source : https://leetcode.com/problems/merge-strings-alternately/\n// Author : Hao Chen\n// Date   : 2021-03-20\n\n/***************************************************************************************************** \n *\n * You are given two strings word1 and word2. Merge the strings by adding letters in alternating \n * order, starting with word1. If a string is longer than the other, append the additional letters \n * onto the end of the merged string.\n * \n * Return the merged string.\n * \n * Example 1:\n * \n * Input: word1 = \"abc\", word2 = \"pqr\"\n * Output: \"apbqcr\"\n * Explanation: The merged string will be merged as so:\n * word1:  a   b   c\n * word2:    p   q   r\n * merged: a p b q c r\n * \n * Example 2:\n * \n * Input: word1 = \"ab\", word2 = \"pqrs\"\n * Output: \"apbqrs\"\n * Explanation: Notice that as word2 is longer, \"rs\" is appended to the end.\n * word1:  a   b \n * word2:    p   q   r   s\n * merged: a p b q   r   s\n * \n * Example 3:\n * \n * Input: word1 = \"abcd\", word2 = \"pq\"\n * Output: \"apbqcd\"\n * Explanation: Notice that as word1 is longer, \"cd\" is appended to the end.\n * word1:  a   b   c   d\n * word2:    p   q \n * merged: a p b q c   d\n * \n * Constraints:\n * \n * \t1 <= word1.length, word2.length <= 100\n * \tword1 and word2 consist of lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string mergeAlternately(string word1, string word2) {\n        int len1 = word1.size();\n        int len2 = word2.size();\n        int len = min(len1, len2);\n        \n        string result;\n        for (int i=0; i<len; i++) {\n            result += word1[i];\n            result += word2[i];\n        }\n        \n        if (len1 > len) result += word1.substr(len, len1 - len );\n        if (len2 > len) result += word2.substr(len, len2 - len );\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/mergeTwoSortedArray/mergeTwoSortedArray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/merge-sorted-array/\n// Author : Hao Chen\n// Date   : 2014-06-20\n\n/********************************************************************************** \n* \n* Given two sorted integer arrays A and B, merge B into A as one sorted array.\n* \n* Note:\n*   You may assume that A has enough space (size that is greater or equal to m + n) \n*   to hold additional elements from B. The number of elements initialized in A and B \n*   are m and n respectively.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\nvoid merge(int A[], int m, int B[], int n) {\n    int ia = m-1 ;\n    int ib = n-1 ;\n    int i = m + n - 1;\n    for (int i=m+n-1; i>=0; i--){\n        \n        if (ia>=0 && ib<0){\n            break;\n        }\n        if (ia<0 && ib>=0){\n            A[i] = B[ib--];\n            continue;\n        }            \n        if (ia>=0 && ib>=0){\n            if (A[ia] > B[ib]){\n                A[i] = A[ia--];\n            }else{\n                A[i] = B[ib--];\n            }\n        }\n\n    }\n}\n\nvoid printArray(int A[], int n) {\n    printf(\"{\");\n    for(int i=0; i<n; i++) {\n        printf(\"%d, \", A[i]);\n    }\n    printf(\"}\\n\");\n}\n\nint main()\n{\n    int a[]={2,4,6,8,10,0,0,0};\n    int b[]={1,3,5};\n    merge(a, 5, b, 3 );\n    printArray(a,  sizeof(a)/sizeof(int));\n\n    int a1[]={2,4,0,0,0};\n    int b1[]={3,5,7};\n    merge(a1, 2, b1, 3 );\n    printArray(a1, sizeof(a1)/sizeof(int));\n\n    int a2[]={12,14,16,18,20,0,0,0};\n    int b2[]={1,3,5};\n    merge(a2, 5, b2, 3 );\n    printArray(a2,  sizeof(a2)/sizeof(int));\n\n    int a3[]={2,0};\n    int b3[]={3,};\n    merge(a3, 1, b3, 1 );\n    printArray(a3, sizeof(a3)/sizeof(int));\n\n    int a4[]={0,0,0};\n    int b4[]={1,3,5};\n    merge(a4, 0, b4, 3 );\n    printArray(a4, sizeof(a4)/sizeof(int));\n\n    int a5[]={2,4,6,8,10,0,0,0};\n    int b5[]={11,13,15};\n    merge(a5, 5, b5, 3 );\n    printArray(a5,  sizeof(a5)/sizeof(int));\n\n    int a6[]={2,4,0,0,0,0,0,0};\n    int b6[]={1,3,5,7,9,11};\n    merge(a6, 2, b6, 6 );\n    printArray(a6, sizeof(a6)/sizeof(int));\n\n    return 0;\n\n\n}\n"
  },
  {
    "path": "algorithms/cpp/mergeTwoSortedList/mergeTwoSortedList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/merge-two-sorted-lists/\n// Author : Hao Chen\n// Date   : 2014-07-06\n\n/********************************************************************************** \n* \n* Merge two sorted linked lists and return it as a new list. The new list should be \n* made by splicing together the nodes of the first two lists.\n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        switch (random()%3){\n            case 0:\n                return mergeTwoLists01(l1, l2);\n            case 1:\n                return mergeTwoLists02(l1, l2);\n            default:\n                return mergeTwoLists03(l1, l2);\n        }\n    }\n    \n    /* merge the 2nd list into 1st list*/\n    ListNode *mergeTwoLists01(ListNode* head1, ListNode* head2){\n        ListNode *p1 = head1,  *p2=head2;\n        static ListNode dummy(0);\n    \n        dummy.next = p1;\n        ListNode *prev = &dummy;\n    \n        while(p1 && p2){\n            if(p1->val < p2->val){\n                prev = p1;\n                p1 = p1->next;\n            }else{\n                prev->next = p2;\n                p2 = p2->next;\n                prev = prev->next;\n                prev->next = p1;\n            }\n        }\n        if (p2){\n            prev->next = p2;\n        }\n    \n        return dummy.next;\n    }\n\n\n    /* merge two lists to the new list */\n    ListNode *mergeTwoLists02(ListNode *l1, ListNode *l2) {\n        ListNode *l=NULL, *p=NULL;\n        \n        while (l1!=NULL && l2!=NULL ){\n            ListNode *n=NULL;\n            if (l1->val < l2-> val){\n                n = l1;\n                l1=l1->next;\n            }else{\n                n = l2;\n                l2=l2->next;\n            }\n            if (l==NULL){\n                l = p = n;\n            }else{\n                p->next = n;\n                p = p->next;\n            }\n        }\n        \n        ListNode* rest = l1 ? l1 :l2;\n        \n        l = mergeTheRest(rest, l, p);\n       \n        \n        return l;\n    }\n\n    ListNode* mergeTheRest(ListNode* l, ListNode*head, ListNode* tail){\n        if (l){\n            if (head && tail ){\n                tail->next = l;\n            }else{\n                head = l;\n            }\n        }\n        return head;\n    }\n\n    /*  \n     * You can see the 2nd slution's code is quite complicated, \n     * because it need to check the (head==NULL) situation.\n     * We can use the \"pointer to pointer\" to make the code more clean\n     * however, this would be bad for performance.\n     */\n    ListNode *mergeTwoLists03(ListNode *l1, ListNode *l2) {\n        ListNode *head = NULL;\n        ListNode **pTail = &head;\n        while (l1 != NULL && l2 != NULL) {\n            if (l1->val < l2->val) {\n                *pTail = l1;\n                l1 = l1->next;\n            } else {\n                *pTail = l2;\n                l2 = l2->next;\n            }\n            pTail = &(*pTail)->next;\n        }\n        *pTail = (l1 != NULL ? l1 : l2);\n        return head;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/minCostClimbingStairs/MinCostClimbingStairs.cpp",
    "content": "// Source : https://leetcode.com/problems/min-cost-climbing-stairs/\n// Author : Hao Chen\n// Date   : 2019-02-04\n\n/***************************************************************************************************** \n *\n * \n * On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).\n * \n * Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to \n * reach the top of the floor, and you can either start from the step with index 0, or the step with \n * index 1.\n * \n * Example 1:\n * \n * Input: cost = [10, 15, 20]\n * Output: 15\n * Explanation: Cheapest is start on cost[1], pay that cost and go to the top.\n * \n * Example 2:\n * \n * Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\n * Output: 6\n * Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].\n * \n * Note:\n * \n * cost will have a length in the range [2, 1000].\n * Every cost[i] will be an integer in the range [0, 999].\n * \n ******************************************************************************************************/\nclass Solution {\n    public:\n        int minCostClimbingStairs(vector<int>& cost) {\n            return minCostClimbingStairs02(cost); \n            return minCostClimbingStairs01(cost); \n        }\n        int minCostClimbingStairs01(vector<int>& cost) {\n            vector<int> dp(cost.size() , 0);\n            dp[0] = cost[0];\n            dp[1] = cost[1];\n            for (int i=2; i<cost.size(); i++) {\n                dp[i] = min( dp[i-1], dp[i-2] ) + cost[i];\n            }\n            return min(dp[dp.size()-1], dp[dp.size()-2]);\n        }\n\n        int minCostClimbingStairs02(vector<int>& cost) {\n            int dp1 = cost[0], dp2 = cost[1];\n            for (int i=2; i<cost.size(); i++) {\n                int dp = min( dp1, dp2 ) + cost[i];\n                dp1 = dp2;\n                dp2 = dp;\n            }\n            return min (dp1, dp2);\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/minStack/minStack.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/min-stack/\n// Author : Hao Chen\n// Date   : 2014-11-16\n\n/********************************************************************************** \n* \n* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n* \n* push(x) -- Push element x onto stack.\n* \n* pop() -- Removes the element on top of the stack.\n* \n* top() -- Get the top element.\n* \n* getMin() -- Retrieve the minimum element in the stack.\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\n//It seems C++ vector cause the Memory Limit Error, So, implement a simple one\ntemplate <typename T>\nclass Stack {\n    private:\n        T* _stack;\n        int _capacity;\n        int _top;\n    public:\n        Stack():_capacity(1),_top(-1){\n            _stack = (T*)malloc(_capacity*sizeof(T));\n        }\n\n        ~Stack(){\n            free(_stack);\n        }\n\n        void push(T x){\n            _top++;\n            if ( _top >= _capacity ){\n                //if capacity is not enough, enlarge it 5 times.\n                //Notes: why 5 times? because if you change to other(e.g. 2 times), \n                //       LeetCode system will report Run-time Error! it sucks!\n                _capacity*=5;\n                _stack = (T*)realloc(_stack, _capacity*sizeof(T));\n            }\n            _stack[_top] = x;\n        }\n\n        T pop() {\n            return top(true);\n        }\n\n        T& top(bool pop=false) {\n            if (_top>=0){\n                if (pop){\n                    return _stack[_top--];\n                }\n                return _stack[_top];\n            }\n            static T null;\n            return null;\n        }\n\n        bool empty(){\n            return (_top<0);\n        }\n        int size() {\n            return _top+1;\n        }\n        void clear(){\n            _top = -1;\n        }\n};\n\n\n/*\n * Idea: \n *\n *    Using two stacks, \n *    1) one stack is the real stack to store the data.\n *    2) another stack store the minimal number when it changes.\n *\n *    For example:\n *\n *        if we keep pushing the following numbers:\n *        5 1 1 2 3 2 \n *        the minial number stack will be: \n *        5 1 1   <-- only store the number which <= cureent minimal number\n *   \n *    Then, when we pop up the stack.\n *\n *    we need compare whether the current number is the current minial number.\n *    if it is, then we need popup the number in minimal number stack.\n *        \n */\nclass MinStack {\n    private:\n        //Using a minData struct to remove the duplication in minimal stack\n        //which can save the memory.\n        struct minData{\n            int min;\n            int cnt;\n            minData():min(0), cnt(0) {}\n            minData(int m, int c):min(m),cnt(c){}\n        };\n        Stack<int> stack; //real stack store the data\n        Stack<minData> minStack; //minimal number stack store the number \n        int min; //current minial number\n\n    public:\n\n        void push(int x) {\n            if(stack.empty()){\n                min = x;\n                minStack.push(minData(x,1));\n            }else{\n                if (min >= x ){\n                    min = x;\n                    //if current minial number already pushed, then just add the reference coount.\n                    if (minStack.top().min == x){\n                        minStack.top().cnt++;\n                    }else{\n                        minStack.push(minData(x,1));\n                    }\n                }\n            }\n            stack.push(x);\n\n        }\n\n        void pop() {\n            if (stack.empty()){\n                return;\n            }\n            int x = stack.pop();\n            if (x == minStack.top().min){\n                //de-reference the count at first.\n                if (minStack.top().cnt > 1){\n                    minStack.top().cnt--;\n                }else{\n                    minStack.pop();\n                    min = minStack.top().min;\n                }\n            }\n        }\n\n        int top() {\n            return stack.top();\n        }\n\n        int getMin() {\n            return min;\n        }\n        void clear() {\n            stack.clear();\n            minStack.clear();\n        }\n\n};\n\nint main()\n{\n    cout << \"--- expected output [0, 0, 0, 2]\" << endl;\n    MinStack ms;\n    ms.push(2);\n    ms.push(0);\n    ms.push(3);\n    ms.push(0);\n\n    cout << ms.getMin() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n\n\n    ms.clear();\n\n    cout << \"--- expected output [2147483647 2147483646 2147483646 2147483647 2147483647 -2147483648 -2147483648 2147483647 \" << endl;\n\n    ms.push(2147483646);\n    ms.push(2147483646);\n    ms.push(2147483647);\n\n    cout << ms.top() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n    ms.pop();\n\n    ms.push(2147483647);\n    cout << ms.top() << endl;\n    cout << ms.getMin() << endl;\n    ms.push(-2147483648);\n    cout << ms.top() << endl;\n    cout << ms.getMin() << endl;\n    ms.pop();\n    cout << ms.getMin() << endl;\n\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/miniParser/MiniParser.cpp",
    "content": "// Source : https://leetcode.com/problems/mini-parser/\n// Author : Hao Chen\n// Date   : 2016-08-24\n\n/*************************************************************************************** \n *\n * Given a nested list of integers represented as a string, implement a parser to \n * deserialize it.\n * \n * Each element is either an integer, or a list -- whose elements may also be integers \n * or other lists.\n * \n * Note:\n * You may assume that the string is well-formed:\n * \n * String is non-empty.\n * String does not contain white spaces.\n * String contains only digits 0-9, [, - ,, ].\n * \n * Example 1:\n * \n * Given s = \"324\",\n * \n * You should return a NestedInteger object which contains a single integer 324.\n * \n * Example 2:\n * \n * Given s = \"[123,[456,[789]]]\",\n * \n * Return a NestedInteger object containing a nested list with 2 elements:\n * \n * 1. An integer containing value 123.\n * 2. A nested list containing two elements:\n *     i.  An integer containing value 456.\n *     ii. A nested list with one element:\n *          a. An integer containing value 789.\n ***************************************************************************************/\n\n\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Constructor initializes an empty nested list.\n *     NestedInteger();\n *\n *     // Constructor initializes a single integer.\n *     NestedInteger(int value);\n *\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Set this NestedInteger to hold a single integer.\n *     void setInteger(int value);\n *\n *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n *     void add(const NestedInteger &ni);\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n    NestedInteger deserialize(string s) {\n        if (s.size()==0) return NestedInteger();\n        int pos = 0;\n        if (s[pos]!='[') return atoni(s, pos);\n        \n        return helper(s, ++pos);\n    }\nprivate:\n    NestedInteger helper(string& s, int& pos) {\n       \n        NestedInteger ni;\n        \n        while ( s[pos] != ']' && pos < s.size() ) {\n\n            if (s[pos]=='-' || isnum(s[pos])){\n                ni.add(atoni(s, pos));\n            }else if (s[pos] == '[') {\n                pos++;\n                ni.add(helper(s, pos));\n            }else {\n                pos++;\n            }\n        }\n        pos++;\n        return ni;\n    }\n    NestedInteger atoni(string& s, int& pos) {\n        int sign = 1;\n        int num = 0;\n        if (s[pos]=='-') {\n            sign = -1;\n            pos++;\n        }\n        for (; pos < s.size(); pos++) {\n            if (isnum(s[pos])) {\n                num = num * 10 + s[pos] - '0';\n            }else{\n                break;\n            }\n        }\n        return NestedInteger(sign * num);\n    }\n    bool isnum(char& c) {\n        return (c >='0' && c <='9');\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimizeMaximumPairSumInArray/MinimizeMaximumPairSumInArray.cpp",
    "content": "// Source : https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/\n// Author : Hao Chen\n// Date   : 2021-11-12\n\n/***************************************************************************************************** \n *\n * The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a \n * list of pairs.\n * \n * \tFor example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be \n * max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.\n * \n * Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:\n * \n * \tEach element of nums is in exactly one pair, and\n * \tThe maximum pair sum is minimized.\n * \n * Return the minimized maximum pair sum after optimally pairing up the elements.\n * \n * Example 1:\n * \n * Input: nums = [3,5,2,3]\n * Output: 7\n * Explanation: The elements can be paired up into pairs (3,3) and (5,2).\n * The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\n * \n * Example 2:\n * \n * Input: nums = [3,5,4,2,4,6]\n * Output: 8\n * Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\n * The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\n * \n * Constraints:\n * \n * \tn == nums.length\n * \t2 <= n <= 10^5\n * \tn is even.\n * \t1 <= nums[i] <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minPairSum(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        int i = 0, j = nums.size() - 1;\n        int m = 0;\n        for(int i = 0, j = nums.size() - 1; i < j; i++,j--) {\n            m = max(m, nums[i] + nums[j]);\n        }\n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumASCIIDeleteSumForTwoStrings/MinimumAsciiDeleteSumForTwoStrings.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/\n// Author : Hao Chen\n// Date   : 2019-01-30\n\n/***************************************************************************************************** \n *\n * Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.\n * \n * Example 1:\n * \n * Input: s1 = \"sea\", s2 = \"eat\"\n * Output: 231\n * Explanation: Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\n * Deleting \"t\" from \"eat\" adds 116 to the sum.\n * At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n * \n * Example 2:\n * \n * Input: s1 = \"delete\", s2 = \"leet\"\n * Output: 403\n * Explanation: Deleting \"dee\" from \"delete\" to turn the string into \"let\",\n * adds 100[d]+101[e]+101[e] to the sum.  Deleting \"e\" from \"leet\" adds 101[e] to the sum.\n * At the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\n * If instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which \n * are higher.\n * \n * Note:\n * 0 .\n * All elements of each string will have an ASCII value in [97, 122]. \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minimumDeleteSum(string s1, string s2) {\n        // Dynamic Programm - simlar with : Edit Distance\n        vector < vector <int> > dp ( s1.size()+1, vector<int>( s2.size()+1, 0) );\n\n        // s1 is row, s2 is column\n        for (int i=1; i<=s2.size(); i++) dp[0][i] = dp[0][i-1] + s2[i-1];\n        for (int i=1; i<=s1.size(); i++) dp[i][0] = dp[i-1][0] + s1[i-1];\n\n        for (int i=1; i<=s1.size(); i++){\n            for (int j=1; j<=s2.size(); j++) {\n                if ( s1[i-1] == s2[j-1] ) {\n                    dp[i][j] = dp[i-1][j-1];\n                }else{\n                    dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1] + s2[j-1]);\n                }\n            }\n        }\n\n        return dp[s1.size()][s2.size()];\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumAbsoluteSumDifference/MinimumAbsoluteSumDifference.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-absolute-sum-difference/\n// Author : Hao Chen\n// Date   : 2021-04-05\n\n/***************************************************************************************************** \n *\n * You are given two positive integer arrays nums1 and nums2, both of length n.\n * \n * The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - \n * nums2[i]| for each 0 <= i < n (0-indexed).\n * \n * You can replace at most one element of nums1 with any other element in nums1 to minimize the \n * absolute sum difference.\n * \n * Return the minimum absolute sum difference after replacing at most one element in the array nums1. \n * Since the answer may be large, return it modulo 10^9 + 7.\n * \n * |x| is defined as:\n * \n * \tx if x >= 0, or\n * \t-x if x < 0.\n * \n * Example 1:\n * \n * Input: nums1 = [1,7,5], nums2 = [2,3,5]\n * Output: 3\n * Explanation: There are two possible optimal solutions:\n * - Replace the second element with the first: [1,7,5] => [1,1,5], or\n * - Replace the second element with the third: [1,7,5] => [1,5,5].\n * Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\n * \n * Example 2:\n * \n * Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\n * Output: 0\n * Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \n * absolute sum difference of 0.\n * \n * Example 3:\n * \n * Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\n * Output: 20\n * Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\n * This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n * \n * Constraints:\n * \n * \tn == nums1.length\n * \tn == nums2.length\n * \t1 <= n <= 10^5\n * \t1 <= nums1[i], nums2[i] <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {\n        int max=0, idx=0;\n        long sum=0;\n        int len = nums1.size();\n        for (int i=0; i<len; i++) {\n            int m = abs(nums1[i] - nums2[i]);\n            if (max < m) {\n                max = m; \n                idx = i;\n            }\n            sum += m ;\n        }\n        int min = max;\n        for (int i=0; i<len; i++) {\n            int m = abs(nums1[i] - nums2[idx]);\n            if (m < min) {\n                min = m;\n            }\n        }\n        \n        sum -= (max - min);\n        return sum % 1000000007 ;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumAdjacentSwapsToReachTheKthSmallestNumber/MinimumAdjacentSwapsToReachTheKthSmallestNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * You are given a string num, representing a large integer, and an integer k.\n * \n * We call some integer wonderful if it is a permutation of the digits in num and is greater in value \n * than num. There can be many wonderful integers. However, we only care about the smallest-valued \n * ones.\n * \n * \tFor example, when num = \"5489355142\":\n * \n * \t\tThe 1^st smallest wonderful integer is \"5489355214\".\n * \t\tThe 2^nd smallest wonderful integer is \"5489355241\".\n * \t\tThe 3^rd smallest wonderful integer is \"5489355412\".\n * \t\tThe 4^th smallest wonderful integer is \"5489355421\".\n * \n * Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k^th \n * smallest wonderful integer.\n * \n * The tests are generated in such a way that k^th smallest wonderful integer exists.\n * \n * Example 1:\n * \n * Input: num = \"5489355142\", k = 4\n * Output: 2\n * Explanation: The 4^th smallest wonderful number is \"5489355421\". To get this number:\n * - Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n * - Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"\n * \n * Example 2:\n * \n * Input: num = \"11112\", k = 4\n * Output: 4\n * Explanation: The 4^th smallest wonderful number is \"21111\". To get this number:\n * - Swap index 3 with index 4: \"11112\" -> \"11121\"\n * - Swap index 2 with index 3: \"11121\" -> \"11211\"\n * - Swap index 1 with index 2: \"11211\" -> \"12111\"\n * - Swap index 0 with index 1: \"12111\" -> \"21111\"\n * \n * Example 3:\n * \n * Input: num = \"00123\", k = 1\n * Output: 1\n * Explanation: The 1^st smallest wonderful number is \"00132\". To get this number:\n * - Swap index 3 with index 4: \"00123\" -> \"00132\"\n * \n * Constraints:\n * \n * \t2 <= num.length <= 1000\n * \t1 <= k <= 1000\n * \tnum only consists of digits.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    // Refer to:\n    // https://leetcode.com/problems/next-permutation/solution/\n    void nextPermutation(string& num) {\n        int i = num.size() - 2;\n        while (i >= 0 && num[i + 1] <= num[i]) {\n            i--;\n        }\n        if (i >= 0) {\n            int j = num.size() - 1;\n            while (j >= 0 && num[j] <= num[i]) {\n                j--;\n            }\n            swap(num[i], num[j]);\n        }\n        reverse(num, i + 1);\n    }\n\n    void reverse(string& num, int start) {\n        int i = start, j = num.size() - 1;\n        while (i < j) {\n            swap(num[i], num[j]);\n            i++;\n            j--;\n        }\n    }\n\n\npublic:\n    int getMinSwaps(string num, int k) {\n        string pnum = num;\n        while(k--) {\n            nextPermutation(pnum);\n        }\n        //cout << num << endl << pnum << endl;\n        int result = 0;\n        for(int i = 0; i < num.size(); i++) {\n            if (num[i] == pnum[i]) continue;\n            for(int j = i + 1; j < num.size(); j++) {\n                if(num[i] != pnum[j]) continue;\n                //cout << \"j=\" << j << \", i=\" << i << endl;\n                result += j - i;\n                \n                //shift the string\n                char c = pnum[j];\n                for (int k = j; k > i; k--) {\n                    pnum[k] = pnum[k-1];\n                }\n                pnum[i] = c;\n                //cout << pnum << endl;\n                break;\n            }\n        }\n        //cout << endl;\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumChangesToMakeAlternatingBinaryString/MinimumChangesToMakeAlternatingBinaryString.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/\n// Author : Hao Chen\n// Date   : 2021-02-14\n\n/***************************************************************************************************** \n *\n * You are given a string s consisting only of the characters '0' and '1'. In one operation, you can \n * change any '0' to '1' or vice versa.\n * \n * The string is called alternating if no two adjacent characters are equal. For example, the string \n * \"010\" is alternating, while the string \"0100\" is not.\n * \n * Return the minimum number of operations needed to make s alternating.\n * \n * Example 1:\n * \n * Input: s = \"0100\"\n * Output: 1\n * Explanation: If you change the last character to '1', s will be \"0101\", which is alternating.\n * \n * Example 2:\n * \n * Input: s = \"10\"\n * Output: 0\n * Explanation: s is already alternating.\n * \n * Example 3:\n * \n * Input: s = \"1111\"\n * Output: 2\n * Explanation: You need two operations to reach \"0101\" or \"1010\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 104\n * \ts[i] is either '0' or '1'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minOperations(string s) {\n        int start_with_zero = 0;\n        int start_with_one = 0;\n        for (int i=0; i<s.size(); i++){\n            if (i % 2 == 0) {\n                s[i] == '1' ? start_with_zero++ : start_with_one++;\n            }else{\n                s[i] == '0' ? start_with_zero++ : start_with_one++;\n            }\n        }\n        return std::min(start_with_zero, start_with_one);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumCostForTickets/MinimumCostForTickets.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-cost-for-tickets/\n// Author : Hao Chen\n// Date   : 2019-01-29\n\n/***************************************************************************************************** \n *\n * In a country popular for train travel, you have planned some train travelling one year in advance.  \n * The days of the year that you will travel is given as an array days.  Each day is an integer from 1 \n * to 365.\n * \n * Train tickets are sold in 3 different ways:\n * \n * \ta 1-day pass is sold for costs[0] dollars;\n * \ta 7-day pass is sold for costs[1] dollars;\n * \ta 30-day pass is sold for costs[2] dollars.\n * \n * The passes allow that many days of consecutive travel.  For example, if we get a 7-day pass on day \n * 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.\n * \n * Return the minimum number of dollars you need to travel every day in the given list of days.\n * \n * Example 1:\n * \n * Input: days = [1,4,6,7,8,20], costs = [2,7,15]\n * Output: 11\n * Explanation: \n * For example, here is one way to buy passes that lets you travel your travel plan:\n * On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\n * On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\n * On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\n * In total you spent $11 and covered all the days of your travel.\n * \n * Example 2:\n * \n * Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\n * Output: 17\n * Explanation: \n * For example, here is one way to buy passes that lets you travel your travel plan:\n * On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\n * On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\n * In total you spent $17 and covered all the days of your travel.\n * \n * Note:\n * \n * \t1 <= days.length <= 365\n * \t1 <= days[i] <= 365\n * \tdays is in strictly increasing order.\n * \tcosts.length == 3\n * \t1 <= costs[i] <= 1000\n * \n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int min(int x, int y){\n        return x < y ? x : y;\n    }\n    int min(int x, int y, int z) {\n        return min(min(x, y), z);\n    }\npublic:\n    int mincostTickets(vector<int>& days, vector<int>& costs) {\n\n        // Dynamic Programming\n        vector<int> dp(days.size()+1, INT_MAX);\n\n        // dp[i] is the minimal cost from Days[0] to Days[i]\n        dp[0] = 0;\n        dp[1] = min(costs[0], costs[1], costs[2]);\n\n        for (int i = 2; i<= days.size(); i ++) {\n\n            // the currnet day need at least min(1-day, 7days, 30days) from previous.\n            int m = dp[i-1] + min(costs[0], costs[1], costs[2]);\n\n            // Seprating the array to two parts.\n            //     days[0] -> days[j] -> day[i]\n            //\n            // calculate the day[i] - day[j] whether can use 7-day pass or 30-day pass\n            //\n            // Traking the minimal costs, then can have dp[i] minimal cost\n\n            int SevenDays = INT_MAX, ThrityDays = INT_MAX;\n            for (int j=i-1; j>0; j--){\n                int gaps = days[i-1] - days[j-1];\n                if ( gaps < 7 )  {\n                    // can use 7-days or 30-days ticket\n                    SevenDays  = dp[j-1] + min(costs[1], costs[2]);\n                } else if (gaps < 30 ) {\n                    //can use 30-days tickets\n                    ThrityDays = dp[j-1] + costs[2];\n                } else {\n                    break;\n                }\n                m = min(m, SevenDays, ThrityDays);\n            }\n            if ( dp[i] > m )  dp[i] = m;\n        }\n        \n        return dp[dp.size()-1];    \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumDegreeOfAConnectedTrioInAGraph/MinimumDegreeOfAConnectedTrioInAGraph.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/\n// Author : Hao Chen\n// Date   : 2021-02-14\n\n/***************************************************************************************************** \n *\n * You are given an undirected graph. You are given an integer n which is the number of nodes in the \n * graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge \n * between ui and vi.\n * \n * A connected trio is a set of three nodes where there is an edge between every pair of them.\n * \n * The degree of a connected trio is the number of edges where one endpoint is in the trio, and the \n * other is not.\n * \n * Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected \n * trios.\n * \n * Example 1:\n * \n * Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\n * Output: 3\n * Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded \n * in the figure above.\n * \n * Example 2:\n * \n * Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\n * Output: 0\n * Explanation: There are exactly three trios:\n * 1) [1,4,3] with degree 0.\n * 2) [2,5,6] with degree 2.\n * 3) [5,6,7] with degree 2.\n * \n * Constraints:\n * \n * \t2 <= n <= 400\n * \tedges[i].length == 2\n * \t1 <= edges.length <= n * (n-1) / 2\n * \t1 <= ui, vi <= n\n * \tui != vi\n * \tThere are no repeated edges.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    vector<vector<bool>>* edge_matrix;\n    vector<int>* node_edge_num;\n    \n    bool has_edge(int x, int y) {\n        return (*edge_matrix)[x][y];\n    }\n    \n    int node_edges(int x){\n        return (*node_edge_num)[x];\n    }\n    \n    int degree(int x, int y, int z) {\n        if (has_edge(x,y) && has_edge(y,z) && has_edge(x,z)) {\n            return node_edges(x) +  node_edges(y) +  node_edges(z) - 6; \n        }\n        return -1;\n    }\npublic:\n   \n    int minTrioDegree(int n, vector<vector<int>>& edges) {\n        vector<vector<bool>> edge_matrix(n+1, vector<bool>(n+1, false));\n        vector<int> node_edge_num(n+1, 0);\n        \n        this->edge_matrix = &edge_matrix;\n        this->node_edge_num = &node_edge_num;\n        \n        for (auto& edge : edges) {\n            edge_matrix[edge[0]][edge[1]] = true;\n            edge_matrix[edge[1]][edge[0]] = true;\n            node_edge_num[edge[0]]++;\n            node_edge_num[edge[1]]++;\n        }\n        \n        int result = -1;\n        for(int i=1; i<=n; i++) {\n            if (node_edge_num[i] < 2) continue;\n            for(int j=i+1; j<=n; j++) {\n                if (!has_edge(i, j)) continue;\n                for(int k=j+1; k<=n; k++) {\n                    if (!has_edge(j, k)) continue;\n                    int d = degree(i, j, k);\n                    if ( d >= 0 ) {\n                        result = result < 0 ? d : min(result, d);\n                    }\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given a binary tree, find its minimum depth.\n* \n* The minimum depth is the number of nodes along the shortest path from the root node \n* down to the nearest leaf node.\n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int minDepth(TreeNode *root) {\n        if (root==NULL){\n            return 0;\n        }\n        if (root->left==NULL && root->right==NULL){\n            return 1;\n        }\n        int left=INT_MAX;\n        if (root->left){\n            left = minDepth(root->left) + 1 ;\n        }\n        int right=INT_MAX;\n        if (root->right){\n            right = minDepth(root->right) + 1;\n        }\n        \n        return left<right ? left : right;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumDistanceToTheTargetElement/MinimumDistanceToTheTargetElement.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-distance-to-the-target-element/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * Given an integer array nums (0-indexed) and two integers target and start, find an index i such \n * that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.\n * \n * Return abs(i - start).\n * \n * It is guaranteed that target exists in nums.\n * \n * Example 1:\n * \n * Input: nums = [1,2,3,4,5], target = 5, start = 3\n * Output: 1\n * Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n * \n * Example 2:\n * \n * Input: nums = [1], target = 1, start = 0\n * Output: 0\n * Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 1.\n * \n * Example 3:\n * \n * Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\n * Output: 0\n * Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = \n * 0.\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 1000\n * \t1 <= nums[i] <= 10^4\n * \t0 <= start < nums.length\n * \ttarget is in nums.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int getMinDistance(vector<int>& nums, int target, int start) {\n        int minDist = nums.size();\n        for(int i=start; i < nums.size(); i++){\n            if ( target == nums[i] ) {\n                minDist = i - start;\n                break;\n            } \n        }\n\n        for (int i=start; i>=0; i--) {\n            if ( target == nums[i] && start - i <= minDist) {\n                minDist = start - i;\n                break;\n            }\n        }\n        return minDist;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumElementsToAddToFormAGivenSum/MinimumElementsToAddToFormAGivenSum.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/\n// Author : Hao Chen\n// Date   : 2021-03-07\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums and two integers limit and goal. The array nums has an \n * interesting property that abs(nums[i]) <= limit.\n * \n * Return the minimum number of elements you need to add to make the sum of the array equal to goal. \n * The array must maintain its property that abs(nums[i]) <= limit.\n * \n * Note that abs(x) equals x if x >= 0, and -x otherwise.\n * \n * Example 1:\n * \n * Input: nums = [1,-1,1], limit = 3, goal = -4\n * Output: 2\n * Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.\n * \n * Example 2:\n * \n * Input: nums = [1,-10,9,1], limit = 100, goal = 0\n * Output: 1\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 105\n * \t1 <= limit <= 106\n * \t-limit <= nums[i] <= limit\n * \t-109 <= goal <= 109\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    long sum(vector<int>& nums) {\n        long s = 0;\n        for (auto n : nums) {\n            s += n;\n        }\n        return s;\n    }\n    int minElements(vector<int>& nums, int limit, int goal) {\n        long s = sum(nums);\n        return (abs(goal - s) + limit -1) / limit;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumFallingPathSum/MinimumFallingPathSum.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-falling-path-sum/\n// Author : Hao Chen\n// Date   : 2019-01-30\n\n/***************************************************************************************************** \n *\n * Given a square array of integers A, we want the minimum sum of a falling path through A.\n * \n * A falling path starts at any element in the first row, and chooses one element from each row.  The \n * next row's choice must be in a column that is different from the previous row's column by at most \n * one.\n * \n * Example 1:\n * \n * Input: [[1,2,3],[4,5,6],[7,8,9]]\n * Output: 12\n * Explanation: \n * The possible falling paths are:\n * \n * \t[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]\n * \t[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]\n * \t[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]\n * \n * The falling path with the smallest sum is [1,4,7], so the answer is 12.\n * \n * Note:\n * \n * \t1 <= A.length == A[0].length <= 100\n * \t-100 <= A[i][j] <= 100\n ******************************************************************************************************/\nclass Solution {\nprivate:\n    int min(int x, int y) {\n        return x < y ? x: y;\n    }\n    int min( int x, int y, int z) {\n        return min(min(x, y),z);\n    }\npublic:\n    int minFallingPathSum(vector<vector<int>>& A) {\n        int m = INT_MAX;\n        \n        for (int i=0; i<A.size(); i++) {\n            for (int j=0; j<A[i].size(); j++){\n                //find the minimal item in previous row, and add it into the current item\n                if (i > 0) {\n                    if (j == 0 ){\n                       A[i][j] += min( A[i-1][j], A[i-1][j+1]); \n                    } else if ( j + 1 == A[i].size()) {\n                       A[i][j] += min( A[i-1][j], A[i-1][j-1]); \n                    }else {\n                        A[i][j] += min( A[i-1][j], A[i-1][j-1], A[i-1][j+1]);\n                    }\n                }\n                \n                if ( i + 1 == A.size() ) {\n                    m = min(m, A[i][j]);\n                }\n            }\n        }\n        \n        return m;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumHeightTrees/MinimumHeightTrees.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-height-trees/\n// Author : Hao Chen\n// Date   : 2016-01-24\n\n/*************************************************************************************** \n *\n * For a undirected graph with tree characteristics, we can choose any node as the \n * root. The result graph is then a rooted tree. Among all possible rooted trees, those \n * with minimum height are called minimum height trees (MHTs).\n *\n * Given such a graph, write a function to find all the MHTs and return a list of \n * their root labels.\n * \n *     *Format*\n *     The graph contains n nodes which are labeled from 0 to n - 1.\n *     You will be given the number n and a list of undirected edges (each edge is a \n *     pair of labels).\n * \n *  \n *     You can assume that no duplicate edges will appear in edges. Since all edges are\n *     undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.\n * \n *     Example 1:\n * \n *     Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]\n * \n *         0\n *         |\n *         1\n *        / \\\n *       2   3\n * \n *     return  [1]\n * \n *     Example 2:\n * \n *     Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]\n * \n *      0  1  2\n *       \\ | /\n *         3\n *         |\n *         4\n *         |\n *         5\n * \n *     return  [3, 4]\n * \n *     How many MHTs can a graph have at most?\n * \n *     Note:\n * \n *     (1) According to the definition of tree on Wikipedia: https://en.wikipedia.org/wiki/Tree_(graph_theory)\n *         “a tree is an undirected graph in which any two vertices are connected by exactly one path. \n *         In other words, any connected graph without simple cycles is a tree.”\n * \n *     (2) The height of a rooted tree is the number of edges on the longest downward path between \n *         the root and a leaf.\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {\n        //corner case\n        if ( n <= 1 ) return {0};\n        \n        //construct a edges search data stucture\n        vector<unordered_set<int>> graph(n);\n        for (auto e : edges) {\n            graph[e.first].insert(e.second);\n            graph[e.second].insert(e.first);\n        }\n        \n        //find all of leaf nodes\n        vector<int> current;\n        for (int i=0; i<graph.size(); i++){\n            if (graph[i].size() == 1)  current.push_back(i);\n        }\n        \n        // BFS the graph\n        while (true) {\n            vector<int> next;\n            for (int node : current) {\n                for (int neighbor : graph[node]) {\n                    graph[neighbor].erase(node);\n                    if (graph[neighbor].size() == 1) next.push_back(neighbor);\n                }\n            }\n            if (next.empty()) break;\n            current = next;\n        }\n        return current;\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/minimumInsertionsToBalanceAParenthesesString/MinimumInsertionsToBalanceAParenthesesString.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/\n// Author : Hao Chen\n// Date   : 2020-10-02\n\n/***************************************************************************************************** \n *\n * Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is \n * balanced if:\n * \n * \tAny left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.\n * \tLeft parenthesis '(' must go before the corresponding two consecutive right parenthesis \n * '))'.\n * \n * In other words, we treat '(' as openning parenthesis and '))' as closing parenthesis.\n * \n * For example, \"())\", \"())(())))\" and \"(())())))\" are balanced, \")()\", \"()))\" and \"(()))\" are not \n * balanced.\n * \n * You can insert the characters '(' and ')' at any position of the string to balance it if needed.\n * \n * Return the minimum number of insertions needed to make s balanced.\n * \n * Example 1:\n * \n * Input: s = \"(()))\"\n * Output: 1\n * Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need \n * to to add one more ')' at the end of the string to be \"(())))\" which is balanced.\n * \n * Example 2:\n * \n * Input: s = \"())\"\n * Output: 0\n * Explanation: The string is already balanced.\n * \n * Example 3:\n * \n * Input: s = \"))())(\"\n * Output: 3\n * Explanation: Add '(' to match the first '))', Add '))' to match the last '('.\n * \n * Example 4:\n * \n * Input: s = \"((((((\"\n * Output: 12\n * Explanation: Add 12 ')' to balance the string.\n * \n * Example 5:\n * \n * Input: s = \")))))))\"\n * Output: 5\n * Explanation: Add 4 '(' at the beginning of the string and one ')' at the end. The string becomes \n * \"(((())))))))\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 10^5\n * \ts consists of '(' and ')' only.\n ******************************************************************************************************/\nclass Solution {\npublic:\n    int minInsertions(string s) {\n        vector<char> stack;\n        \n        int cnt = 0;\n        int len = s.size();\n        for (int i=0; i<len; i++) {\n            \n            if ( s[i] == '(' ) {\n                stack.push_back( s[i] );\n                continue;\n            }\n            // if s[i] is ')'\n            if (stack.size() > 0)  {\n                stack.pop_back();\n            } else {\n                cnt++; // missed the '('\n            }\n            \n            // if  s[i+1] is ')', need to skip\n            if ( i < len -1 && s[i+1] == ')' ) {\n                i++;\n            }else{\n                cnt++; //missed the ')'\n            }\n         \n        }\n        \n        // if the stack still has '(', which means need double of ')'\n        return cnt + stack.size()*2;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumIntervalToIncludeEachQuery/MinimumIntervalToIncludeEachQuery.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-interval-to-include-each-query/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the i^th \n * interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as \n * the number of integers it contains, or more formally righti - lefti + 1.\n * \n * You are also given an integer array queries. The answer to the j^th query is the size of the \n * smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer \n * is -1.\n * \n * Return an array containing the answers to the queries.\n * \n * Example 1:\n * \n * Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]\n * Output: [3,3,1,4]\n * Explanation: The queries are processed as follows:\n * - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n * - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n * - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n * - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.\n * \n * Example 2:\n * \n * Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]\n * Output: [2,-1,4,6]\n * Explanation: The queries are processed as follows:\n * - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n * - Query = 19: None of the intervals contain 19. The answer is -1.\n * - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n * - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + \n * 1 = 6.\n * \n * Constraints:\n * \n * \t1 <= intervals.length <= 10^5\n * \t1 <= queries.length <= 10^5\n * \tqueries[i].length == 2\n * \t1 <= lefti <= righti <= 10^7\n * \t1 <= queries[j] <= 10^7\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {\n        set<vector<int>> s;\n        \n        vector<vector<int>> iQueries;\n        for(int i=0; i < queries.size(); i++) {\n            iQueries.push_back({queries[i], i});\n        }\n        \n        sort(intervals.begin(), intervals.end());\n        sort(iQueries.begin(), iQueries.end());\n        \n        vector<int> result(queries.size(), -1);\n        \n        int i = 0, len = intervals.size();\n        \n        for(auto& iq: iQueries) {\n            int q = iq[0];\n            int idx = iq[1];\n            \n            while( i < len && intervals[i][0] <= q) {\n                s.insert({intervals[i][1] - intervals[i][0] + 1, intervals[i][1]});\n                i++;\n            }\n            while( !s.empty() ) {\n                auto it = s.begin();\n                if ( (*it)[1] >= q ) break;\n                s.erase(s.begin());\n            }\n            if ( !s.empty() ) {\n                auto it = s.begin();\n                result[idx] = (*it)[0];\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumLengthOfStringAfterDeletingSimilarEnds/MinimumLengthOfStringAfterDeletingSimilarEnds.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/\n// Author : Hao Chen\n// Date   : 2021-02-12\n\n/***************************************************************************************************** \n *\n * Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the \n * following algorithm on the string any number of times:\n * \n * \tPick a non-empty prefix from the string s where all the characters in the prefix are equal.\n * \tPick a non-empty suffix from the string s where all the characters in this suffix are equal.\n * \tThe prefix and the suffix should not intersect at any index.\n * \tThe characters from the prefix and suffix must be the same.\n * \tDelete both the prefix and the suffix.\n * \n * Return the minimum length of s after performing the above operation any number of times (possibly \n * zero times).\n * \n * Example 1:\n * \n * Input: s = \"ca\"\n * Output: 2\n * Explanation: You can't remove any characters, so the string stays as is.\n * \n * Example 2:\n * \n * Input: s = \"cabaabac\"\n * Output: 0\n * Explanation: An optimal sequence of operations is:\n * - Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n * - Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n * - Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n * - Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".\n * \n * Example 3:\n * \n * Input: s = \"aabccabba\"\n * Output: 3\n * Explanation: An optimal sequence of operations is:\n * - Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n * - Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 105\n * \ts only consists of characters 'a', 'b', and 'c'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minimumLength(string s) {\n        char ch; \n        int left=0, right=s.size()-1;\n        \n        while(left < right) {\n            ch = s[left];\n            if (s[right] != ch) break;\n            \n            while (s[left] == ch) left++;\n    \n            if (left >= right ) return 0;\n            while (s[right] == ch) right--;\n        }\n        \n        return right - left + 1;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumLimitOfBallsInABag/MinimumLimitOfBallsInABag.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/\n// Author : Hao Chen\n// Date   : 2021-02-14\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an \n * integer maxOperations.\n * \n * You can perform the following operation at most maxOperations times:\n * \n * \tTake any bag of balls and divide it into two new bags with a positive number of balls.\n * \n * \t\tFor example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new \n * bags of 2 and 3 balls.\n * \n * Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the \n * operations.\n * \n * Return the minimum possible penalty after performing the operations.\n * \n * Example 1:\n * \n * Input: nums = [9], maxOperations = 2\n * Output: 3\n * Explanation: \n * - Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n * - Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\n * The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n * \n * Example 2:\n * \n * Input: nums = [2,4,8,2], maxOperations = 4\n * Output: 2\n * Explanation:\n * - Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n * - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n * - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n * - Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\n * The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.\n * \n * Example 3:\n * \n * Input: nums = [7,17], maxOperations = 2\n * Output: 7\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 105\n * \t1 <= maxOperations, nums[i] <= 109\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minimumSize(vector<int>& nums, int maxOperations) {\n        \n        //find the theoretical min/max of penalty\n        int max_penalty = 0;\n        long long sum = 0;\n        for (auto& n: nums){\n            max_penalty = max(max_penalty, n);\n            sum += n;\n        }\n        //the max of bags is nums.size() + maxOperations\n        //the average of the ball is the theoretical min penalty\n        int min_penalty = sum / (nums.size() + maxOperations);\n        min_penalty = max(1, min_penalty); // in case of min_penalty is zero\n        \n        //binary search the real min penalty\n        while (min_penalty < max_penalty) {\n            int mid = min_penalty + (max_penalty - min_penalty) / 2;\n            \n            //if the penalty is `mid`, then how many operation we need\n            int ops = 0;\n            for (auto& n : nums){\n                if (n <= mid) continue; //no need seperation\n                ops += (n-1) / mid;\n            }\n            \n            //if the operation we need is beyoned the limitation, \n            //then we find in the large part, else find in the small part.\n            if (ops > maxOperations) {\n                min_penalty = mid + 1;\n            }else{\n                max_penalty = mid;\n            }\n        }\n        return min_penalty;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumNumberOfOperationsToMoveAllBallsToEachBox/MinimumNumberOfOperationsToMoveAllBallsToEachBox.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/\n// Author : Hao Chen\n// Date   : 2021-03-20\n\n/***************************************************************************************************** \n *\n * You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith \n * box is empty, and '1' if it contains one ball.\n * \n * In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j \n * if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\n * \n * Return an array answer of size n, where answer[i] is the minimum number of operations needed to \n * move all the balls to the ith box.\n * \n * Each answer[i] is calculated considering the initial state of the boxes.\n * \n * Example 1:\n * \n * Input: boxes = \"110\"\n * Output: [1,1,3]\n * Explanation: The answer for each box is as follows:\n * 1) First box: you will have to move one ball from the second box to the first box in one operation.\n * 2) Second box: you will have to move one ball from the first box to the second box in one operation.\n * 3) Third box: you will have to move one ball from the first box to the third box in two operations, \n * and move one ball from the second box to the third box in one operation.\n * \n * Example 2:\n * \n * Input: boxes = \"001011\"\n * Output: [11,8,5,4,3,4]\n * \n * Constraints:\n * \n * \tn == boxes.length\n * \t1 <= n <= 2000\n * \tboxes[i] is either '0' or '1'.\n ******************************************************************************************************/\n\nclass Solution {\n\npublic:\n    vector<int> minOperations(string boxes) {\n        vector<int> result(boxes.size());\n        //minOperations01(boxes, result); //128ms\n        minOperations02(boxes, result); //4s\n        return result;\n    }\n    \n    void minOperations01(string& boxes, vector<int>& result ) {\n        vector<int> balls;\n        for(int i=0; i<boxes.size(); i++) {\n            if(boxes[i] == '1') balls.push_back(i);\n        }\n        \n        for (int i=0; i<boxes.size(); i++) {\n            int steps = 0;\n            for (int j=0; j<balls.size(); j++) {\n                steps += abs(balls[j] - i);\n            }\n            result[i] = steps;\n        }\n    }\n    void minOperations02(string& boxes, vector<int>& result ) {\n        //from left to right\n        for(int i=0, ops=0, balls=0; i< boxes.size(); i++) {\n            result[i] += ops;\n            balls += (boxes[i] == '1' ? 1 : 0);\n            ops += balls;\n        }\n        //from right to left\n        for(int i=boxes.size()-1, ops=0, balls=0; i>=0; i--) {\n            result[i] += ops;\n            balls += (boxes[i] == '1' ? 1 : 0);\n            ops += balls;\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumNumberOfOperationsToReinitializeAPermutation/MinimumNumberOfOperationsToReinitializeAPermutation.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * You are given an even integer n. You initially have a permutation perm of size n where \n * perm[i] == i (0-indexed).\n * \n * In one operation, you will create a new array arr, and for each i:\n * \n * \tIf i % 2 == 0, then arr[i] = perm[i / 2].\n * \tIf i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].\n * \n * You will then assign arr to perm.\n * \n * Return the minimum non-zero number of operations you need to perform on perm to return the \n * permutation to its initial value.\n * \n * Example 1:\n * \n * Input: n = 2\n * Output: 1\n * Explanation: prem = [0,1] initially.\n * After the 1^st operation, prem = [0,1]\n * So it takes only 1 operation.\n * \n * Example 2:\n * \n * Input: n = 4\n * Output: 2\n * Explanation: prem = [0,1,2,3] initially.\n * After the 1^st operation, prem = [0,2,1,3]\n * After the 2^nd operation, prem = [0,1,2,3]\n * So it takes only 2 operations.\n * \n * Example 3:\n * \n * Input: n = 6\n * Output: 4\n * \n * Constraints:\n * \n * \t2 <= n <= 1000\n * \tn is even.\n ******************************************************************************************************/\n\nclass Solution {\nprivate: \n    bool check(vector<int>& a) {\n        for(int i=0; i<a.size(); i++) {\n            if (a[i] != i) return false;\n        }\n        return true;\n    }\npublic:\n    int reinitializePermutation(int n) {\n        vector<int> perm(n);\n        vector<int> arr(n);\n        for(int i=0; i<n; i++) {\n            perm[i] = i;\n        }\n        int cnt = 0;\n        while(1){\n            cnt++;\n            for(int i=0; i<n; i++) {\n                if (i%2==0) arr[i] = perm[i / 2];\n                else arr[i] = perm[n / 2 + (i - 1) / 2];\n            }\n            if (check(arr)) break;\n            perm = arr;\n        }\n        \n        return cnt;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumNumberOfPeopleToTeach/MinimumNumberOfPeopleToTeach.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-number-of-people-to-teach/\n// Author : Hao Chen\n// Date   : 2021-02-17\n\n/***************************************************************************************************** \n *\n * On a social network consisting of m users and some friendships between users, two users can \n * communicate with each other if they know a common language.\n * \n * You are given an integer n, an array languages, and an array friendships where:\n * \n * \tThere are n languages numbered 1 through n,\n * \tlanguages[i] is the set of languages the i​​​​​​th​​​​ user knows, and\n * \tfriendships[i] = [u​​​​​​i​​​, v​​​​​​i] denotes a friendship between the users u​​​​​​​​​​​\n * i​​​​​ and vi.\n * \n * You can choose one language and teach it to some users so that all friends can communicate with \n * each other. Return the minimum number of users you need to teach.\n * Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, \n * this doesn't guarantee that x is a friend of z.\n * \n * Example 1:\n * \n * Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\n * Output: 1\n * Explanation: You can either teach user 1 the second language or user 2 the first language.\n * \n * Example 2:\n * \n * Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\n * Output: 2\n * Explanation: Teach the third language to users 1 and 3, yielding two users to teach.\n * \n * Constraints:\n * \n * \t2 <= n <= 500\n * \tlanguages.length == m\n * \t1 <= m <= 500\n * \t1 <= languages[i].length <= n\n * \t1 <= languages[i][j] <= n\n * \t1 <= u​​​​​​i < v​​​​​​i <= languages.length\n * \t1 <= friendships.length <= 500\n * \tAll tuples (u​​​​​i, v​​​​​​i) are unique\n * \tlanguages[i] contains only unique values\n ******************************************************************************************************/\n\nclass Solution {\n\npublic:\n    bool hasLang(vector<int>& langlist, int lang){\n        for(auto& l : langlist) {\n            if (l == lang) return true;\n        }\n        return false;\n    }\n    \n    bool canComm(int u, int v, int n, vector<vector<bool>>& langs) {\n        for (int l=0; l<n; l++) {\n            if (langs[u][l] && langs[v][l]) return true;\n        }\n        return false;\n    }\n    \n    int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {\n        int persons = languages.size();\n        //use to check a person know a langauge or not\n        vector<vector<bool>> langs(persons, vector<bool>(n, false));\n        for (int p=0; p<persons; p++) {\n            for(int l=0; l<languages[p].size(); l++) {\n                langs[p][languages[p][l]-1] = true;\n            }\n        } \n        \n        int result = persons;\n        vector<vector<bool>> langToTeach(n, vector<bool>(persons, false));\n        for (int l=0; l <n; l++) {\n            int cnt = 0;\n            vector<bool> teach(persons, false);\n            for (auto& fs : friendships) {\n                int u = fs[0] - 1;\n                int v = fs[1] - 1;\n\n                if (canComm(u, v, n, langs)) continue;\n\n                if (langs[u][l]==false && teach[u]==false) {\n                    teach[u] = true; cnt++;\n                }\n                if (langs[v][l]==false && teach[v]==false) {\n                    teach[v] = true; cnt++;\n                }\n            }\n            result = min(result, cnt);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumOperationsToMakeArrayEqual/MinimumOperationsToMakeArrayEqual.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-operations-to-make-array-equal/\n// Author : Hao Chen\n// Date   : 2020-10-03\n\n/***************************************************************************************************** \n *\n * You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i \n * < n).\n * \n * In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] \n * and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements \n * of the array equal. It is guaranteed that all the elements of the array can be made equal using \n * some operations.\n * \n * Given an integer n, the length of the array. Return the minimum number of operations needed to make \n * all the elements of arr equal.\n * \n * Example 1:\n * \n * Input: n = 3\n * Output: 2\n * Explanation: arr = [1, 3, 5]\n * First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\n * In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\n * \n * Example 2:\n * \n * Input: n = 6\n * Output: 9\n * \n * Constraints:\n * \n * \t1 <= n <= 10^4\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minOperations(int n) {\n        // the sum of odd number is : n*n\n        // the sum of even number is: n*n+n\n        /* int sum = n*n; */\n\n        //calculate the average\n        /* int average = sum / n;  //actually it is n  */\n\n        //calculate the different between n and all of the odd number which less than `average`\n        //  (n - 1) + (n - 3) + (n - 5) + (n - 7) ...\n        // = m*n - (1+3+5+7+...m)   where m = n/2\n        // = m*n - m*m\n        // = (n/2)*n - (n/2)*(n/2)\n        // = n*n/2 - n*n/4\n        // = n*n/4\n\n        return n*n/4;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumOperationsToMakeTheArrayIncreasing/MinimumOperationsToMakeTheArrayIncreasing.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums (0-indexed). In one operation, you can choose an element of the \n * array and increment it by 1.\n * \n * \tFor example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].\n * \n * Return the minimum number of operations needed to make nums strictly increasing.\n * \n * An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An \n * array of length 1 is trivially strictly increasing.\n * \n * Example 1:\n * \n * Input: nums = [1,1,1]\n * Output: 3\n * Explanation: You can do the following operations:\n * 1) Increment nums[2], so nums becomes [1,1,2].\n * 2) Increment nums[1], so nums becomes [1,2,2].\n * 3) Increment nums[2], so nums becomes [1,2,3].\n * \n * Example 2:\n * \n * Input: nums = [1,5,2,4,1]\n * Output: 14\n * \n * Example 3:\n * \n * Input: nums = [8]\n * Output: 0\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 5000\n * \t1 <= nums[i] <= 10^4\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int minOperations(vector<int>& nums) {\n        int ins = 0;\n        int top = nums[0];\n        for(int i = 1; i < nums.size(); i++) {\n            if (nums[i] > top){\n                top = nums[i];\n            }else{\n                ins += (top - nums[i] + 1);\n                top++;\n            }\n        }\n        return ins;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumPathSum/minimumPathSum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/minimum-path-sum/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/***************************************************************************************************** \n *\n * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right \n * which minimizes the sum of all numbers along its path.\n * \n * Note: You can only move either down or right at any point in time.\n * \n * Example:\n * \n * Input:\n * [\n *   [1,3,1],\n *   [1,5,1],\n *   [4,2,1]\n * ]\n * Output: 7\n * Explanation: Because the path 1&rarr;3&rarr;1&rarr;1&rarr;1 minimizes the sum.\n * \n ******************************************************************************************************/\n\n#include <limits.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nint minPathSum(vector<vector<int>>& grid) {\n    for (int i=0; i<grid.size(); i++) {\n        for (int j=0; j<grid[0].size(); j++) {\n            if (i==0 && j==0) continue;\n            else if (i==0) grid[0][j] += grid[0][j-1];\n            else if (j==0) grid[i][0] += grid[i-1][j];\n            else grid[i][j] += min( grid[i-1][j], grid[i][j-1]);\n        }\n    }\n    return grid[grid.size()-1][grid[0].size()-1];\n}\n\nint main()\n{\n    int a[6][2]={{7,2},{6,6},{8,6},{8,7},{5,0},{6,0}};\n    vector< vector<int> > grid;\n    for(int i=0; i<6; i++){\n        vector<int> v;\n        for(int j=0; j<2; j++){\n            v.push_back(a[i][j]);\n        }\n        grid.push_back(v);\n    }\n\n    cout << \"minPathSum=\" << minPathSum(grid) << endl;\n\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/minimumSidewayJumps/MinimumSidewayJumps.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-sideway-jumps/\n// Author : Hao Chen\n// Date   : 2021-04-11\n\n/***************************************************************************************************** \n *\n * There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts \n * at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along \n * the way.\n * \n * You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) \n * describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no \n * obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.\n * \n * \tFor example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.\n * \n * The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle \n * on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to \n * another lane (even if they are not adjacent) at the same point if there is no obstacle on the new \n * lane.\n * \n * \tFor example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.\n * \n * Return the minimum number of side jumps the frog needs to reach any lane at point n starting from \n * lane 2 at point 0.\n * \n * Note: There will be no obstacles on points 0 and n.\n * \n * Example 1:\n * \n * Input: obstacles = [0,1,2,3,0]\n * Output: 2 \n * Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\n * Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n * \n * Example 2:\n * \n * Input: obstacles = [0,1,1,3,3,0]\n * Output: 0\n * Explanation: There are no obstacles on lane 2. No side jumps are required.\n * \n * Example 3:\n * \n * Input: obstacles = [0,2,1,0,3,0]\n * Output: 2\n * Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n * \n * Constraints:\n * \n * \tobstacles.length == n + 1\n * \t1 <= n <= 5 * 10^5\n * \t0 <= obstacles[i] <= 3\n * \tobstacles[0] == obstacles[n] == 0\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int min (int x, int y) {\n        return x < y ? x : y;\n    }\n    int min(int x, int y, int z) {\n        return min(x, min(y,z));\n    }\n    void print(vector<vector<int>>& matrix) {\n        int n = matrix.size();\n        int m = matrix[0].size();\n        \n        for(int i=0; i<m; i++) {\n            for (int j=0; j<n-1; j++){\n                if (matrix[j][i] == n) {\n                    cout << setw(2) << \"X\"<<\",\";\n                } else {\n                    cout << setw(2) <<matrix[j][i] << \",\";\n                }\n            }\n            cout << matrix[n-1][i] << endl;\n        }\n    }\npublic:\n    int minSideJumps(vector<int>& obstacles) {\n        int n = obstacles.size();\n        vector<vector<int>> dp(n, vector(3,0));\n        dp[0][0] = dp[0][2] = 1;\n        \n        for(int i = 1; i < n; i++){\n            \n            dp[i][0] = dp[i-1][0];\n            dp[i][1] = dp[i-1][1];\n            dp[i][2] = dp[i-1][2];\n            if (obstacles[i] > 0 ) dp[i][obstacles[i]-1] = n;\n            \n            if (obstacles[i]-1 != 0 ) dp[i][0] = min(dp[i-1][0], dp[i][1]+1, dp[i][2]+1);     \n            if (obstacles[i]-1 != 1 ) dp[i][1] = min(dp[i][0]+1, dp[i-1][1], dp[i][2]+1);\n            if (obstacles[i]-1 != 2 ) dp[i][2] = min(dp[i][0]+1, dp[i][1]+1, dp[i-1][2]);\n \n        }\n        //print(dp);\n        //cout << endl;\n        return min(dp[n-1][0], dp[n-1][1], dp[n-1][2]);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumSizeSubarraySum/MinimumSizeSubarraySum.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-size-subarray-sum/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Given an array of n positive integers and a positive integer s, find the minimal length of a subarray \n * of which the sum ≥ s. If there isn't one, return 0 instead.\n * \n * For example, given the array [2,3,1,2,4,3] and s = 7,\n * the subarray [4,3] has the minimal length under the problem constraint.\n * \n * click to show more practice.\n * \n * More practice:\n * \n * If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).\n * \n * Credits:Special thanks to @Freezen for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    int minSubArrayLen(int s, vector<int>& nums) {\n        int min = nums.size();\n        int begin=0, end=0;\n        int sum = 0;\n        bool has = false;\n        \n        for (int i=0; i<nums.size(); i++, end++){\n            \n            sum += nums[i];\n            \n            while (sum >= s && begin <= end) {\n                //the 1 is minial length, just return\n                if (begin == end) return 1;\n                \n                if (end-begin+1 < min) {\n                    min = end - begin + 1;\n                    has = true;\n                }\n                //move the begin\n                sum -= nums[begin++];\n            }\n \n        }\n        \n        return has ? min : 0; \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumSpeedToArriveOnTime/MinimumSpeedToArriveOnTime.cpp",
    "content": "// Source : https://leetcode.com/problems/minimum-speed-to-arrive-on-time/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * You are given a floating-point number hour, representing the amount of time you have to reach the \n * office. To commute to the office, you must take n trains in sequential order. You are also given an \n * integer array dist of length n, where dist[i] describes the distance (in kilometers) of the i^th \n * train ride.\n * \n * Each train can only depart at an integer hour, so you may need to wait in between each train ride.\n * \n * \tFor example, if the 1^st train ride takes 1.5 hours, you must wait for an additional 0.5 \n * hours before you can depart on the 2^nd train ride at the 2 hour mark.\n * \n * Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel \n * at for you to reach the office on time, or -1 if it is impossible to be on time.\n * \n * Tests are generated such that the answer will not exceed 10^7 and hour will have at most two digits \n * after the decimal point.\n * \n * Example 1:\n * \n * Input: dist = [1,3,2], hour = 6\n * Output: 1\n * Explanation: At speed 1:\n * - The first train ride takes 1/1 = 1 hour.\n * - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second \n * train takes 3/1 = 3 hours.\n * - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third \n * train takes 2/1 = 2 hours.\n * - You will arrive at exactly the 6 hour mark.\n * \n * Example 2:\n * \n * Input: dist = [1,3,2], hour = 2.7\n * Output: 3\n * Explanation: At speed 3:\n * - The first train ride takes 1/3 = 0.33333 hours.\n * - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train \n * ride takes 3/3 = 1 hour.\n * - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third \n * train takes 2/3 = 0.66667 hours.\n * - You will arrive at the 2.66667 hour mark.\n * \n * Example 3:\n * \n * Input: dist = [1,3,2], hour = 1.9\n * Output: -1\n * Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n * \n * Constraints:\n * \n * \tn == dist.length\n * \t1 <= n <= 10^5\n * \t1 <= dist[i] <= 10^5\n * \t1 <= hour <= 10^9\n * \tThere will be at most two digits after the decimal point in hour.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool verify(vector<int>& dist, double hour, int speed) {\n        double t = 0;\n        int n = dist.size();\n        for (int i=0; i<n-1; i++){\n            t += (dist[i] + speed -1) / speed;\n        }\n        t += (double)dist[n-1]/speed;\n        return t <= hour;\n    }\n    \n    int minSpeedOnTime(vector<int>& dist, double hour) {\n        int n = dist.size();\n        if (hour <= n-1) return -1;\n        \n        int low = 1, high = 1e7;\n        while (low < high) {\n            int mid = low + (high - low) / 2;\n            if (verify(dist, hour, mid)) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/minimum-window-substring/\n// Author : Hao Chen\n// Date   : 2014-07-22\n\n/********************************************************************************** \n* \n* Given a string S and a string T, find the minimum window in S which will \n* contain all the characters in T in complexity O(n).\n* \n* For example,\n* S = \"ADOBECODEBANC\"\n* T = \"ABC\"\n* \n* Minimum window is \"BANC\".\n* \n* Note:\n*\n* > If there is no such window in S that covers all characters in T, \n*   return the emtpy string \"\".\n* \n* > If there are multiple such windows, you are guaranteed that there \n*   will always be only one unique minimum window in S.\n* \n*               \n**********************************************************************************/\n\n#include <string.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#define INT_MAX      2147483647\n\nstring minWindow(string s, string t) {\n    string win;\n    if (s.size()<=0 || t.size()<=0 || t.size() > s.size()) return win;\n    /*\n     * Declare two \"hash map\" for ASCII chars\n     *   window[]: represents the char found in string S\n     *   dict[]: stores the chars in string T\n     */    \n    const int MAX_CHARS = 256;\n    int window[MAX_CHARS], dict[MAX_CHARS];\n\n    const int NOT_EXISTED   = -1;\n    const int NOT_FOUND     =  0;\n    memset(dict, NOT_EXISTED, sizeof(dict));\n    memset(window, NOT_EXISTED, sizeof(window));\n\n    /* \n     *  Go through the T, and inital the dict[] and window[] \n     *  Notes: a same char can be appeared multiple times.\n     */\n    for(int i=0; i<t.size(); i++) {\n        dict[t[i]]==NOT_EXISTED ? dict[t[i]]=1 : dict[t[i]]++ ; \n        window[t[i]] = NOT_FOUND; \n    }\n\n    int start =-1;\n    int winSize = INT_MAX;\n    int letterFound = 0;\n    int left = 0;\n\n    for(int right=0; right<s.size(); right++) {\n        if ( dict[s[right]] == NOT_EXISTED ){\n            continue;\n        }\n\n        /* if s[i] is existed in `t` */ \n        char chr = s[right];\n        window[chr]++;\n\n        /* if one char has been found enough times, then do not do letterFound++ */\n        if (window[chr] <= dict[chr]) {\n            letterFound++;\n        }\n\n        if ( letterFound >= t.size() ) {\n            /* \n             * Find the left of the window - try to make the window smaller\n             * 1) windows[S[left]] == NOT_EXISTED  ===> the char at the `left` is not in T\n             * 2) window[S[left]] > dict[S[left]]   ===> a same char appeared more than excepted.\n             */\n            char chl = s[left];\n            while ( window[chl] == NOT_EXISTED || window[chl] > dict[chl] ) { \n                if (dict[chl] != NOT_EXISTED  ) {\n                    //move the left of window\n                    window[chl]--; \n                    // reduce the number of letters found\n                    if (window[chl] < dict[chl] ) letterFound--;\n                }\n                chl = s[++left];\n            }\n\n            /* Calculate the minimized window size */\n            if(winSize > right - left + 1){\n                start = left;\n                winSize = right - left + 1;\n            }\n\n        }\n    }\n\n    if (start>=0 && winSize>0) {\n        win = s.substr(start, winSize);\n    }\n    return win;\n}\n\nint main(int argc, char**argv)\n{\n    string S = \"ADOBECODEBANC\";\n    string T = \"ABC\";\n    if (argc>2){\n        S = argv[1];\n        T = argv[2];\n    }\n    cout << \"S = \\\"\" << S << \"\\\"  T=\\\"\" << T << \"\\\"\" <<endl;\n    cout << minWindow(S, T) << endl;\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/mirrorReflection/MirrorReflection.cpp",
    "content": "// Source : https://leetcode.com/problems/mirror-reflection/description/\n// Author : Hao Chen\n// Date   : 2018-06-27\n\n/*************************************************************************************** \n *\n * There is a special square room with mirrors on each of the four walls.  Except for \n * the southwest corner, there are receptors on each of the remaining corners, numbered \n * 0, 1, and 2.\n * \n * The square room has walls of length p, and a laser ray from the southwest corner \n * first meets the east wall at a distance q from the 0th receptor.\n * \n * Return the number of the receptor that the ray meets first.  (It is guaranteed that \n * the ray will meet a receptor eventually.)\n * \n *  \n * \n * \n * Example 1:\n * \n * \n * Input: p = 2, q = 1\n * Output: 2\n * Explanation: The ray meets receptor 2 the first time it gets reflected back to the \n * left wall.\n * \n * \n * \n * \n * Note:\n * \n * \n * \t1 <= p <= 1000\n * \t0 <= q <= p\n * \n ***************************************************************************************/\n\n/*\n *  Solution \n *  --------\n *  \n *  We know the following things:\n *  1）every reflection will increase the step of `q`.  \n *  2) when reach the top, the reflection would go down, when reach the bottom the reflection would go up.\n *  \n *  So, we can image if there have two walls, left one and right one, then the reflection can go up instanstly, \n *\n *   - the reflection points on left wall would be even times of `q`.\n *   - the reflection points on right wall would be odd times of `q`.\n *\n *  And in the right wall, the receptors `#0` would be the times of `2p`.\n *\n *  So, we need find the least common multiple of `p` and `q`, then we can have the answer.    \n */\n\n\nclass Solution {\nprivate:\n    //GCD -  greatest common divisor  最大公因数\n    int greatestCommonDivisor (int a, int b) {\n        if(b) while((a %= b) && (b %= a));\n        return a + b;\n    }\n    //LCM - least common multiple 最小公倍数\n    int leastCommonMultiple(int a, int b) {\n        return a * b / greatestCommonDivisor(a, b);\n    }\npublic:\n    int mirrorReflection(int p, int q) {\n        int lcm = leastCommonMultiple(p, q);\n        if (lcm % (2*p) == 0 ) return 0;\n        \n        int nq = lcm / q; \n        \n        if (nq % 2 == 0 ) return 2;\n        return 1;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/missingNumber/MissingNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/missing-number/\n// Author : Hao Chen\n// Date   : 2015-10-22\n\n/*************************************************************************************** \n *\n * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the \n * one that is missing from the array.\n * \n * For example,\n * Given nums = [0, 1, 3] return 2.\n * \n * Note:\n * Your algorithm should run in linear runtime complexity. Could you implement it using \n * only constant extra space complexity?\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    // This problem can be converted to the classic problem --\n    //    `There is an array, all of numbers except one appears twice, and that one only appears once`\n    // It means, we can combin two arrays together, one is [1..n], another one is `nums`.\n    // Then, you know, we can use the XOR solve this problem.\n    \n    int missingNumber01(vector<int>& nums) {\n        int result = 0;\n        for(int i=0; i<nums.size(); i++){\n            result ^=  nums[i];\n        }\n        for(int i=1; i<=nums.size(); i++){\n            result ^=(i);\n        }\n        return result;\n    }\n    \n    // We can simplify the previous solution as below\n    int missingNumber02(vector<int>& nums) {\n        int result = 0;\n        for(int i=0; i<nums.size(); i++){\n            result = result ^ (i+1) ^ nums[i];\n        }\n        return result;\n    }\n    \n    int missingNumber(vector<int>& nums) {\n        //By Leetcode running result, they all are same performance\n        return missingNumber02(nums); //36ms\n        return missingNumber01(nums); //36ms\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/missingRanges/missingRanges.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/missing-ranges/\n// Author : Hao Chen\n// Date   : 2014-12-11\n\n/********************************************************************************** \n * \n * Given a sorted integer array where the range of elements are [lower, upper] inclusive, \n * return its missing ranges.\n *\n * For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, \n * return [\"2\", \"4->49\", \"51->74\", \"76->99\"]. \n * \n **********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <iterator>\nusing namespace std;\n\n\nstring& makeRange(int lo, int hi){\n    static string result;\n    result=\"\";\n    stringstream ss;\n    if (lo != hi){\n        ss << lo << \"->\" << hi;\n    }else{\n        ss << lo;\n    }\n    ss >> result;\n    return result;\n}\n\n\nvector<string> findMissingRanges(int A[], int n, int lower, int upper) {\n\n    vector<string> result;\n\n    if ( n<=0 ) {\n        result.push_back(makeRange(lower, upper));\n        return result;\n    }\n\n    if (lower < A[0]){\n        result.push_back(makeRange(lower, A[0]-1 < upper ? A[0]-1 : upper));\n    }\n\n    for(int i=0; i<n-1; i++){\n        if ( A[i] + 1 == A[i+1] ) {\n            continue;\n        }\n        result.push_back(makeRange(A[i]+1, A[i+1]-1));\n    }\n\n    if (upper > A[n-1]){\n        result.push_back(makeRange(A[n-1]+1, upper));\n    }\n\n    return result;\n}\n\n\nvoid printVector(vector<string> v){\n    cout << \"[\";\n    int i=0;\n    for(; i<v.size(); i++){\n        cout << \"\\\"\" << v[i] << \"\\\"\" << (i==v.size()-1 ? \"\":\", \" );\n    }\n    cout << \"]\" <<endl;\n}\n\n\nvector<int> string2Array(string s){\n\n\n    vector<string> strarr;\n    istringstream iss(s);\n    copy(istream_iterator<string>(iss),\n            istream_iterator<string>(),\n            back_inserter(strarr));\n\n    vector<int> result;\n    for (int i=0; i<strarr.size(); i++){\n        result.push_back(atoi(strarr[i].c_str()));\n    }\n\n    return result;\n}\n\nint main(int argc, char**argv)\n{\n    int A[] = {0, 1, 3, 50, 75};\n    int lo = 0;\n    int hi = 99;\n\n    vector<string> result = findMissingRanges(A, sizeof(A)/sizeof(A[0]), lo ,hi);\n\n    printVector(result);    \n\n\n    //usage: ./missingRanges 0 9 \"3 5 7\"\n    if (argc>3){\n        lo = atoi(argv[1]);\n        hi = atoi(argv[2]);\n        vector<int> a;\n        a = string2Array(argv[3]);\n\n        int *pA = &a[0];\n        result = findMissingRanges(pA, a.size(), lo, hi);\n        printVector(result);    \n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/mostCommonWord/MostCommonWord.cpp",
    "content": "// Source : https://leetcode.com/problems/most-common-word/\n// Author : Hao Chen\n// Date   : 2018-04-19\n\n/*************************************************************************************** \n *\n * Given a paragraph and a list of banned words, return the most frequent word that is \n * not in the list of banned words.  It is guaranteed there is at least one word that \n * isn't banned, and that the answer is unique.\n * \n * Words in the list of banned words are given in lowercase, and free of punctuation.  \n * Words in the paragraph are not case sensitive.  The answer is in lowercase.\n * \n * \n * Example:\n * Input: \n * paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\"\n * banned = [\"hit\"]\n * Output: \"ball\"\n * Explanation: \n * \"hit\" occurs 3 times, but it is a banned word.\n * \"ball\" occurs twice (and no other word does), so it is the most frequent non-banned \n * word in the paragraph. \n * Note that words in the paragraph are not case sensitive,\n * that punctuation is ignored (even if adjacent to words, such as \"ball,\"), \n * and that \"hit\" isn't the answer even though it occurs more because it is banned.\n * \n * \n *  \n * \n * Note: \n * \n * \n * \t1 <= paragraph.length <= 1000.\n * \t1 <= banned.length <= 100.\n * \t1 <= banned[i].length <= 10.\n * \tThe answer is unique, and written in lowercase (even if its occurrences in \n * paragraph may have uppercase symbols, and even if it is a proper noun.)\n * \tparagraph only consists of letters, spaces, or the punctuation symbols !?',;.\n * \tDifferent words in paragraph are always separated by a space.\n * \tThere are no hyphens or hyphenated words.\n * \tWords only consist of letters, never apostrophes or other punctuation \n * symbols.\n * \n * \n *  \n ***************************************************************************************/\n\n\nclass Solution {\nprivate:\n    bool isLetter(char c) {\n        return c >= 'a' && c <= 'z';\n    }\npublic:\n    string mostCommonWord(string paragraph, vector<string>& banned) {\n        unordered_map<string, int> banned_map, words_map;\n        for (auto w:banned) {\n            banned_map[w]++;\n        }\n        \n        //conert the string to lower case.\n        transform(paragraph.begin(), paragraph.end(), paragraph.begin(), ::tolower);\n        \n        //transfer the symbols to space.\n        for (int i=0; i<paragraph.size(); i++) {\n            if ( !isLetter(paragraph[i]) ){\n                paragraph[i] = ' ';\n            }\n        }\n        string word;\n        for(auto c:paragraph) {\n            if (isLetter(c)) { \n                word += c;\n            }else{\n                if ( word.size()>0 ) {\n                    words_map[word]++;\n                }\n                word=\"\";\n            }\n        }\n        if ( word.size()>0 ) words_map[word]++;\n        \n        string result;\n        int max_cnt=0;\n        // go through the words_map\n        for (auto const& w : words_map) {\n            \n            if ( banned_map.find(w.first) != banned_map.end() ) {\n                continue;\n            }\n            if (max_cnt < w.second) {\n                result = w.first;\n                max_cnt = w.second;\n            }\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/moveZeroes/moveZeroes.cpp",
    "content": "// Source : https://leetcode.com/problems/move-zeroes/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-10-21\n\n/*************************************************************************************** \n *\n * Given an array nums, write a function to move all 0's to the end of it while \n * maintaining the relative order of the non-zero elements.\n *\n * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should\n * be [1, 3, 12, 0, 0].\n * \n * Note:\n * You must do this in-place without making a copy of the array.\n * Minimize the total number of operations.\n * \n * Credits:\n * Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.\n *               \n ***************************************************************************************/\n\n\n\nclass Solution {\npublic:\n    /* \n     * Solution (Calinescu Valentin)\n     * ==============================\n     *\n     * One solution would be to store the position of the next non-zero element of the array.\n     * Every position of the array, starting with position 0, must store this next non-zero\n     * element until we can no more do that, case in which we need to add the remaining zeros\n     * that we skipped.\n     * \n     * \n     * Time Complexity: O(N)\n     * Space Complexity: O(1)\n     * \n     */\n    void moveZeroes(vector<int>& nums) {\n        int i = 0, poz = 0;\n        for(i = 0; i < nums.size() && poz < nums.size(); i++)\n        {\n                while(poz < nums.size() && nums[poz] == 0)\n                    poz++;\n                if(poz < nums.size())\n                    nums[i] = nums[poz];\n                else\n                    i--; // we need 0 on position i, but i is increasing one last time\n                poz++;\n        }\n        for(; i < nums.size(); i++)\n            nums[i] = 0;\n    }\n\n\n\n    /*\n     * Another implemtation which is easy to understand (Hao Chen)\n     * ===========================================================\n     *\n     * We have two pointers to travel the array, assume they named `p1` and `p2`.\n     * \n     *   1) `p1` points the tail of current arrays without any ZEROs.\n     *   2) `p2` points the head of the rest array which skips the ZEROs.\n     * \n     * Then we can just simply move the item from `p2` to `p1`.\n     *\n     */\n    void moveZeroes(vector<int>& nums) {\n        int p1=0, p2=0;\n\n        // Find the first ZERO, where is the tail of the array.\n        // (Notes: we can simply remove this!)\n        for (; p1<nums.size() && nums[p1]!=0; p1++);\n        \n        // copy the item from p2 to p1, and skip the ZERO\n        for (p2=p1; p2<nums.size(); p2++) {\n            if ( nums[p2] == 0 ) continue;\n            nums[p1++] = nums[p2]; \n        }    \n        \n        //set ZERO for rest items \n        while ( p1<nums.size() ) nums[p1++] = 0;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/multiplyStrings/multiplyStrings.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/multiply-strings/\n// Author : Hao Chen\n// Date   : 2014-07-18\n\n/********************************************************************************** \n* \n* Given two numbers represented as strings, return multiplication of the numbers as a string.\n* \n* Note: The numbers can be arbitrarily large and are non-negative.\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nstring multiply(string& num, char ch){\n    int n = ch - '0';\n    string s;\n    int carry = 0;\n    int x;\n    for(int i=num.size()-1; i>=0; i--){\n        x = (num[i]-'0') * n + carry;\n        carry = x/10;\n        s.insert(s.begin(), x%10+'0'); \n    }\n    if (carry>0) {\n        s.insert(s.begin(), carry+'0');\n    }\n    return s;\n}\n\nstring strPlus(string& num1, string& num2) {\n    string s;\n    int carry=0;\n    int x;\n    int n1 = num1.size(); \n    int n2 = num2.size(); \n    \n    int i, j;\n    for(i=n1-1, j=n2-1; i>=0 || j>=0; i--, j--){\n        int x1 = i>=0 ?  num1[i]-'0' : 0;\n        int x2 = j>=0 ?  num2[j]-'0' : 0;\n        x = x1 + x2 + carry; \n        carry = x/10;\n        s.insert(s.begin(), x%10+'0');\n    }\n    if (carry>0) {\n        s.insert(s.begin(), carry+'0');\n    }\n    return s;\n}\n\nstring multiply(string num1, string num2) {\n\n    if (num1.size()<=0 || num2.size()<=0) return \"\";\n\n    int shift=0;\n    string result=\"0\";\n    for (int i=num1.size()-1; i>=0; i--) {\n        string s = multiply(num2, num1[i]);        \n        for(int j=0; j<shift; j++){\n            s.insert(s.end(), '0');\n        }\n        result = strPlus(result, s);\n        shift++;\n    }\n    //check if it is zero\n    if (result[0]=='0') return \"0\";\n    return result;\n}\n\n\n/********************************************************************************** \n *                            Another implementation\n **********************************************************************************/\n\nclass Solution {\n    public:\n\n        string strPlus(string& num1, string& num2) {\n            if (num1.size()==0) return num2;\n            if (num2.size()==0) return num1;\n\n            if ( num1.size() < num2.size() ) {\n                swap(num1, num2);\n            }\n\n            string s;\n            int carry=0;\n            int x;\n            for (int i=num1.size()-1, j=num2.size()-1; i>=0; i--, j--) {\n                x = num1[i]-'0' + carry;\n                if(j>=0){\n                    x += num2[j]-'0';\n                }\n                s.insert(s.begin(), x%10+'0');\n                carry = x/10;\n            }\n            if (carry>0) {\n                s.insert(s.begin(), carry+'0');\n            }\n\n            return s;\n        }\n\n\n        string multiply(string num1, string num2) {\n\n            if (num1.size()<=0 || num2.size()<=0) return \"\";\n\n            string result;\n            for ( int i=num1.size()-1; i>=0; i--) {\n                int carry = 0;\n                string val;\n                for( int j=num2.size()-1; j>=0; j--) {\n                    int v = (num2[j]-'0') * (num1[i]-'0') + carry;\n                    val.insert(val.begin(), v%10+'0');\n                    carry = v/10;\n                }\n                if (carry) val.insert(val.begin(), carry+'0');\n                for (unsigned int j=i; j<num1.size()-1; j++) {\n                    val.push_back('0');\n                }\n                result = strPlus(result, val);\n            }\n\n            //check if it is zero\n            if (result[0]=='0') return \"0\";\n            return result;\n\n        }\n};\n\n\n\nint main(int argc, char**argv)\n{\n    string s1=\"20\";\n    string s2=\"25\";\n    if (argc>2){\n        s1 = argv[1];\n        s2 = argv[2];\n    }\n    cout << s1 << \" * \" << s2 << \" = \" << multiply(s1, s2) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/nQueens/nQueuens.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/n-queens-ii/\n// Author : Hao Chen\n// Date   : 2014-08-22\n\n/********************************************************************************** \n* \n* Follow up for N-Queens problem.\n* \n* Now, instead outputting board configurations, return the total number of distinct solutions.\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nint totalNQueens(int n); \nvoid solveNQueensRecursive(int n, int currentRow, vector<int>& solution, int& result); \nbool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn); \n\n\nint totalNQueens(int n) {\n    int result=0;\n    vector<int> solution(n);\n\n    solveNQueensRecursive(n, 0, solution, result);\n\n    return result;    \n}\n\n// the solution is same as the \"N Queens\" problem.\nvoid solveNQueensRecursive(int n, int currentRow, vector<int>& solution, int& result) {\n\n    for (int i = 0; i < n; i++) {\n        if (isValid(i, currentRow, solution) ) {\n            if (currentRow+1 == n){\n                result++;\n                continue;\n            }\n            solution[currentRow] = i;\n            solveNQueensRecursive(n, currentRow+1, solution, result);\n        }\n    } \n}\n\n\nbool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn) {\n\n    for(int i=0; i<attemptedRow; i++) {\n        if (attemptedColumn == queenInColumn[i]  || \n            abs(attemptedColumn - queenInColumn[i]) == abs(attemptedRow - i)) {\n            return false;\n        } \n    }\n    return true;\n}\n\n\n\nint main(int argc, char** argv)\n{\n    int n = 8;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    \n    int result = totalNQueens(n);\n    \n    cout << n << \" Queens, total = \" << result << endl;\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/nQueens/nQueuens.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/n-queens/\n// Author : Hao Chen\n// Date   : 2014-08-22\n\n/********************************************************************************** \n* \n* The n-queens puzzle is the problem of placing n queens on an n×n chessboard \n* such that no two queens attack each other.\n* \n* Given an integer n, return all distinct solutions to the n-queens puzzle.\n* \n* Each solution contains a distinct board configuration of the n-queens' placement, \n* where 'Q' and '.' both indicate a queen and an empty space respectively.\n* \n* For example,\n* There exist two distinct solutions to the 4-queens puzzle:\n* \n* [\n*  [\".Q..\",  // Solution 1\n*   \"...Q\",\n*   \"Q...\",\n*   \"..Q.\"],\n* \n*  [\"..Q.\",  // Solution 2\n*   \"Q...\",\n*   \"...Q\",\n*   \".Q..\"]\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nvector< vector<string> > solveNQueens(int n); \nvoid solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result); \nbool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn); \n\n\nvector< vector<string> > solveNQueens(int n) {\n    vector< vector<string> > result;\n    vector<int> solution(n);\n\n    solveNQueensRecursive(n, 0, solution, result);\n\n    return result;    \n}\n\n//The following recursion is easy to understand. Nothing's tricky.\n//  1) recursively find all of possible columns row by row.\n//  2) solution[] array only stores the columns index. `solution[row] = col;` \nvoid solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result) {\n    //if no more row need to do, shape the result\n    if (currentRow == n){\n        vector<string> s;\n        vector<string> s(n, string(n, '.'));\n        for (int row = 0; row < n; row++) {\n            s[row][solution[row]] = 'Q';\n        }\n        result.push_back(s);\n        return;\n    }\n\n    //for each column\n    for (int col = 0; col < n; col++) {\n        //if the current column is valid\n        if (isValid(col, currentRow, solution) ) {\n            //place the Queue\n            solution[currentRow] = col;\n            //recursively put the Queen in next row\n            solveNQueensRecursive(n, currentRow+1, solution, result);\n        }\n    } \n}\n\n//Attempting to put the Queen into [row, col], check it is valid or not\n//Notes: \n//  1) we just checking the Column not Row, because the row cannot be conflicted\n//  2) to check the diagonal, we just check |x'-x| == |y'-y|, (x',y') is a Queen will be placed\nbool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn) {\n\n    for(int i=0; i<attemptedRow; i++) {\n        if (attemptedColumn == queenInColumn[i]  || \n            abs(attemptedColumn - queenInColumn[i]) == abs(attemptedRow - i)) {\n            return false;\n        } \n    }\n    return true;\n}\n\n\n\n\n\nvoid printMatrix(vector< vector<string> >& matrix ){\n    for (int i = 0; i < matrix.size(); i++) {\n        cout << \"-----------\" << endl;\n        for (int j = 0; j < matrix[i].size(); j++) {\n            cout << matrix[i][j] << endl;\n        }\n    }\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 8;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    \n    vector< vector<string> > result = solveNQueens(n);\n    printMatrix(result);\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/nRepeatedElementInSize2NArray/N-Repeated-Element-in-Size-2N-Array.cpp",
    "content": "// Source : https://leetcode.com/problems/n-repeated-element-in-size-2n-array/\n// Author : Manu Gond\n// Date   : 2019-10-06\n\n/***************************************************************************************************** \n*\tIn a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.\n*\t\n*\tReturn the element repeated N times.\n*\t\n*\t \n*\t\n*\tExample 1:\n*\t\n*\tInput: [1,2,3,3]\n*\tOutput: 3\n*\tExample 2:\n*\t\n*\tInput: [2,1,2,5,3,2]\n*\tOutput: 2\n*\tExample 3:\n*\t\n*\tInput: [5,1,5,2,5,3,5,4]\n*\tOutput: 5\n*\t \n*\t\n*\tNote:\n*\t\n*\t4 <= A.length <= 10000\n*\t0 <= A[i] < 10000\n*\tA.length is even\n ******************************************************************************************************/\n \n class Solution {\npublic:\n    int repeatedNTimes(vector<int>& A) {\n        map<int,int>myMap;\n        for(int i=0;i<A.size();i++){\n            myMap[A[i]]++;\n        }\n        for(auto x:myMap){\n            if((x.second)==(A.size()/2)){\n                return x.first;\n            }\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/nextPermutation/nextPermutation.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/next-permutation/\n// Author : Hao Chen\n// Date   : 2014-08-21\n\n/********************************************************************************** \n* \n* Implement next permutation, which rearranges numbers into the lexicographically next \n* greater permutation of numbers.\n* \n* If such arrangement is not possible, it must rearrange it as the lowest possible order \n* (ie, sorted in ascending order).\n* \n* The replacement must be in-place, do not allocate extra memory.\n* \n* Here are some examples. Inputs are in the left-hand column and its corresponding outputs \n* are in the right-hand column.\n*\n*   1,2,3 → 1,3,2\n*   3,2,1 → 1,2,3\n*   1,1,5 → 1,5,1\n*               \n**********************************************************************************/\n\n/*\n * Take a look the following continuous permutation, can you find the patern?\n *\n *    1 2 3 4\n *    1 2 4 3\n *    1 3 2 4\n *    1 3 4 2\n *    1 4 2 3\n *    1 4 3 2\n *    2 1 3 4\n *    ...\n *\n * The pattern can be descripted as below:\n *\n *    1) from n-1 to 0, find the first place [i-1] which num[i-1] < num[i]\n *    2) from n-1 to i, find the first number from n-1 to i which >= num[i-1]\n *    3) swap the 2) num with the num[i-1]\n *    4) sort the sub-array [i, n) //actuall sort is fine as well\n * \n * For example:\n * \n *     1 4 3 2   <-- 1) find the first place which num[i-1] < num[i]\n *     ^\n * \n *     1 4 3 2   <-- 2) find the first number from n-1 to i which >= num[i-1]\n *     ^     ^  \n * \n *     2 4 3 1   <-- 3) swap them\n *     ^     ^\n * \n *     2 4 3 1   <-- 4) sort\n *       ^   ^\n *\n *     2 1 3 4   \n * \n * Edge Case:\n *\n *     4 3 2 1, the next permutation is 1 2 3 4\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\nvoid nextPermutation(vector<int> &num) {\n\n    if(num.size()<=1) return;\n\n    for(int i=num.size()-1; i>0; i--) {\n        if (num[i-1] < num[i]){\n            int j = num.size()-1;\n            while( num[i-1] >= num[j]) {\n                //pass;\n                j--;\n            }\n            int tmp = num[j];\n            num[j] = num[i-1];\n            num[i-1] = tmp;\n            //sort works as well\n            //sort(num.begin()+i, num.end()); \n            reverse(num.begin()+i, num.end()); \n            return; \n        }\n        //edge case: 4 3 2 1\n        if (i == 1 ){\n            //sort works as well\n            //sort(num.begin(), num.end());\n            reverse(num.begin(), num.end());\n            return;\n        }\n    }\n\n}\n\nvoid printVector(vector<int> &num) {\n    for(int i=0; i<num.size(); i++) {\n        cout << num[i] << \" \";\n    } \n    cout <<endl;\n}\nbool isBeginVector(vector<int> &num) {\n    for(int i=0; i<num.size(); i++) {\n        if(num[i] != i+1) {\n            return false;\n        }\n    } \n    return true;\n}\n\nint main(int argc, char** argv)\n{\n    int n = 4;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector<int> num;\n    for(int i=1; i<=n; i++){\n        num.push_back(i);\n    }\n    \n    while(true){\n        printVector(num);\n        nextPermutation(num);\n        if(isBeginVector(num)){\n            break;\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/nimGame/nimGame.cpp",
    "content": "// Source : https://leetcode.com/problems/nim-game/\n// Author : Calinescu Valentin\n// Date   : 2015-10-19\n\n/*************************************************************************************** \n *\n * You are playing the following Nim Game with your friend: There is a heap of stones \n * on the table, each time one of you take turns to remove 1 to 3 stones. The one who \n * removes the last stone will be the winner. You will take the first turn to remove \n * the stones.\n * \n * Both of you are very clever and have optimal strategies for the game. Write a \n * function to determine whether you can win the game given the number of stones in the \n * heap.\n * \n * For example, if there are 4 stones in the heap, then you will never win the game: no \n * matter 1, 2, or 3 stones you remove, the last stone will always be removed by your \n * friend.\n * \n *   If there are 5 stones in the heap, could you figure out a way to remove the stones \n * such that you will always be the winner? \n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\n\n\n/* \n * Solutions\n * =========\n *\n * Let's look at the example:\n * \n *    0 stones - false\n *    1 stone - true\n *    2 stones - true\n *    3 stones - true\n *    4 stones - false\n * \n * We notice that all we need for a position to be true is to get the opponent in a position \n * that is false. With 1, 2 and 3 you can take 1, 2 and 3 stones respectively to force your \n * opponent into having 0 stones, a position where he cannot win. No matter how many stones \n * we take from 4 we cannot \n *\n * force the opponent into a losing positon, so position 4 becomes a losing position. \n * Let's take a look at the next 4 positions:\n * \n *     5 stones - true\n *     6 stones - true\n *     7 stones - true\n *     8 stones - false\n * \n * With 5, 6 and 7 stones we can take 1, 2 and 3 stones respectively to force the opponent into \n * position 4. Position 8 is a losing one because we can only force the opponent into winning \n * positions. We notice that this group of 4 positions can repeat itself indefinitely, because \n * we only need the previous 3 positions to judge whether a position is winning or losing. \n *\n * Thus we can see the pattern:\n * \n *     n % 4 == 0 - false\n *     n % 4 != 0 - true\n * \n */\n\nclass Solution {\npublic:\n    bool canWinNim(int n) {\n        return !(n % 4 == 0);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/nthDigit/NthDigit.cpp",
    "content": "// Source : https://leetcode.com/problems/nth-digit/\n// Author : Hao Chen\n// Date   : 2016-11-05\n\n/*************************************************************************************** \n *\n * Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \n * 11, ... \n * \n * Note:\n * n is positive and will fit within the range of a 32-bit signed integer (n 31).\n * \n * Example 1:\n * \n * Input:\n * 3\n * \n * Output:\n * 3\n * \n * Example 2:\n * \n * Input:\n * 11\n * \n * Output:\n * 0\n * \n * Explanation:\n * The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which \n * is part of the number 10.\n ***************************************************************************************/\n\n\n#include <cmath>\nusing namespace std;\n\nclass Solution {\npublic:\n    int findNthDigit(int n) {\n        \n        // We can see the following pattern:\n        //\n        // 1, 2, .... 9 : there are 9 * 1 digits.\n        // 10, 11, ..., 99: there are 90 * 2 digits. \n        // 101, 102, 103, ..., 999:  there are 900 * 3.\n        // ...\n        \n        \n        //we can count the digits with the above pattern\n        long digits_cnt = 0;\n        long digits_cnt_prev = 0;\n        int base = 0;\n        for ( ; digits_cnt < n; base++) {\n            digits_cnt_prev = digits_cnt;\n            digits_cnt = digits_cnt +  9 * pow(10 , base) * ( base + 1 );\n        }\n        \n        \n        // Now, we got `digits_cnt_prev`, `digits_cnt` and `base`\n        //\n        //   For examples: \n        //      n = 20;    digits_cnt_prev = 9,            digits_cnt = 9+90*2 = 189,         base = 2;\n        //      n = 500;   digits_cnt_prev = 9+90*2 = 189, digits_cnt = 9+90*2+900*3 = 2889,  base = 3;\n        //      n = 2000;  digits_cnt_prev = 9+90*2 = 189, digits_cnt = 9+90*2+900*3 = 2889,  base = 3;\n        //\n        // It means, we found the range where the number it is\n        //     n = 20,  the number located in the range 10 -- 99\n        //     n = 500, the number located in the range 100 - 999\n        //\n        // and we can use `digits_cnt_prev` to know the previous rangs produce how many digits.\n        //     n = 20, the previous ranges produce 9 digits, so there needs 20-9 = 11 digits in [10 - 99]\n        //     n = 500, the previous ranges produce 189 digits, so there needs 500-189 = 311 digits in [100-999]\n        // \n        // the `base` told us in current ranges, each number can have how many digits.\n        // then we can locate the target number.\n        //     n = 20, \n        //       (n - digits_cnt_prev) / base = (20 - 9 ) / 2 = 5, so, [10 - 14] produces 10 digits (ZERO-based),\n        //       now, we have 1 digits left, it is the first digit of the target number 15.\n        //\n        //     n = 500, \n        //       (n - digits_cnt_prev) / base = (500 - 189) / 3 = 103, so, [100 - 202] produces 309 digits(ZERO-based).\n        //       now, we have (500 - 189 - 309) = 2 digits left, it is the second digit of the target number 203.\n        //\n        // We can write the code now... \n        //\n        int target = pow(10, base-1) + (n - digits_cnt_prev) / base - 1;\n        int left = n - digits_cnt_prev - (n - digits_cnt_prev) / base * base;\n        \n        //cout << \"target = \" << target <<  \", left = \" << left << endl;\n        \n        //no digits left\n        if ( left == 0 ) return (target) % 10;\n        \n        //still have some digits left, it should be in next number.\n        target++;\n        return int( target / pow(10, base - left) ) % 10;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOf1Bits/numberOf1Bits.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-1-bits/\n// Author : Hao Chen\n// Date   : 2015-03-30\n\n/********************************************************************************** \n* \n* Write a function that takes an unsigned integer and returns the number of ’1' bits it has \n* (also known as the Hamming weight).\n* \n* For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, \n* so the function should return 3.\n* \n* Credits:Special thanks to @ts for adding this problem and creating all test cases.\n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    int hammingWeight(uint32_t n) {\n        int cnt = 0;\n        for(;n>0; n/=2){\n            if (n & 0x1) cnt++;\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfDifferentIntegersInAString/NumberOfDifferentIntegersInAString.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-different-integers-in-a-string/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * You are given a string word that consists of digits and lowercase English letters.\n * \n * You will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \n * \" 123  34 8  34\". Notice that you are left with some integers that are separated by at least one \n * space: \"123\", \"34\", \"8\", and \"34\".\n * \n * Return the number of different integers after performing the replacement operations on word.\n * \n * Two integers are considered different if their decimal representations without any leading zeros \n * are different.\n * \n * Example 1:\n * \n * Input: word = \"a123bc34d8ef34\"\n * Output: 3\n * Explanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only \n * counted once.\n * \n * Example 2:\n * \n * Input: word = \"leet1234code234\"\n * Output: 2\n * \n * Example 3:\n * \n * Input: word = \"a1b01c001\"\n * Output: 1\n * Explanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\n * the leading zeros are ignored when comparing their decimal values.\n * \n * Constraints:\n * \n * \t1 <= word.length <= 1000\n * \tword consists of digits and lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    bool isNumber(char ch) {\n        return (ch >='0' && ch <='9');\n    }\n    \npublic:\n    int numDifferentIntegers(string word) {\n        word.push_back('z'); // add a char for edge case.\n        bool intStart = false; // a stat for control \n        int start = 0, len = 0;\n        unordered_map<string, bool> stat;\n        for(int i=0; i<word.size(); i++) {\n            if (!isNumber(word[i]) ) {\n                if (intStart) {\n                    while(word[start]=='0') {\n                        start++, len--;\n                    }\n                    stat[word.substr(start, len)] = true;\n                    intStart=false; \n                }\n                continue;\n            }\n            \n            if (intStart == false) {\n                intStart = true;\n                start = i;\n                len = 1;\n            }else {\n                len++;\n            }\n        }\n        return stat.size();           \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfDifferentSubsequencesGcds/NumberOfDifferentSubsequencesGcds.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-different-subsequences-gcds/\n// Author : Hao Chen\n// Date   : 2021-04-05\n\n/***************************************************************************************************** \n *\n * You are given an array nums that consists of positive integers.\n * \n * The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in \n * the sequence evenly.\n * \n * \tFor example, the GCD of the sequence [4,6,16] is 2.\n * \n * A subsequence of an array is a sequence that can be formed by removing some elements (possibly \n * none) of the array.\n * \n * \tFor example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\n * \n * Return the number of different GCDs among all non-empty subsequences of nums.\n * \n * Example 1:\n * \n * Input: nums = [6,10,3]\n * Output: 5\n * Explanation: The figure shows all the non-empty subsequences and their GCDs.\n * The different GCDs are 6, 10, 3, 2, and 1.\n * \n * Example 2:\n * \n * Input: nums = [5,15,40,5,6]\n * Output: 7\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t1 <= nums[i] <= 2 * 10^5\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    // Euclidean algorithm\n    // https://en.wikipedia.org/wiki/Euclidean_algorithm\n    int gcd(int a, int b) {\n        while ( b != 0 ) {\n            int t = b;\n            b = a % b;\n            a = t;\n        }\n        return a;\n    }\n\npublic:\n    int countDifferentSubsequenceGCDs(vector<int>& nums) {\n        int len = nums.size();\n        vector<int> gcds(200001, 0);\n        \n        for(int i=0; i<len; i++) {\n            int n = nums[i];\n            int m = sqrt(n);\n            for(int g=1; g<=m; g++){\n                if (n % g != 0) continue;\n                int x = g, y = n/g;\n                if (x != y ){\n                    gcds[x] = gcd(n, gcds[x]);\n                    gcds[y] = gcd(n, gcds[y]);\n                }else {\n                    gcds[x] = gcd(n, gcds[x]);\n                }\n            }\n        }\n        \n        int cnt = 0;\n        for(int i=1; i<gcds.size(); i++){\n            if (gcds[i]==i) cnt++;\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfDigitOne/NumberOfDigitOne.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-digit-one/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Given an integer n, count the total number of digit 1 appearing in all non-negative \n * integers less than or equal to n.\n * \n * For example: \n * Given n = 13,\n * Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.\n * \n *   Beware of overflow.\n * \n **********************************************************************************/\n\n/*\n *  The idea is:\n *  \n *  1) seprate the n to two parts. considering n is `abc` \n *     \n *  2) at first, we seprate it to `ab` & `c`, then, \n *     c == 0,  the # of `1` appears in uints is  \"ab * 1\"\n *     c == 1,  the # of `1` appears in units is  \"ab * 1 + 0 + 1\" (0 means the number after `c`)\n *     c > 1 ,  the # of `1` appears in units is  \"(ab+1)*1\"\n *  \n *  3) at second, we seprate it to `a` & `bc`, then,\n *     b == 0,  the # of `1` appears in tens is  \"a * 10\"\n *     b == 1,  the # of `1` appears in tens is  \"a * 10 + c + 1\" (`c` means the number after `b`)\n *     b > 1 ,  the # of `1` appears in tens is  \"(a+1)*10\"\n *  \n *  4) at thrid, we seprate it to `` & `abc`, then,\n *     a == 0,  the # of `1` appears in tens is  \"0 * 100\" ( 0 menas the number before `a`)\n *     a == 1,  the # of `1` appears in tens is  \"0 * 100 + bc + 1\" (`bc` means the number after `a`)\n *     a > 1 ,  the # of `1` appears in tens is  \"(0+1)*100\" \n *  \n *  \n *  For some examples: \n *  0) n = 5,   we have (0+1)*1 = 1 digit 1\n *  1) n = 53,  we have  (5+1)*1  + (0+1)*10   = 16  digit 1\n *  2) n = 20,  we have     (2*1) + (0+1)*10   = 12  digit 1 \n *  3) n = 21,  we have (2*1+0+1) + (0+1)*10   = 13  digit 1\n *  4) n = 13,  we have   (1+1)*1 + (0*10+3+1) = 6   digit 1\n *  5) n = 109, we have  (10+1)*1 + (1*10) + (0*100 + 09 + 1) = 31 digit 1 \n *  \n *  Converting the ideas to code as below:\n *  \n */\n\nclass Solution {\npublic:\n\n    int countDigitOne(int n) {\n        long long base=1, left=n, right=0, currDigit=0;\n        int numOfOne = 0;\n        while(left>0) {\n            currDigit = left % 10;\n            left = left/ 10;\n            \n            if (currDigit == 0) {\n                numOfOne += (left * base);\n            }else if (currDigit == 1) {\n                numOfOne += (left * base + right + 1);\n            }else {\n                numOfOne += ((left+1)*base);\n            }\n            \n            right = right + currDigit * base;\n            base *= 10;\n        }\n        return numOfOne;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfGoodWaysToSplitAString/NumberOfGoodWaysToSplitAString.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-good-ways-to-split-a-string/\n// Author : Hao Chen\n// Date   : 2020-10-07\n\n/***************************************************************************************************** \n *\n * You are given a string s, a split is called good if you can split s into 2 non-empty strings p and \n * q where its concatenation is equal to s and the number of distinct letters in p and q are the same.\n * \n * Return the number of good splits you can make in s.\n * \n * Example 1:\n * \n * Input: s = \"aacaba\"\n * Output: 2\n * Explanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n * (\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n * (\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n * (\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good \n * split).\n * (\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good \n * split).\n * (\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\n * \n * Example 2:\n * \n * Input: s = \"abcd\"\n * Output: 1\n * Explanation: Split the string as follows (\"ab\", \"cd\").\n * \n * Example 3:\n * \n * Input: s = \"aaaaa\"\n * Output: 4\n * Explanation: All possible splits are good.\n * \n * Example 4:\n * \n * Input: s = \"acbadbaada\"\n * Output: 2\n * \n * Constraints:\n * \n * \ts contains only lowercase English letters.\n * \t1 <= s.length <= 10^5\n ******************************************************************************************************/\nclass Solution {\npublic:\n    int numSplits(string s) {\n        //just walk through the string from left side and right side, \n        //calculate the diffrent letters from both side.\n        \n        // `ldict` & `rdict` remember the letter occurs or not\n        //vector bool is bit data structure\n        const int max_chars= 256;\n        vector<bool> ldict(max_chars, false), rdict(max_chars, false);\n        \n        // `lstat` & `rstat` are used to record the different letters.\n        // `lstat` is used from left side walk through\n        // `rstat` is used from right side walk through \n        int len = s.size();\n        vector<int> lstat(len, 0), rstat(len, 0);\n        \n        int lcnt=0, rcnt=0;\n        \n        for (int i=0; i<len; i++) {\n            char lc = s[i];\n            char rc = s[len-i-1];\n            \n            if (ldict[lc] == false) {\n                lcnt++;\n                ldict[lc] = true;\n            }\n            \n            if (rdict[rc] == false) {\n                rcnt++;\n                rdict[rc] = true;\n            }\n            \n            lstat[i] = lcnt;\n            rstat[len-i-1] = rcnt;\n        }\n        \n        \n        int cnt = 0;\n        for (int i=1; i<len; i++){\n            if (lstat[i-1] == rstat[i]) {\n                cnt++;\n            }\n        }\n        \n        return cnt;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfIslands/NumberOfIslands.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-islands/\n// Author : Hao Chen\n// Date   : 2015-06-08\n\n/********************************************************************************** \n * \n * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. \n * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. \n * You may assume all four edges of the grid are all surrounded by water.\n * \n * Example 1:\n *   11110\n *   11010\n *   11000\n *   00000\n * Answer: 1\n * \n * Example 2:\n *   11000\n *   11000\n *   00100\n *   00011\n * Answer: 3\n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid mark(vector<vector<char> >& grid, int r, int c){\n    if ( r<0 || r>=grid.size() ||\n            c<0 || c>=grid[0].size() ||\n            grid[r][c] != '1' ) {\n        return;\n    }\n\n    grid[r][c] = 'M';\n\n    mark(grid, r, c+1); //left\n    mark(grid, r, c-1); //right\n    mark(grid, r-1, c); //up\n    mark(grid, r+1, c); //down\n}\n\nint numIslands(vector<vector<char> >& grid) {\n    int result = 0;\n    for (int r=0; r<grid.size(); r++) {\n        for (int c=0; c<grid[r].size(); c++) {\n            if (grid[r][c] == '1') {\n                result++;\n                mark(grid, r, c);\n            }\n        }\n    }\n    return result;\n}\n\nvoid initGrid( string g[], int len, vector<vector<char> >& grid )\n{\n    for (int i=0; i<len; i++){\n       grid.push_back(vector<char>(g[i].begin(), g[i].end())); \n    }\n}\n\nint main(void)\n{\n    vector< vector<char> > grid;\n    grid.push_back( vector<char>(1, '1') );\n\n    cout << numIslands(grid) << endl;\n\n\n    grid.clear();\n\n    string g1[] = { \"11110\",\n                    \"11010\", \n                    \"11000\", \n                    \"00000\" };\n\n    initGrid(g1, 4, grid);\n    cout << numIslands(grid) << endl;\n\n\n\n    grid.clear();\n\n    string g2[] = { \"11000\",\n                    \"11000\",\n                    \"00100\",\n                    \"00011\" };\n\n    initGrid(g2, 4, grid);\n    cout << numIslands(grid) << endl;\n\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/numberOfOrdersInTheBacklog/NumberOfOrdersInTheBacklog.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-orders-in-the-backlog/\n// Author : Hao Chen\n// Date   : 2021-03-21\n\n/***************************************************************************************************** \n *\n * You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] \n * denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei \n * is:\n * \n * \t0 if it is a batch of buy orders, or\n * \t1 if it is a batch of sell orders.\n * \n * Note that orders[i] represents a batch of amounti independent orders with the same price and order \n * type. All orders represented by orders[i] will be placed before all orders represented by \n * orders[i+1] for all valid i.\n * \n * There is a backlog that consists of orders that have not been executed. The backlog is initially \n * empty. When an order is placed, the following happens:\n * \n * \tIf the order is a buy order, you look at the sell order with the smallest price in the \n * backlog. If that sell order's price is smaller than or equal to the current buy order's price, they \n * will match and be executed, and that sell order will be removed from the backlog. Else, the buy \n * order is added to the backlog.\n * \tVice versa, if the order is a sell order, you look at the buy order with the largest price \n * in the backlog. If that buy order's price is larger than or equal to the current sell order's \n * price, they will match and be executed, and that buy order will be removed from the backlog. Else, \n * the sell order is added to the backlog.\n * \n * Return the total amount of orders in the backlog after placing all the orders from the input. Since \n * this number can be large, return it modulo 109 + 7.\n * \n * Example 1:\n * \n * Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\n * Output: 6\n * Explanation: Here is what happens with the orders:\n * - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are \n * added to the backlog.\n * - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than \n * or equal to 15, so the 2 orders are added to the backlog.\n * - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or \n * equal to 25 in the backlog, so this order is added to the backlog.\n * - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell \n * orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The \n * 3rd order is matched with the sell order of the least price, which is 25 and this sell order is \n * removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is \n * added to the backlog.\n * Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total \n * number of orders in the backlog is 6.\n * \n * Example 2:\n * \n * Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\n * Output: 999999984\n * Explanation: Here is what happens with the orders:\n * - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are \n * added to the backlog.\n * - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the \n * least price which is 7, and those 3 sell orders are removed from the backlog.\n * - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so \n * the 999999995 orders are added to the backlog.\n * - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest \n * price, which is 5, and that buy order is removed from the backlog.\n * Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with \n * price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).\n * \n * Constraints:\n * \n * \t1 <= orders.length <= 105\n * \torders[i].length == 3\n * \t1 <= pricei, amounti <= 109\n * \torderTypei is either 0 or 1.\n ******************************************************************************************************/\n\nclass Order {\npublic:\n    int price;\n    int amount;\n};\n\nenum COMP { GREATER, LESS };\n\ntemplate <COMP op>\nclass OrderComp {\npublic:\n    bool operator() (const Order& lhs, const Order& rhs) {\n        if (op == GREATER) {\n            return lhs.price > rhs.price;\n        }\n        return lhs.price < rhs.price;\n    }\n};\n\n\nclass Solution {\nprivate:\n    template<typename T1, typename T2>\n    void processOrder(T1& q1, T2& q2, COMP op, int price, int amount, string n1=\"q1\", string n2=\"q2\") {\n        if (q2.size() == 0) {\n            q1.push(Order{price, amount});\n            return;\n        }\n        \n        while(!q2.empty() && amount > 0  ){\n            Order order = q2.top(); \n            if (op == GREATER && order.price > price ) break;\n            if (op == LESS && order.price < price) break;\n\n            q2.pop();\n            //cout << \"=> deQueue(\"<< n2 << \"): \" << order.price << \", \"<< order.amount << endl;\n\n            int amt = min(order.amount, amount);\n            order.amount -= amt;\n            amount -= amt;\n            if (order.amount > 0) {\n                //cout << \"<= enQueue(\"<< n2 <<\"): \" << order.price << \", \"<< order.amount << endl;\n                q2.push(order);\n            }\n        }\n        if (amount > 0) {\n            //cout << \"<= enQueue(\"<< n1 <<\"): \" << price << \", \"<< amount << endl;\n            q1.push(Order{price, amount});\n        }\n    }\n    \n    template<typename T>\n    void countQ(T& q, int& amount){\n        while(!q.empty()) {\n            amount = (amount + q.top().amount) % 1000000007;\n            q.pop();\n        }\n    }\npublic:\n    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n        \n        priority_queue<Order, vector<Order>, OrderComp<GREATER>> sell;\n        priority_queue<Order, vector<Order>, OrderComp<LESS>> buy;\n        \n        \n        for (auto& order : orders) {\n            int& price = order[0];\n            int& amount = order[1];\n            \n            if (order[2] == 0)  { //buy order\n                processOrder(buy, sell, GREATER, price, amount, \"buy\", \"sell\");\n            }else { // sell order\n                processOrder(sell, buy, LESS, price, amount, \"sell\", \"buy\");\n            }\n        }\n        \n        int amount = 0;\n        countQ(sell, amount);\n        countQ(buy, amount);\n        return amount ;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfRecentCalls/NumberOfRecentCalls.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-recent-calls/\n// Author : Hao Chen\n// Date   : 2020-07-26\n\n/***************************************************************************************************** \n *\n * Write a class RecentCounter to count recent requests.\n * \n * It has only one method: ping(int t), where t represents some time in milliseconds.\n * \n * Return the number of pings that have been made from 3000 milliseconds ago until now.\n * \n * Any ping with time in [t - 3000, t] will count, including the current ping.\n * \n * It is guaranteed that every call to ping uses a strictly larger value of t than before.\n * \n * Example 1:\n * \n * Input: inputs = [\"RecentCounter\",\"ping\",\"ping\",\"ping\",\"ping\"], inputs = [[],[1],[100],[3001],[3002]]\n * Output: [null,1,2,3,3]\n * \n * Note:\n * \n * \tEach test case will have at most 10000 calls to ping.\n * \tEach test case will call ping with strictly increasing values of t.\n * \tEach call to ping will have 1 <= t <= 10^9.\n * \n ******************************************************************************************************/\n\nclass RecentCounter {\npublic:\n    RecentCounter() {\n\n    }\n\n    int ping(int t) {\n        req.push_back(t);\n        return req.size() - binary_search(t-3000);\n    }\nprivate:\n    vector<int> req;\n    int binary_search(int x) {\n        int low=0, high=req.size()-1;\n        while(low < high) {\n            int mid = low + (high -low) / 2;\n            if ( req[mid] == x ) return mid;\n            if ( req[mid] < x ) low = mid + 1;\n            else high = mid - 1;\n        }\n        cout << \"x=\"  << x << \"\\tlow=\" << low << endl;\n        return x > req[low] ? low+1 : low ;\n    }\n};\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter* obj = new RecentCounter();\n * int param_1 = obj->ping(t);\n */\n"
  },
  {
    "path": "algorithms/cpp/numberOfRectanglesThatCanFormTheLargestSquare/NumberOfRectanglesThatCanFormTheLargestSquare.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/\n// Author : Hao Chen\n// Date   : 2021-03-27\n\n/***************************************************************************************************** \n *\n * You are given an array rectangles where rectangles[i] = [li, wi] represents the i^th rectangle of \n * length li and width wi.\n * \n * You can cut the i^th rectangle to form a square with a side length of k if both k <= li and k <= \n * wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length \n * of at most 4.\n * \n * Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.\n * \n * Return the number of rectangles that can make a square with a side length of maxLen.\n * \n * Example 1:\n * \n * Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]\n * Output: 3\n * Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].\n * The largest possible square is of length 5, and you can get it out of 3 rectangles.\n * \n * Example 2:\n * \n * Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]\n * Output: 3\n * \n * Constraints:\n * \n * \t1 <= rectangles.length <= 1000\n * \trectangles[i].length == 2\n * \t1 <= li, wi <= 10^9\n * \tli != wi\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countGoodRectangles(vector<vector<int>>& rectangles) {\n        return countGoodRectangles2(rectangles);\n        return countGoodRectangles1(rectangles); \n    }\n    \n    int countGoodRectangles1(vector<vector<int>>& rectangles) {\n        int maxLen = 0;\n        for(auto& rect : rectangles) {\n            int  len = min(rect[0], rect[1]);\n            maxLen = max(maxLen, len);\n        }\n        \n        int cnt = 0;\n        for(auto& rect : rectangles) {\n            if (maxLen <= rect[0] && maxLen <= rect[1]) cnt++;\n        }\n        return cnt;\n    }\n    \n    int countGoodRectangles2(vector<vector<int>>& rectangles) {\n        int maxLen = 0;\n        int cnt = 0;\n        for(auto& rect : rectangles) {\n            int  len = min(rect[0], rect[1]);\n            if (len > maxLen ) {\n                cnt = 1;\n                maxLen = len;\n            }else if (len == maxLen ) {\n                cnt++;\n            }\n        }\n\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfRestrictedPathsFromFirstToLastNode/NumberOfRestrictedPathsFromFirstToLastNode.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/\n// Author : Hao Chen\n// Date   : 2021-03-07\n\n/***************************************************************************************************** \n *\n * There is an undirected weighted connected graph. You are given a positive integer n which denotes \n * that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, \n * weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.\n * \n * A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = \n * start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.\n * \n * The distance of a path is the sum of the weights on the edges of the path. Let \n * distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A \n * restricted path is a path that also satisfies that distanceToLastNode(zi) > \n * distanceToLastNode(zi+1) where 0 <= i <= k-1.\n * \n * Return the number of restricted paths from node 1 to node n. Since that number may be too large, \n * return it modulo 109 + 7.\n * \n * Example 1:\n * \n * Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\n * Output: 3\n * Explanation: Each circle contains the node number in black and its distanceToLastNode value in \n * blue. The three restricted paths are:\n * 1) 1 --> 2 --> 5\n * 2) 1 --> 2 --> 3 --> 5\n * 3) 1 --> 3 --> 5\n * \n * Example 2:\n * \n * Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\n * Output: 1\n * Explanation: Each circle contains the node number in black and its distanceToLastNode value in \n * blue. The only restricted path is 1 --> 3 --> 7.\n * \n * Constraints:\n * \n * \t1 <= n <= 2 * 104\n * \tn - 1 <= edges.length <= 4 * 104\n * \tedges[i].length == 3\n * \t1 <= ui, vi <= n\n * \tui != vi\n * \t1 <= weighti <= 105\n * \tThere is at most one edge between any two nodes.\n * \tThere is at least one path between any two nodes.\n ******************************************************************************************************/\n\nclass Solution {\n    void printVector(vector<int>& v) {\n        cout << \"[\";\n        for (int i = 0; i< v.size() -1 ; i ++) {\n            cout << v[i] << \", \";\n        }\n        cout << v[v.size()-1] << \"]\" << endl;\n    }\npublic:\n    int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n        \n        // re-orginanize the graph map\n        vector<unordered_map<int, int>> graph(n);\n        for(auto e : edges) {\n            int x = e[0]-1;\n            int y = e[1]-1;\n            int d = e[2];\n            graph[x][y] = graph[y][x] = d; \n        }\n        \n        \n        \n        //Dijkstra Algorithm\n        vector<int> distance(n, INT_MAX);\n        distance[n-1] = 0;\n        \n        auto cmp = [&](const int& lhs, const int& rhs) {return distance[lhs] > distance[rhs]; };\n        priority_queue<int, vector<int>, decltype(cmp)> nodes(cmp);\n        \n        nodes.push(n-1);\n        \n        while( !nodes.empty() ) {\n            int x = nodes.top(); nodes.pop();\n            for(const auto & [ y, d ] : graph[x]) {  \n                if ( distance[y] > d + distance[x] ) {\n                    distance[y] = d + distance[x];\n                    // if the node's distance is updated, \n                    // it's neighbor  must be recaluated \n                    nodes.push(y); \n                }\n            }\n        }\n        \n        //printVector(distance);\n        \n\n        //Dynamic Programming for restric paths\n        vector<bool> visited(n, false);\n        vector<long> restriced_path(n, 0);\n        \n        nodes.push(n-1);\n        restriced_path[n-1] = 1;\n        visited[n-1] = true;\n        \n        while( !nodes.empty() ) {\n            int x = nodes.top(); nodes.pop();\n\n            //cout << x+1 << \":\";\n            for(const auto & [ y, d ] : graph[x]) { \n                \n                if ( distance[y] > distance[x]) {\n                    restriced_path[y] += restriced_path[x];\n                    restriced_path[y] %= 1000000007;\n                }\n                if (!visited[y]) {\n                    //cout << y+1 << \",\";\n                    nodes.push(y);\n                    visited[y] = true;\n                }\n            }\n  \n            //cout<<endl;\n            //printVector(restriced_path);\n        }\n        //cout << \"-------\" <<endl;\n        //printVector(restriced_path);\n        return restriced_path[0];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfStudentsUnableToEatLunch/NumberOfStudentsUnableToEatLunch.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/\n// Author : Hao Chen\n// Date   : 2021-05-10\n\n/***************************************************************************************************** \n *\n * The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 \n * and 1 respectively. All students stand in a queue. Each student either prefers square or circular \n * sandwiches.\n * \n * The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are \n * placed in a stack. At each step:\n * \n * \tIf the student at the front of the queue prefers the sandwich on the top of the stack, they \n * will take it and leave the queue.\n * \tOtherwise, they will leave it and go to the queue's end.\n * \n * This continues until none of the queue students want to take the top sandwich and are thus unable \n * to eat.\n * \n * You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the \n * ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of \n * the jth student in the initial queue (j = 0 is the front of the queue). Return the number of \n * students that are unable to eat.\n * \n * Example 1:\n * \n * Input: students = [1,1,0,0], sandwiches = [0,1,0,1]\n * Output: 0 \n * Explanation:\n * - Front student leaves the top sandwich and returns to the end of the line making students = \n * [1,0,0,1].\n * - Front student leaves the top sandwich and returns to the end of the line making students = \n * [0,0,1,1].\n * - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches \n * = [1,0,1].\n * - Front student leaves the top sandwich and returns to the end of the line making students = \n * [1,1,0].\n * - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = \n * [0,1].\n * - Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n * - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = \n * [1].\n * - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\n * Hence all students are able to eat.\n * \n * Example 2:\n * \n * Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\n * Output: 3\n * \n * Constraints:\n * \n * \t1 <= students.length, sandwiches.length <= 100\n * \tstudents.length == sandwiches.length\n * \tsandwiches[i] is 0 or 1.\n * \tstudents[i] is 0 or 1.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countStudents(vector<int>& students, vector<int>& sandwiches) {\n        int st[2] = {0};\n        for(auto s: students) {\n            st[s]++;\n        }\n        int cnt = 0;\n        for(auto& san : sandwiches){\n            if (st[san] == 0) break;\n            st[san]--;\n            cnt++;\n        }\n        return students.size() - cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfSubArraysWithOddSum/NumberOfSubArraysWithOddSum.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/\n// Author : Hao Chen\n// Date   : 2020-10-07\n\n/***************************************************************************************************** \n *\n * Given an array of integers arr. Return the number of sub-arrays with odd sum.\n * \n * As the answer may grow large, the answer must be computed modulo 10^9 + 7.\n * \n * Example 1:\n * \n * Input: arr = [1,3,5]\n * Output: 4\n * Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\n * All sub-arrays sum are [1,4,9,3,8,5].\n * Odd sums are [1,9,3,5] so the answer is 4.\n * \n * Example 2:\n * \n * Input: arr = [2,4,6]\n * Output: 0\n * Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\n * All sub-arrays sum are [2,6,12,4,10,6].\n * All sub-arrays have even sum and the answer is 0.\n * \n * Example 3:\n * \n * Input: arr = [1,2,3,4,5,6,7]\n * Output: 16\n * \n * Example 4:\n * \n * Input: arr = [100,100,99,99]\n * Output: 4\n * \n * Example 5:\n * \n * Input: arr = [7]\n * Output: 1\n * \n * Constraints:\n * \n * \t1 <= arr.length <= 10^5\n * \t1 <= arr[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int numOfSubarrays(vector<int>& arr) {\n        //Walk through the array, and calculate the current sum\n        //if current sum is odd, then all of the sum are evil previously are valid sub-array\n        //if current sum is evil, then all of the sum are odd previously are valid sub-array\n        int odd_sum_cnt=0, evil_sum_cnt=0;\n        int sum = 0;\n        long long result=0;\n        for (auto a : arr) {\n            sum += a;\n            if (sum % 2 == 0) {\n                evil_sum_cnt++;\n                result += odd_sum_cnt;\n            }else {\n                odd_sum_cnt++;\n                result += evil_sum_cnt + 1;\n            }\n        }\n\n        return result % 1000000007;\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/numberOfSubstringsWithOnly1s/NumberOfSubstringsWithOnly1s.cpp",
    "content": "// Source : https://leetcode.com/problems/number-of-substrings-with-only-1s/\n// Author : Hao Chen\n// Date   : 2020-10-03\n\n/***************************************************************************************************** \n *\n * Given a binary string s (a string consisting only of '0' and '1's).\n * \n * Return the number of substrings with all characters 1's.\n * \n * Since the answer may be too large, return it modulo 10^9 + 7.\n * \n * Example 1:\n * \n * Input: s = \"0110111\"\n * Output: 9\n * Explanation: There are 9 substring in total with only 1's characters.\n * \"1\" -> 5 times.\n * \"11\" -> 3 times.\n * \"111\" -> 1 time.\n * \n * Example 2:\n * \n * Input: s = \"101\"\n * Output: 2\n * Explanation: Substring \"1\" is shown 2 times in s.\n * \n * Example 3:\n * \n * Input: s = \"111111\"\n * Output: 21\n * Explanation: Each substring contains only 1's characters.\n * \n * Example 4:\n * \n * Input: s = \"000\"\n * Output: 0\n * \n * Constraints:\n * \n * \ts[i] == '0' or s[i] == '1'\n * \t1 <= s.length <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    // 11 - 1+2\n    // 111 - 1+2+3\n    // 1111 - 1+2+3+4\n    // 11111 - 1+2+3+4+5\n    // so, we just simply find the length of continuous '1',\n    // then, the answer it len*(len+1)/2\n    int numSub(string s) {\n       long long len=0;\n       long long result=0;\n        for (auto c : s) {\n            if (c=='1') {\n                len++;\n                continue;\n            }\n            if (len > 0){\n                result += len*(len+1)/2;\n                len = 0;\n            }\n        }\n\n        result += len*(len+1)/2;\n        return result % 1000000007 ;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp",
    "content": "// Source : https://leetcode.com/problems/odd-even-linked-list/\n// Author : Hao Chen\n// Date   : 2016-01-16\n\n/*************************************************************************************** \n *\n * Given a singly linked list, group all odd nodes together followed by the even nodes. \n * Please note here we are talking about the node number and not the value in the nodes.\n * \n * You should try to do it in place. The program should run in O(1) space complexity \n * and O(nodes) time complexity.\n * \n * Example:\n * Given 1->2->3->4->5->NULL,\n * return 1->3->5->2->4->NULL.\n * \n * Note:\n * The relative order inside both the even and odd groups should remain as it was in \n * the input. \n * The first node is considered odd, the second node even and so on ...\n * \n * Credits:Special thanks to @aadarshjajodia for adding this problem and creating all \n * test cases.\n ***************************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* oddEvenList(ListNode* head) {\n        if (!head) return head;\n        ListNode* pOdd = head;\n        ListNode* p = head->next;\n        ListNode* pNext = NULL;\n        while(p && (pNext=p->next)) {\n            \n            p->next = pNext->next;\n            pNext->next = pOdd->next;\n            pOdd->next = pNext;\n            \n            p = p->next;\n            pOdd = pOdd->next;\n        \n        }\n        return head;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/oneEditDistance/oneEditDistance.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/one-edit-distance/\n// Author : Hao Chen\n// Date   : 2014-12-03\n\n/*\n *    Given two strings S and T, determine if they are both one edit distance apart.\n */\n\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\n/*\n * Notes: \n *\n *   If you try to use the Dynamic Program Algorithm, just like the `Edit Distance`, \n *   Then, you will get `Memory Limit Error` or `Time Limit Error`.\n *\n *   The Dynamic Program Algorithm which `Edit Distance` prolem used call `Wagner–Fischer Algorithm`\n *   (refer to: http://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm)\n *   Ths DP algorithm's  time complexity is O(m*n), and the space complexity is O(m*n) as well, \n *   You can optimized the space complexity to O(2*min(m,n)), but it still have `Time Limit Error`\n *\n *   Fortunately, this problem just for the `One` edit distance, so, this is special case we can solve it by special way.\n */\n\nbool isOneEditDistance(string s, string t) {\n    int len_s = s.size();\n    int len_t = t.size();\n    if (len_s==0) return len_t==1;\n    if (len_t==0) return len_s==1;\n\n\n    switch (abs(len_s-len_t)) {\n        case 0:\n            {\n                //if these two strings have same length.\n                //it means - we cannot use `add` or `delete` edit methods, just use the `replace` method\n                //So, just simply count the different char(s).\n                int cnt=0;\n                for (int i=0; i<len_s; i++){\n                    if(s[i]!=t[i]){\n                        cnt++;\n                        if(cnt>1) return false;\n                    }\n                }\n                return cnt==1;\n            }\n\n        case 1:\n            {\n                //if these two strings' length just have ONE difference.\n                //it means - we only can use `delete` edit method to delete one char in longer string.\n                //So, just remove one char in longer string, and check it whether equal to shorter string.\n                string& ss = (len_s > len_t)? s : t;\n                string& tt = (len_s < len_t)? s : t;\n                for(int i=0; i<ss.size(); i++){\n                    string tmp = ss;\n                    if (ss.erase(i,1) == tt) {\n                        return true;\n                    }\n                }\n                return false;\n\n            }\n\n        default:\n            return false;\n    }\n\n    return false;\n}\n\nint main(int argc, char** argv)\n{\n    string s=\"ab\", t=\"acb\";\n    if(argc>2){\n        s = argv[1];\n        t = argv[2];\n    }\n    cout << \"s = \\\"\" << s << \"\\\"  t = \\\"\" << t << \"\\\"  : \" << (isOneEditDistance(s,t) ? \"true\" : \"false\") << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp",
    "content": "// Source : https://leetcode.com/problems/palindrome-linked-list/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Given a singly linked list, determine if it is a palindrome.\n * \n * Follow up:\n * Could you do it in O(n) time and O(1) space?\n *               \n **********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* findMiddle(ListNode* head) {\n        ListNode *p1=head, *p2=head;\n        while(p2 && p2->next){\n            p1 = p1->next;\n            p2 = p2->next->next;\n        }\n        return p1;\n    }\n    \n    ListNode* reverseLink(ListNode* head) {\n        ListNode* p=NULL;\n        \n        while (head) {\n            ListNode* q = head->next;\n            head->next = p;\n            p = head;\n            head = q;\n        }\n        return p;\n    }\n    \n    bool isPalindrome(ListNode* head) {\n        ListNode* pMid = findMiddle(head);\n        ListNode* pRev = reverseLink(pMid); \n        for(;head!=pMid; head=head->next, pRev=pRev->next) {\n            if (head->val != pRev->val) {\n                return false;\n            }\n        }\n        return true;\n    }\n};\n\n\n"
  },
  {
    "path": "algorithms/cpp/palindromeNumber/palindromeNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/palindrome-number/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Determine whether an integer is a palindrome. Do this without extra space.\n* \n* \n* Some hints:\n* \n* Could negative integers be palindromes? (ie, -1)\n* \n* If you are thinking of converting the integer to string, note the restriction of using extra space.\n* \n* You could also try reversing an integer. However, if you have solved the problem \"Reverse Integer\", \n* you know that the reversed integer might overflow. How would you handle such case?\n* \n* There is a more generic way of solving this problem.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\nclass Solution {\npublic:\n\n    bool isPalindrome(int x) {    \n        return isPalindrome1(x);\n        return isPalindrome2(x);\n    }\n\n    bool isPalindrome1(int x) {\n        if (x<0) {\n            return false;\n        }\n        \n        int len=1;\n        for (len=1; (x/len) >= 10; len*=10 );\n        \n        while (x != 0 ) {\n            int left = x / len;\n            int right = x % 10;\n            \n            if(left!=right){\n                return false;\n            }\n            \n            x = (x%len) / 10;\n            len /= 100;\n        }\n        return true;\n    }\n    \n    bool isPalindrome2(int x) {\n        return (x>=0 && x == reverse(x));\n    }\n\nprivate:    \n    int reverse(int x) {\n        int y=0;\n\n        int n;\n        while( x!=0 ){\n            n = x%10;\n            //check if y is overflowed or not. \n            //if it is, then it's not palindrome\n            if ( y > INT_MAX/10 - n) return x-1;\n            y = y*10 + n;\n            x /= 10;\n        }\n        return y;\n    }\n};\n\n\n\nint main()\n{\n    Solution s;\n    printf(\"%d is %d\\n\", 0, s.isPalindrome(0) );\n    printf(\"%d is %d\\n\", -101, s.isPalindrome(-101) );\n    printf(\"%d is %d\\n\", 1001, s.isPalindrome(1001) );\n    printf(\"%d is %d\\n\", 1234321, s.isPalindrome(1234321) );\n    printf(\"%d is %d\\n\", 2147447412, s.isPalindrome(2147447412) );\n    printf(\"%d is %d\\n\", 2142, s.isPalindrome(2142) );\n}\n"
  },
  {
    "path": "algorithms/cpp/palindromePairs/PalindromePairs.cpp",
    "content": "// Source : https://leetcode.com/problems/palindrome-pairs/\n// Author : Hao Chen\n// Date   : 2017-03-22\n\n/*************************************************************************************** \n *\n * Given a list of unique words, find all pairs of distinct indices (i, j) in the given \n * list, so that the concatenation of the two words, i.e. words[i] + words[j] is a \n * palindrome.\n * \n *     Example 1:\n *     Given words = [\"bat\", \"tab\", \"cat\"]\n *     Return [[0, 1], [1, 0]]\n *     The palindromes are [\"battab\", \"tabbat\"]\n * \n *     Example 2:\n *     Given words = [\"abcd\", \"dcba\", \"lls\", \"s\", \"sssll\"]\n *     Return [[0, 1], [1, 0], [3, 2], [2, 4]]\n *     The palindromes are [\"dcbaabcd\", \"abcddcba\", \"slls\", \"llssssll\"]\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n *       \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    bool isPalindrome(string& str) {\n        int left = 0, right = str.size() - 1;\n        while( left < right) {\n            if (str[left++] != str[right--]) return false;\n        }\n        return true;\n    }\n    vector<vector<int>> palindromePairs(vector<string>& words) {\n        unordered_map<string, int> dict;\n        for(int i=0; i<words.size(); i++){\n            string w = words[i];\n            reverse(w.begin(), w.end());\n            dict[w] = i;\n        }\n        \n        \n        vector<vector<int>> result;\n        \n        //egde case: deal with empty string \n        if ( dict.find(\"\") != dict.end() ) {\n            for(int i=0; i<words.size(); i++) {\n                if ( isPalindrome(words[i]) && dict[\"\"] != i ) {\n                    result.push_back( { dict[\"\"], i } );\n                }\n            }\n        }\n        \n        for(int i=0; i<words.size(); i++) {\n            for (int j=0; j<words[i].size(); j++) {\n                //split the word to 2 parts\n                string left = words[i].substr(0, j);\n                string right = words[i].substr(j, words[i].size() - j);\n                \n                // if the `left` is found, which means there is a words has reversed sequence with it.\n                // then we can check the `right` part is Palindrome or not. \n                if ( dict.find(left) != dict.end() && isPalindrome(right) && dict[left] != i ) {\n                    result.push_back( { i, dict[left] } );\n                }\n                \n                if (dict.find(right) != dict.end() && isPalindrome(left) && dict[right] != i ) {\n                    result.push_back( { dict[right], i } );\n                }\n            }\n\n        }\n        \n        return result;\n    }\n    \n};\n\n"
  },
  {
    "path": "algorithms/cpp/palindromePartitioning/palindromePartitioning.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/palindrome-partitioning-ii/\n// Author : Hao Chen\n// Date   : 2014-08-24\n\n/********************************************************************************** \n* \n* Given a string s, partition s such that every substring of the partition is a palindrome.\n* \n* Return the minimum cuts needed for a palindrome partitioning of s.\n* \n* For example, given s = \"aab\",\n* Return 1 since the palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\nusing namespace std;\n\nbool isPalindrome(string &s, int start, int end);\nvoid minCutHelper(string &s, int start, int steps, int& min );\nint minCutHelper(string &s, int steps, int& minSteps );\nint minCut_DP(string& s); \n\nint minCut(string s) {\n    #define INT_MAX 2147483647\n    if(s.size()<=1) return 0;\n\n    int min = INT_MAX;\n    \n    //minCutHelper(s, 0, 0, min);\n    //return min-1;\n\n    //int m =  minCutHelper(s, 0, min);\n    //return m-1;\n\n    return minCut_DP(s);\n}\n\n/*\n *  Dynamic Programming\n *  -------------------\n *\n *  Define res[i] = the minimum cut from 0 to i in the string.\n *  The result eventually is res[s.size()-1].\n *  We know res[0]=0. Next we are looking for the optimal solution function f.\n *  \n *  For example, let s = \"leet\".\n *  \n *  f(0) = 0; // minimum cut of str[0:0]=\"l\", which is a palindrome, so not cut is needed.\n *  f(1) = 1; // str[0:1]=\"le\" How to get 1? \n *                   f(1) might be:  (1)   f(0)+1=1, the minimum cut before plus the current char.\n *                                   (2)   0, if str[0:1] is a palindrome  (here \"le\" is not )\n *  f(2) = 1; // str[0:2] = \"lee\" How to get 2?\n *                  f(2) might be:   (1)  f(1) + 1=2\n *                                   (2)  0, if str[0:2] is a palindrome (here \"lee\" is not)\n *                                   (3)  f(0) + 1,  if str[1:2] is a palindrome, yes! \n *  f(3) = 2; // str[0:3] = \"leet\" How to get 2?\n *                  f(3) might be:   (1)  f(2) + 1=2\n *                                   (2)  0, if str[0:3] is a palindrome (here \"leet\" is not)\n *                                   (3)  f(0) + 1,  if str[1:3] is a palindrome (here \"eet\" is not)\n *                                   (4)  f(1) + 1,  if str[2:e] is a palindrome (here \"et\" is not)\n *  OK, output f(3) =2 as the result.\n *  \n *  So, the optimal function is:\n *  \n *  f(i) = min [  f(j)+1,  j=0..i-1   and str[j:i] is palindrome\n *                      0,   if str[0,i] is palindrome ]\n *  \n *  The above algorithm works well for the smaller test cases, however for the big cases, it still cannot pass.\n *  Why? The way we test the palindrome is time-consuming.\n *  \n *  Also using the similar DP idea, we can construct the look-up table before the main part above, \n *  so that the palindrome testing becomes the looking up operation. The way we construct the table is also the idea of DP.\n *\n *  e.g.   mp[i][j]=true if str[i:j] is palindrome.\n *         mp[i][i]=true; \n *         mp[i][j] = true if str[i]==str[j] and (mp[i+1][j-1]==true or j-i<2 )  j-i<2 ensures the array boundary. \n */\n\n\nint minCut_DP(string& s) {\n    //res[] is for minimal cut DP\n    vector<int>res(s.size(),0);\n    //mp[][] is for palindrome checking DP\n    bool mp[s.size()][s.size()];\n\n    //construct the pailndrome checking matrix\n    //  1) matrix[i][j] = true;     if (i==j)                   -- only one char\n    //  2) matrix[i][j] = true;     if (i==j+1) && s[i]==s[j]   -- only two chars\n    //  3) matrix[i][j] = matrix[i+1][j-1];   if s[i]==s[j]     -- more than two chars\n    //\n    //note:  1) and 2) can be combined together\n    for (int i=s.size()-1;i>=0;i--){\n        for (int j=i;j<s.size();j++){\n            if ((s[i]==s[j]) && (j-i<2 || mp[i+1][j-1])){\n                mp[i][j]=true;\n            }else{\n                mp[i][j]=false;\n            }\n        }\n    }\n    //minimal cut dp\n    for (int i=0;i<s.size();i++){\n        //if s[0..i] is palindrome, then no need to cut\n        if (mp[0][i] == true){\n            res[i]=0;\n        }else{\n            // if s[0..i] isn't palindrome \n            // then, for each 0 to i, find a \"j\" which meets two conditions:\n            //    a) s[j+1..i] are palindrome.\n            //    b) res[j]+1 is minimal   \n            int ms = s.size();\n            for (int j=0; j<i; j++){\n                if (mp[j+1][i] && ms>res[j]+1 ) {\n                    ms=res[j]+1;\n                } \n            }\n            res[i]=ms;\n        }\n    }\n    return res[s.size()-1];\n}\n\n//More Optimized DFS -  Time Limit Exceeded\nint minCutHelper(string &s, int steps, int& minSteps ) {\n\n    // remove the steps if it's greater than minSteps \n    if (minSteps <= steps) {\n        return -2;\n    }\n    // adding the cache to remove the duplicated calculation\n    static map<string, int> cache;\n    if ( cache.find(s)!=cache.end() ){\n        if (s.size()>0)\n            cout << s << \":\" << cache[s] << endl;\n        return cache[s];\n    }\n    if (s.size()==0) {\n        if (minSteps > steps){\n            minSteps = steps;\n        }\n        cache[s] = 0;\n        return 0;\n    }\n\n\n    int min = INT_MAX;\n    string subs;\n    int m; \n    for( int i=s.size()-1; i>=0; i-- ) {\n        //remove the steps which greater than minSteps\n        if ( i < s.size()-1 && minSteps - steps <= 1) {\n            break;\n        }\n        if ( isPalindrome(s, 0, i) ){\n            //if ( i == s.size()-1 ) {\n            //    m = 1;\n            //}else{\n            subs = s.substr(i+1, s.size()-i-1);\n            m = minCutHelper(subs, steps+1, minSteps) + 1;\n            //}\n            if (m < 0) continue;\n            cache[subs] = m-1;\n            if (min > m ){\n                min = m;\n            }\n        }\n    }\n    return min;\n}\n\n\n//Optimized DFS -  Time Limit Exceeded\nvoid minCutHelper(string &s, int start, int steps, int& min ) {\n\n    if (start == s.size()) {\n        if (steps < min) {\n            min = steps;\n            return;\n        }\n    }\n\n    //GREED: find the biggest palindrome first\n    for(int i=s.size()-1; i>=start; i--){\n        //cut unnecessary DFS \n        if ( min > steps && isPalindrome(s, start, i)) {\n            minCutHelper(s, i+1, steps+1, min );\n        }\n    }\n}\n\n//traditional palindrome checking function.\nbool isPalindrome(string &s, int start, int end)  {  \n\n    while(start < end)  {  \n        if(s[start] != s[end]) { \n\n            return false;  \n        }\n        start++; end--;  \n    }  \n\n    return true;  \n}  \n\n//ababababababababababababcbabababababababababababa\n//fifgbeajcacehiicccfecbfhhgfiiecdcjjffbghdidbhbdbfbfjccgbbdcjheccfbhafehieabbdfeigbiaggchaeghaijfbjhi\n//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\nint main(int argc, char** argv)\n{\n    string s(\"aab\");\n    if ( argc > 1 ){\n        s = argv[1];\n    }\n\n    cout << s << \" : \" << minCut(s) << endl;\n\n}\n"
  },
  {
    "path": "algorithms/cpp/palindromePartitioning/palindromePartitioning.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/palindrome-partitioning/\n// Author : Hao Chen\n// Date   : 2014-08-21\n\n/********************************************************************************** \n* \n* Given a string s, partition s such that every substring of the partition is a palindrome.\n* \n* Return all possible palindrome partitioning of s.\n* \n* For example, given s = \"aab\",\n* \n* Return\n* \n*   [\n*     [\"aa\",\"b\"],\n*     [\"a\",\"a\",\"b\"]\n*   ]\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\n\nbool isPalindrome(string &s, int start, int end)  {  \n\n    while(start < end)  \n    {  \n        if(s[start] != s[end]) { \n            return false;  \n        }\n        start++; end--;  \n    }  \n    return true;  \n}  \n\n// DFS - Deepth First Search\n//    \n//   For example: \"aaba\"\n//    \n//                     +------+           \n//              +------| aaba |-----+     \n//              |      +------+     |     \n//            +-v-+              +-v--+  \n//            | a |aba           | aa |ba\n//        +---+---+--+           +--+-+  \n//        |          |              |    \n//      +-v-+     +--v--+         +-v-+  \n//      | a |ba   | aba |\\0       | b |a \n//      +-+-+     +-----+         +-+-+  \n//        |        a, aba           |    \n//      +-v-+                     +-v-+  \n//      | b |a                    | a |\\0\n//      +-+-+                     +---+  \n//        |                      aa, b, a\n//      +-v-+                            \n//      | a |\\0                          \n//      +---+                            \n//    a, a, b, a                         \n//\n//   You can see this algorithm still can be optimized, becasue there are some dupliation.\n//   (  The optimization you can see the \"Palindrome Partitioning II\" )\n//\n   \nvoid partitionHelper(string &s, int start, vector<string> &output, vector< vector<string> > &result) {\n\n    if (start == s.size()) {\n        result.push_back(output);\n        return;\n    }\n    for(int i=start; i<s.size(); i++) {\n        if ( isPalindrome(s, start, i) == true ) {\n            //put the current palindrome substring into ouput\n            output.push_back(s.substr(start, i-start+1) );\n            //Recursively check the rest substring\n            partitionHelper(s, i+1, output, result);\n            //take out the current palindrome substring, in order to check longer substring.\n            output.pop_back();\n        }\n    }\n}\n\nvector< vector<string> > partition(string s) {\n\n    vector< vector<string> > result;\n    vector<string> output;\n\n    partitionHelper(s, 0,  output, result);\n\n    return result;\n\n}\n\nvoid printMatrix(vector< vector<string> > &matrix)\n{\n    for(int i=0; i<matrix.size(); i++){\n        cout << \"{ \";\n        for(int j=0; j< matrix[i].size(); j++) {\n            cout << matrix[i][j] << \", \";\n        }\n        cout << \"}\" << endl;\n    }\n    cout << endl;\n}\n\n\nint main(int argc, char** argv)\n{\n    string s(\"aab\");\n    if ( argc > 1 ){\n        s = argv[1];\n    }\n\n    vector< vector<string> > result = partition(s);\n\n    printMatrix(result);\n}\n"
  },
  {
    "path": "algorithms/cpp/palindromicSubstrings/PalindromicSubstrings.cpp",
    "content": "// Source : https://leetcode.com/problems/palindromic-substrings/\n// Author : Hao Chen\n// Date   : 2019-01-30\n\n/***************************************************************************************************** \n *\n * \n * Given a string, your task is to count how many palindromic substrings in this string.\n * \n * The substrings with different start indexes or end indexes are counted as different substrings even \n * they consist of same characters. \n * \n * Example 1:\n * \n * Input: \"abc\"\n * Output: 3\n * Explanation: Three palindromic strings: \"a\", \"b\", \"c\".\n * \n * Example 2:\n * \n * Input: \"aaa\"\n * Output: 6\n * Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".\n * \n * Note:\n * \n * The input string length won't exceed 1000.\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    int countSubstrings(string s) {\n        int len = s.size();\n        if (len<=1) return len;\n        \n        vector< vector<bool> > dp(len, vector<bool>(len, false));\n        \n        int cnt = 0;\n        for( int i=len-1; i>=0; i--) {\n            for (int j=i; j<=len-1; j++) {              \n                if ( i == j  || ( s[i] == s[j] && ( j-i<2 || dp[i+1][j-1]) ) ) {\n                    dp[i][j] = true;\n                    cnt++;\n                }\n            }\n        }\n                                  \n        return cnt;       \n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp",
    "content": "// Source : https://leetcode.com/problems/partition-equal-subset-sum/description/\n// Author : Hao Chen\n// Date   : 2018-06-24\n\n/*************************************************************************************** \n *\n * Given a non-empty array containing only positive integers, find if the array can be \n * partitioned into two subsets such that the sum of elements in both subsets is equal.\n * \n * \n * Note:\n * \n * Each of the array element will not exceed 100.\n * The array size will not exceed 200.\n * \n * \n * \n * Example 1:\n * \n * Input: [1, 5, 11, 5]\n * \n * Output: true\n * \n * Explanation: The array can be partitioned as [1, 5, 5] and [11].\n * \n * \n * \n * Example 2:\n * \n * Input: [1, 2, 3, 5]\n * \n * Output: false\n * \n * Explanation: The array cannot be partitioned into equal sum subsets.\n * \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    //back tracking\n    bool canPartitionRecrusion(vector<int>& nums, int half, int index) {\n        for (int i=index; i<nums.size(); i++){\n            int h = half - nums[i];\n            if ( h < 0 ) return false; //cannot found the solution\n            if ( h == 0 ) return true; //found the solution\n            if ( canPartitionRecrusion(nums, h, i+1) == true ) return true;\n        }\n        return false;\n    }\n\n    \n    bool canPartition(vector<int>& nums) {\n        int sum = 0;\n        for(auto n : nums) sum +=n;\n        if ( sum & 1 ) return false; // sum % 2 !=  1\n        int half = sum / 2;\n        \n        //sort the array in descending order\n        //so, the DFS could be very fast to find the answer because it's greedy.\n        std::sort(nums.begin(), nums.end(), std::greater<int>()); \n\n        //go to find a path which sum is half\n        return canPartitionRecrusion(nums, half, 0);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/partitionList/partitionList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/partition-list/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a linked list and a value x, partition it such that all nodes less than x come \n* before nodes greater than or equal to x.\n* \n* You should preserve the original relative order of the nodes in each of the two partitions.\n* \n* For example,\n* Given 1->4->3->2->5->2 and x = 3,\n* return 1->2->2->4->3->5.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *partition(ListNode *head, int x) {\n    ListNode fakeHead(0);\n    fakeHead.next = head;\n    head = &fakeHead;\n    \n    ListNode *pos = NULL;\n    for(ListNode *p = head; p!=NULL && p->next!=NULL; ){\n        if (!pos && p->next->val >= x){\n            pos = p;\n            p=p->next;\n            continue;\n        }\n        if (pos && p->next->val < x){\n            ListNode *pNext = p->next;\n            p->next = pNext->next;\n            pNext->next = pos->next;\n            pos->next = pNext;\n            pos = pNext;\n            continue;\n        }\n        p=p->next;\n    }\n    \n    return head->next;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\nint main()\n{\n    //int a[] = {1}; int x =2;\n    //int a[] = {2,3,1}; int x=2;\n    int a[] = {3,1,2}; int x=3;\n    ListNode* p = createList(a, sizeof(a)/sizeof(int)); \n    printList(p);\n    p = partition(p, x);\n    printList(p);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/pascalTriangle/pascalTriangle.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/pascals-triangle-ii/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Given an index k, return the kth row of the Pascal's triangle.\n* \n* For example, given k = 3,\n* Return [1,3,3,1].\n* \n* Note:\n* Could you optimize your algorithm to use only O(k) extra space?\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <vector>\n#include <iostream>\nusing namespace std;\n\nvector<int> getRow(int rowIndex) {\n    vector<int> v(rowIndex+1, 0);\n    v[0]=1;\n\n    for (int i=0; i<rowIndex; i++){\n        for(int j=i+1; j>0; j--){\n           v[j] += v[j-1];\n        } \n    }\n    return v;\n    \n}\n\nvoid printVector( vector<int>  pt)\n{\n    cout << \"{ \";\n    for(int j=0; j<pt.size(); j++){\n        cout << pt[j] << \", \";\n    }\n    cout << \"} \" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    int n = 3;\n    if (argc>1) {  \n        n = atoi(argv[1]);\n    }\n    printVector(getRow(n)); \n}\n"
  },
  {
    "path": "algorithms/cpp/pascalTriangle/pascalTriangle.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/pascals-triangle/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Given numRows, generate the first numRows of Pascal's triangle.\n* \n* For example, given numRows = 5,\n* Return\n* \n* [\n*      [1],\n*     [1,1],\n*    [1,2,1],\n*   [1,3,3,1],\n*  [1,4,6,4,1]\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <vector>\n#include <iostream>\nusing namespace std;\n\nvector<vector<int> > generate(int numRows) \n{\n    vector<vector<int> > pascalTriangle;\n    for (int i=0; i<numRows; i++){\n        vector<int> v;\n        if (i==0){\n            v.push_back(1);\n        } else {\n            v.push_back(1);\n            for(int j=0; j<pascalTriangle[i-1].size()-1; j++){\n                v.push_back(pascalTriangle[i-1][j] + pascalTriangle[i-1][j+1]);\n            }\n            v.push_back(1);\n        }\n        pascalTriangle.push_back(v); \n    }\n    return pascalTriangle;\n}\n\nvoid printTriangle(vector< vector<int> > pt)\n{\n\tcout << \"[\" << endl;\n    for(int i=0; i<pt.size(); i++){\n    \tfor(int space=(pt.size()-i-1); space>=0; space--){\n    \t\tcout << \" \";\n    \t}\n        cout << \"[\";\n        for(int j=0; j<pt[i].size(); j++){\n            cout << pt[i][j];\n            if(j<pt[i].size()-1){\n            \tcout << \",\";\n            }\n        }\n        cout << \"]\";\n        if(i<pt.size()-1){\n        \tcout << \",\";\n        }\n        cout << endl;\n    }\n    cout << \"]\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    int n = 3;\n    if (argc>1) {\n        n = atoi(argv[1]);\n    }\n    printTriangle(generate(n)); \n}\n"
  },
  {
    "path": "algorithms/cpp/patchingArray/PatchingArray.cpp",
    "content": "// Source : https://leetcode.com/problems/patching-array/\n// Author : Hao Chen\n// Date   : 2016-03-01\n\n/*************************************************************************************** \n *\n * Given a sorted positive integer array nums and an integer n, add/patch elements to \n * the array such that any number in range [1, n] inclusive can be formed by the sum of \n * some elements in the array. Return the minimum number of patches required.\n * \n * Example 1:\n * nums = [1, 3], n = 6\n * Return 1.\n * \n * Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\n * Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], \n * [1,2,3].\n * Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\n * So we only need 1 patch.\n * \n * Example 2:\n * nums = [1, 5, 10], n = 20\n * Return 2.\n * The two patches can be [2, 4].\n * \n * Example 3:\n * nums = [1, 2, 2], n = 5\n * Return 0.\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    int minPatches(vector<int>& nums, int n) {\n        return minPatches_02(nums, n);\n        return minPatches_01(nums, n);\n    }\n    \n    \n    // Greedy Algorithm\n    // (Assume the array is sorted already)\n    //\n    //   Let do some observation at first,\n    //\n    //     1) if we have [1,2] then we can cover 1, 2, 3\n    //     2) if we have [1,2,3] then we can cover 1,2,3,4,5,6\n    //     So, it looks we can simply add all of nums together, then we can find out max number we can reach.\n    //\n    //     3) if we have [1,2,5], we can see \n    //       3.1) [1,2] can cover 1,2,3, but we cannot reach 4, \n    //       3.2) then we patch 4, then we have [1,2,4] which can cover 1,2,3(1+2),4,5(1+4),6(2+4), 7(1+2+4)\n    //       3.3) we can see [1,2,4] can reach to 7 - sum all of them\n    //       3.4) then [1,2,4,5], we can reach to 12 - 1,2,3,4,5,6,7,8(1+2+5),9(4+5),10(1+4+5), 11(2+4+5), 12(1+2+4+5)\n    //   \n    //   So, we can have figure out our solution\n    //\n    //      0) considering the `n` we need to cover.\n    //      1) maintain a variable we are trying to patch, suppose named `try_patch`\n    //      2) if `try_patch` >= nums[i] then, we just keep add the current array item, \n    //         and set the `try_patch` to the next patch candidate number -  `sum+1`\n    //      3) if `try_patch` < nums[i], which means we need to patch.\n    //\n    int minPatches_01(vector<int>& nums, int n) {\n        long covered = 0; //avoid integer overflow\n        int patch_cnt = 0;\n        int i = 0;\n        while (i<nums.size() ){\n            // set the `try_patch` is the next number which we cannot cover\n            int try_patch = covered + 1;\n            // if the `try_patch` can cover the current item, then just sum it, \n            // then we can have the max number we can cover so far \n            if ( try_patch >= nums[i])  {\n                covered += nums[i];  \n                i++;\n            } else { // if the `try_patch` cannot cover the current item, then we find the number we need to patch\n                patch_cnt++;\n                //cout << \"patch \" << try_patch << endl;\n                covered = covered + try_patch;\n            } \n            \n            if (covered >=n) break;\n        }\n        //for the case - [1], 7\n        //the above while-loop just process all of the numbers in the array, \n        //but we might not reach the goal, so, we need keep patching.\n        while (covered < n) {\n            int try_patch = covered + 1;\n            patch_cnt++;\n            //cout << \"patch \" << try_patch << endl;\n            covered = covered + try_patch;\n        }\n        return patch_cnt;\n    }\n    \n    \n    //The following solution just re-organizes the solution above, and make it shorter \n    int minPatches_02(vector<int>& nums, int n) {\n        long covered = 0;\n        int patch_cnt = 0;\n        int i = 0;\n        while ( covered < n){\n            if (i<nums.size() && nums[i] <= covered + 1) {\n                covered += nums[i++];\n            }else{\n                //cout << \"patch \" << covered + 1 << endl;\n                covered = 2 * covered + 1;\n                patch_cnt++;\n            }\n        }\n        return patch_cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/pathSum/pathSum.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/path-sum-ii/\n// Author : Hao Chen\n// Date   : 2014-07-01\n\n/********************************************************************************** \n* \n* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.\n* \n* For example:\n* Given the below binary tree and sum = 22,\n* \n*               5\n*              / \\\n*             4   8\n*            /   / \\\n*           11  13  4\n*          /  \\    / \\\n*         7    2  5   1\n* \n* return\n* \n* [\n*    [5,4,11,2],\n*    [5,8,4,5]\n* ]\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int> > pathSum(TreeNode *root, int sum) {\n        vector<vector<int> > result;\n        vector<int> v;\n        generatePathSum(root, sum, 0, v, result);\n        return result;\n    }\n\n    void generatePathSum(TreeNode *root, int sum, int s, vector<int> v, vector<vector<int> >& result) {\n        if (root==NULL) return ;\n\n        s += root->val;\n        v.push_back(root->val);\n\n        if ( root->left==NULL && root->right==NULL) {\n            if (s == sum) result.push_back(v);\n            return;\n        }\n\n        generatePathSum(root->left, sum, s, v, result);\n        generatePathSum(root->right, sum, s, v, result);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/pathSum/pathSum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/path-sum/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given a binary tree and a sum, determine if the tree has a root-to-leaf path \n* such that adding up all the values along the path equals the given sum.\n* \n* For example:\n* Given the below binary tree and sum = 22,\n* \n*               5\n*              / \\\n*             4   8\n*            /   / \\\n*           11  13  4\n*          /  \\      \\\n*         7    2      1\n* \n* return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.\n*               \n**********************************************************************************/\n\n#include <time.h>\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n    bool hasPathSum(TreeNode *root, int sum) {\n        return hasPathSum3(root, sum, 0);\n        return hasPathSum2(root, sum);\n        return hasPathSum1(root, sum);    \n    }\n\n    bool hasPathSum3(TreeNode* root, int sum, int s) {\n        if ( root == NULL) return false;\n        s += root->val;\n        if ( !root->left && !root->right)  return s == sum;\n        return (hasPathSum3(root->left, sum, s) || hasPathSum3(root->right, sum, s));\n    }\n    \n    bool hasPathSum1(TreeNode *root, int sum) {\n        if (root==NULL) return false;\n        vector<TreeNode*> v;\n        v.push_back(root);\n        while(v.size()>0){\n            TreeNode* node = v.back();\n            v.pop_back();\n            if (node->left==NULL && node->right==NULL){\n                if (node->val == sum){\n                    return true;\n                }\n            }\n            if (node->left){\n                node->left->val += node->val;\n                v.push_back(node->left);\n            }\n            if (node->right){\n                node->right->val += node->val;\n                v.push_back(node->right);\n            }\n        }\n        return false;\n        \n    }\n    \n    bool hasPathSum2(TreeNode *root, int sum) {\n        \n        if (root==NULL) return false;\n        \n        if (root->left==NULL && root->right==NULL ){\n            return (root->val==sum);\n        }\n        \n        if (root->left){\n            root->left->val += root->val;\n            if (hasPathSum2(root->left, sum)){\n                return true;\n            }\n        }\n        \n        if (root->right){\n            root->right->val += root->val;\n            if (hasPathSum2(root->right, sum)){\n                return true;\n            }\n        }\n        \n        return false;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/peakIndexInAMountainArray/PeakIndexInAMountainArray.cpp",
    "content": "// Source : https://leetcode.com/problems/peak-index-in-a-mountain-array/description/\n// Author : Hao Chen\n// Date   : 2018-06-29\n\n/*************************************************************************************** \n *\n * Let's call an array A a mountain if the following properties hold:\n * \n * \n * \tA.length >= 3\n * \tThere exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < \n * A[i] > A[i+1] > ... > A[A.length - 1]\n * \n * \n * Given an array that is definitely a mountain, return any i such that A[0] < A[1] < \n * ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].\n * \n * Example 1:\n * \n * \n * Input: [0,1,0]\n * Output: 1\n * \n * \n * \n * Example 2:\n * \n * \n * Input: [0,2,1,0]\n * Output: 1\n * \n * \n * Note:\n * \n * \n * \t3 <= A.length <= 10000\n * \t0 <= A[i] <= 10^6\n * \tA is a mountain, as defined above.\n * \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int peakIndexInMountainArray(vector<int>& A) {\n        \n        // Put two dummy items at head and tail to avoid Out-of-Bound Error.\n        #define INT_MAX 2147483647\n        #define INT_MIN (-INT_MAX - 1)\n        A.insert ( A.begin() , INT_MIN );\n        A.push_back(INT_MIN);\n        \n        //binary search\n        int len = A.size();\n        int left = 1, right = len - 2;\n        while(left <= right) {\n            int mid = left + (right - left)/2; //avoid integer overflow\n            if ( A[mid-1] < A[mid] && A[mid] > A[mid+1]) return mid-1;\n            if ( A[mid-1] < A[mid] && A[mid] < A[mid+1]) left = mid + 1;\n            if ( A[mid-1] > A[mid] && A[mid] > A[mid+1]) right = mid - 1;\n            \n        }\n        return -1;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/peekingIterator/PeekingIterator.cpp",
    "content": "// Source : https://leetcode.com/problems/peeking-iterator/\n// Author : Hao Chen\n// Date   : 2015-11-10\n\n/*************************************************************************************** \n *\n * Given an Iterator class interface with methods: next() and hasNext(), design and \n * implement a PeekingIterator that support the peek() operation -- it essentially \n * peek() at the element that will be returned by the next call to next().\n * \n * Here is an example. Assume that the iterator is initialized to the beginning of the \n * list: [1, 2, 3].\n * \n * Call next() gets you 1, the first element in the list.\n * \n * Now you call peek() and it returns 2, the next element. Calling next() after that \n * still return 2.\n * \n * You call next() the final time and it returns 3, the last element. Calling hasNext() \n * after that should return false.\n * \n *   Think of \"looking ahead\". You want to cache the next element.\n *   Is one variable sufficient? Why or why not?\n *   Test your design with call order of peek() before next() vs next() before peek().\n *   For a clean implementation, check out Google's guava library source code.\n * \n * Follow up: How would you extend your design to be generic and work with all types, \n * not just integer?\n * \n * Credits:Special thanks to @porker2008 for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n// Below is the interface for Iterator, which is already defined for you.\n// **DO NOT** modify the interface for Iterator.\nclass Iterator {\n    struct Data;\n    Data* data;\npublic:\n    Iterator(const vector<int>& nums);\n    Iterator(const Iterator& iter);\n    virtual ~Iterator();\n    // Returns the next element in the iteration.\n    int next();\n    // Returns true if the iteration has more elements.\n    bool hasNext() const;\n};\n\n\nclass PeekingIterator : public Iterator {\nprivate:\n    bool m_hasNext;\n    int m_next;\n    \n    void takeNext() {\n        m_hasNext = Iterator::hasNext();\n        if (m_hasNext) {\n            m_next = Iterator::next();\n        }  \n    }\npublic:\n    PeekingIterator(const vector<int>& nums) : Iterator(nums) {\n        // Initialize any member here.\n        // **DO NOT** save a copy of nums and manipulate it directly.\n        // You should only use the Iterator interface methods.\n        takeNext();\n    }\n\n    // Returns the next element in the iteration without advancing the iterator.\n    int peek() {\n        return m_next;\n    }\n\n    // hasNext() and next() should behave the same as in the Iterator interface.\n    // Override them if needed.\n    int next() {\n        int temp = m_next;\n        takeNext();\n        return temp;\n        \n    }\n\n    bool hasNext() const {\n        return m_hasNext;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/perfectRectangle/PerfectRectangle.cpp",
    "content": "// Source : https://leetcode.com/problems/perfect-rectangle/\n// Author : Hao Chen\n// Date   : 2016-09-08\n\n/*************************************************************************************** \n *\n * Given N axis-aligned rectangles where N > 0, determine if they all together form an \n * exact cover of a rectangular region.\n * \n * Each rectangle is represented as a bottom-left point and a top-right point. For \n * example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point \n * is (1, 1) and top-right point is (2, 2)).\n * \n * Example 1:\n * \n * rectangles = [\n *   [1,1,3,3],\n *   [3,1,4,2],\n *   [3,2,4,4],\n *   [1,3,2,4],\n *   [2,3,3,4]\n * ]\n * \n * Return true. All 5 rectangles together form an exact cover of a rectangular region.\n * \n * Example 2:\n * \n * rectangles = [\n *   [1,1,2,3],\n *   [1,3,2,4],\n *   [3,1,4,2],\n *   [3,2,4,4]\n * ]\n * \n * Return false. Because there is a gap between the two rectangular regions.\n * \n * Example 3:\n * \n * rectangles = [\n *   [1,1,3,3],\n *   [3,1,4,2],\n *   [1,3,2,4],\n *   [3,2,4,4]\n * ]\n * \n * Return false. Because there is a gap in the top center.\n * \n * Example 4:\n * \n * rectangles = [\n *   [1,1,3,3],\n *   [3,1,4,2],\n *   [1,3,2,4],\n *   [2,2,4,4]\n * ]\n * \n * Return false. Because two of the rectangles overlap with each other.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    bool isRectangleCover(vector<vector<int>>& rectangles) {\n        unordered_map<string,int> mp;\n        string corners[4];\n        for(auto v: rectangles)\n            for(int i = 0; i<4; ++i){\n                corners[i] = to_string(v[i/2*2]) + \",\" + to_string(v[(i%2)*2+1]);\n                if(mp[corners[i]] & int(pow(2,i))) return false;\n                else mp[corners[i]] |= int(pow(2,i));\n            }\n        int corner = 0;\n        for(auto i=mp.begin(); i!=mp.end(); ++i){\n            int val = i->second;\n            if(!(val & (val-1)) && (++corner >4)) return false;\n            if((val & (val-1)) && !(val == 3 || val==12 || val==10 || val==5 || val==15)) return false;\n        }\n        return true;        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/perfectSquares/PerfectSquares.cpp",
    "content": "// Source : https://leetcode.com/problems/perfect-squares/\n// Author : Hao Chen\n// Date   : 2015-10-25\n\n/*************************************************************************************** \n *\n * Given a positive integer n, find the least number of perfect square numbers (for \n * example, 1, 4, 9, 16, ...) which sum to n.\n * \n * For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 \n * because 13 = 4 + 9.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n\n    int numSquares(int n) {\n        return numSquares_dp_opt(n); //12ms\n        return numSquares_dp(n); //232ms\n    }\n    \n    /*\n     * Dynamic Programming\n     * ===================\n     *   dp[0] = 0 \n     *   dp[1] = dp[0]+1 = 1\n     *   dp[2] = dp[1]+1 = 2\n     *   dp[3] = dp[2]+1 = 3\n     *   dp[4] = min{ dp[4-1*1]+1, dp[4-2*2]+1 } \n     *         = min{ dp[3]+1, dp[0]+1 } \n     *         = 1               \n     *   dp[5] = min{ dp[5-1*1]+1, dp[5-2*2]+1 } \n     *         = min{ dp[4]+1, dp[1]+1 } \n     *         = 2\n     *   dp[6] = min{ dp[6-1*1]+1, dp[6-2*2]+1 } \n     *         = min{ dp[5]+1, dp[2]+1 } \n     *         = 3\n     *   dp[7] = min{ dp[7-1*1]+1, dp[7-2*2]+1 } \n     *         = min{ dp[6]+1, dp[3]+1 } \n     *         = 4\n     *   dp[8] = min{ dp[8-1*1]+1, dp[8-2*2]+1 } \n     *         = min{ dp[7]+1, dp[4]+1 } \n     *         = 2\n     *   dp[9] = min{ dp[9-1*1]+1, dp[9-2*2]+1, dp[9-3*3] } \n     *         = min{ dp[8]+1, dp[5]+1, dp[0]+1 } \n     *         = 1\n     *   dp[10] = min{ dp[10-1*1]+1, dp[10-2*2]+1, dp[10-3*3] } \n     *          = min{ dp[9]+1, dp[6]+1, dp[1]+1 } \n     *          = 2\n     *                           ....\n     *\n     *   So, the dynamic programm formula is\n     *   \n     *      dp[n] = min{ dp[n - i*i] + 1 },  n - i*i >=0 && i >= 1\n     *\n     */\n    int numSquares_dp(int n) {\n        if ( n <=0 ) return 0;\n        \n        int *dp = new int[n+1];\n        dp[0] = 0;\n        \n        for (int i=1; i<=n; i++ ) {\n            int m = n;\n            for (int j=1; i-j*j >= 0; j++) {\n                m = min (m, dp[i-j*j] + 1);\n            }\n            dp[i] = m;\n        }\n    \n        return dp[n];\n        delete [] dp;\n    }\n    \n    //using cache to optimize the dp algorithm\n    int numSquares_dp_opt(int n) {\n        if ( n <=0 ) return 0;\n        \n        static vector<int> dp(1, 0);\n        if (dp.size() >= (n+1) ) return dp[n];\n        \n        for (int i=dp.size(); i<=n; i++ ) {\n            int m = n;\n            for (int j=1; i-j*j >= 0; j++) {\n                m = min (m, dp[i-j*j] + 1);\n            }\n            dp.push_back(m);\n        }\n    \n        return dp[n];\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/permutationSequence/permutationSequence.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/permutation-sequence/\n// Author : Hao Chen\n// Date   : 2014-08-22\n\n/********************************************************************************** \n* \n* The set [1,2,3,…,n] contains a total of n! unique permutations.\n* \n* By listing and labeling all of the permutations in order,\n* We get the following sequence (ie, for n = 3):\n* \n* \"123\"\n* \"132\"\n* \"213\"\n* \"231\"\n* \"312\"\n* \"321\"\n* \n* Given n and k, return the kth permutation sequence.\n* \n* Note: Given n will be between 1 and 9 inclusive.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\n/*\n\"123\"\n\"132\"\n\"213\"\n\"231\"\n\"312\"\n\"321\"\n*/\n\nvoid nextPermutation(vector<int>& num); \n\n/* Extreamly Optimized */\nstring getPermutation(int n, int k) {\n    vector<int> num;\n    int total = 1;\n    for(int i=1; i<=n; i++){\n        num.push_back(i);\n        total *= i;\n    }\n\n    //invalid k;\n    if( total < k ) {\n        return \"\";\n    }\n\n    // Construct the k-th permutation with a list of n numbers\n    // Idea: group all permutations according to their first number (so n groups, each of\n    // (n-1)! numbers), find the group where the k-th permutation belongs, remove the common\n    // first number from the list and append it to the resulting string, and iteratively\n    // construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers\n    int group = total;\n    stringstream ss;\n    while (n>0) {\n        group = group / n;\n        int idx = (k-1) / group;\n        ss << num[idx];\n        num.erase(num.begin()+idx);\n        n--;\n        //the next k also can be caculated like this: \n        //    k = (k-1)%group + 1; \n        k -= group * idx;\n    }\n\n    return ss.str();\n}\n\n\n\n/* Optimization by determining the group */\nstring getPermutation_0(int n, int k) {\n    vector<int> num;\n    int total = 1;\n    for(int i=1; i<=n; i++){\n        num.push_back(i);\n        total *= i;\n    }\n\n    //invalid k;\n    if( total < k ) {\n        return \"\";\n    }\n    int group = total / n;\n    int idx = (k-1) / group;\n    int nn = num[idx];\n    num.erase(num.begin()+idx);\n    num.insert(num.begin(), nn);\n\n    int offset = (k-1) % group;\n    for(int i=0; i<offset; i++) {\n        nextPermutation(num);\n    }\n\n    //string result;\n    stringstream ss;\n    for(int i=0; i<n; i++){\n        ss << num[i];\n    }\n\n    return ss.str();\n}\n\n/* Time Limit Exceeded */\nstring getPermutation_1(int n, int k) {\n    vector<int> num;\n    for(int i=1; i<=n; i++){\n        num.push_back(i);\n    }\n\n    for(int i=1; i<k; i++) {\n        nextPermutation(num);\n    }\n\n    //string result;\n    stringstream ss;\n    for(int i=0; i<n; i++){\n        ss << num[i];\n    }\n\n    return ss.str();\n}\n\n\n\nvoid nextPermutation(vector<int>& num) {\n    if (num.size()<=1) return;\n    for (int i=num.size()-1; i>0; i-- ) {\n        if (num[i-1] < num[i]) {\n            int j = num.size() - 1;\n            while( num[i-1] > num[j] ) {\n                j--;\n            }\n            int temp = num[i-1];\n            num[i-1] = num[j];\n            num[j] = temp;\n\n            reverse(num.begin()+i, num.end());\n            return;\n        }\n    }\n\n    reverse( num.begin(), num.end() );\n}\n\n\nint main(int argc, char**argv)\n{\n    int n=3, k=6;\n    if ( argc > 2 ) {\n        n = atoi(argv[1]);\n        k = atoi(argv[2]);\n    }\n    cout << \"n = \" << n << \", k = \" << k << \" : \" << getPermutation(n, k) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/permutations/permutations.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/permutations-ii/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a collection of numbers that might contain duplicates, return all possible unique permutations.\n* \n* For example,\n* [1,1,2] have the following unique permutations:\n* [1,1,2], [1,2,1], and [2,1,1].\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n// To deal with the duplication number, we need do those modifications:\n//    1) sort the array [pos..n].\n//    2) skip the same number.\nvector<vector<int> > permute(vector<int> &num) {\n\n    vector<vector<int> > vv;\n    vv.push_back(num);\n\n    if (num.size() <2){\n        return vv;\n    }\n        \n    int pos=0;\n    while(pos<num.size()-1){\n        int size = vv.size();\n        for(int i=0; i<size; i++){\n            //sort the array, so that the same number will be together\n            sort(vv[i].begin()+pos, vv[i].end());\n            //take each number to the first\n            for (int j=pos+1; j<vv[i].size(); j++) {\n                vector<int> v = vv[i];\n                //skip the same number \n                if (j>0 && v[j]==v[j-1]){\n                    continue;\n                }\n                int t = v[j]; \n                v[j] = v[pos];\n                v[pos] = t;\n                vv.push_back(v);\n            }\n        }\n        pos++;\n    }\n    return vv;\n}\n\nvoid printVector( vector<int>&  pt)\n{\n    cout << \"{ \";\n    for(int j=0; j<pt.size(); j++){\n        cout << pt[j] << \" \";\n    }\n    cout << \"} \" << endl;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 3;\n    if (argc>1){\n       n = atoi(argv[1]); \n    }\n\n    srand(time(NULL));\n    vector<int> v;\n    for (int i=0; i<n; i++) {\n        v.push_back(random()%n+1);\n    }\n    /*v[0] =0;\n    v[1] =1;\n    v[2] =0;\n    v[3] =0;\n    v[4] =9;*/\n\n    printVector(v); \n    cout << \"-----------------\" << endl;\n\n\n    vector<vector<int> > vv;\n    vv = permute(v);\n    \n    for(int i=0; i<vv.size(); i++) {\n        printVector(vv[i]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/permutations/permutations.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/permutations/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a collection of numbers, return all possible permutations.\n* \n* For example,\n* [1,2,3] have the following permutations:\n* [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n/*\n{ 1 2 3 }\n{ 2 1 3 }\n{ 3 2 1 }\n{ 1 3 2 }\n{ 2 3 1 }\n{ 3 1 2 }\n*/\n\n/*\n *    The algroithm - Take each element in array to the first place.\n *\n *    For example: \n *    \n *         0) initalization \n * \n *             pos = 0\n *             [1, 2, 3]   \n *\n *         1) take each element into the first place, \n *\n *             pos = 1\n *             [1, 2, 3]  ==>  [2, 1, 3] , [3, 1, 2] \n *\n *             then we have total 3 answers\n *             [1, 2, 3],  [2, 1, 3] , [3, 1, 2] \n *            \n *         2) take each element into the \"first place\" -- pos \n *\n *             pos = 2\n *             [1, 2, 3]  ==>  [1, 3, 2]\n *             [2, 1, 3]  ==>  [2, 3, 1]\n *             [3, 1, 2]  ==>  [3, 2, 1] \n *\n *             then we have total 6 answers\n *             [1, 2, 3],  [2, 1, 3] , [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]\n *\n *          3) pos = 3 which greater than length of array, return.\n *\n */\nvector<vector<int> > permute(vector<int> &num) {\n    \n    vector<vector<int> > vv;\n    vv.push_back(num);\n\n    if (num.size() <2){\n        return vv;\n    }\n        \n    int pos=0;\n    while(pos<num.size()-1){\n        int size = vv.size();\n        for(int i=0; i<size; i++){\n            //take each number to the first place\n            for (int j=pos+1; j<vv[i].size(); j++) {\n                vector<int> v = vv[i];\n                int t = v[j]; \n                v[j] = v[pos];\n                v[pos] = t;\n                vv.push_back(v);\n            }\n        }\n        pos++;\n    }\n    return vv;\n}\n\nint main(int argc, char** argv)\n{\n    int n = 3;\n    if (argc>1){\n       n = atoi(argv[1]); \n    }\n\n    vector<int> v;\n    for (int i=0; i<n; i++) {\n        v.push_back(i+1);\n    }\n    vector<vector<int> > vv;\n    vv = permute(v);\n    \n    for(int i=0; i<vv.size(); i++) {\n        cout << \"{ \";\n        for(int j=0; j<vv[i].size(); j++){\n            cout << vv[i][j] << \" \";\n        }\n        cout << \"}\" <<endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/plusOne/plusOne.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/plus-one/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a non-negative number represented as an array of digits, plus one to the number.\n* \n* The digits are stored such that the most significant digit is at the head of the list.\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector<int> plusOne(vector<int> &digits) {\n    int carry=1;\n    vector <int> v;\n    while(digits.size()>0){\n        int x = digits.back();\n        digits.pop_back();\n        x = x + carry;\n        v.insert(v.begin(), x%10);\n        carry = x/10;\n    }\n    if (carry>0){\n        v.insert(v.begin(), carry);\n    }\n    return v;\n\n}\n\nvoid printVector(vector<int>& v)\n{\n    cout << \"{ \";\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] << \" \";\n    }\n    cout << \"} \" << endl;\n}\n\n\nint main()\n{\n    int a[]={9,9,9};\n    vector<int> d(&a[0], &a[0]+sizeof(a)/sizeof(int));\n    vector<int> v = plusOne(d);\n    printVector(v);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/\n// Author : Hao Chen\n// Date   : 2014-06-19\n\n/********************************************************************************** \n* \n* Follow up for problem \"Populating Next Right Pointers in Each Node\".\n* What if the given tree could be any binary tree? Would your previous solution still work?\n* \n* Note:\n* You may only use constant extra space.\n* \n* For example,\n* Given the following binary tree,\n* \n*          1\n*        /  \\\n*       2    3\n*      / \\    \\\n*     4   5    7\n* \n* After calling your function, the tree should look like:\n* \n*          1 -> NULL\n*        /  \\\n*       2 -> 3 -> NULL\n*      / \\    \\\n*     4-> 5 -> 7 -> NULL\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <vector>\n#include <queue>\nusing namespace std;\n\n/**\n * Definition for binary tree with next pointer.\n */\nstruct TreeLinkNode {\n    int val;\n    TreeLinkNode *left, *right, *next;\n    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n    TreeLinkNode() : val(0), left(NULL), right(NULL), next(NULL) {}\n};\nvoid connect(TreeLinkNode *root) {\n    if (root==NULL) return;\n\n    if (root->left && root->right){\n        root->left->next = root->right;\n    }\n\n    if (root->next) {\n        \n         TreeLinkNode *left=NULL, *right=NULL;\n         left = root->right ? root->right: root->left;\n\n         for (TreeLinkNode *p = root->next; p!=NULL; p=p->next) {\n             if (p->left){\n                 right = p->left;\n                 break;\n             }\n             if (p->right){\n                 right = p->right;\n                 break;\n             }\n         }\n         if (left){\n             left->next = right;\n         }   \n    }\n    connect(root->right);\n    connect(root->left);\n}\n\nvoid connect1(TreeLinkNode *root) {\n\n    if (root==NULL){\n        return;\n    }\n    \n    vector<TreeLinkNode*> v;\n\n    v.push_back(root);\n    \n    while(v.size()>0){\n        \n        if ( (root->left && root->left->next==NULL) || (root->right && root->right->next==NULL) ) {\n\n            if (root->left && root->right){\n                root->left->next = root->right;\n            }\n            \n            if (root->next){\n                TreeLinkNode *left=NULL, *right=NULL;\n                left = root->right ? root->right: root->left;\n                \n                for (TreeLinkNode *p = root->next; p!=NULL; p=p->next) {\n                    if (p->left){\n                        right = p->left;\n                        break;\n                    }\n                    if (p->right){\n                        right = p->right;\n                        break;\n                    }\n                }\n\n                if (left){\n                    left->next = right;\n                }   \n            }\n            if (root->left) {\n                v.push_back(root->left);\n            }\n            if (root->right) {\n                v.push_back(root->right);\n            }\n        }\n        root = v.back();\n        v.pop_back();\n    }\n}\n\nvoid connect3(TreeLinkNode *root) {\n    if(root == NULL) return;\n\n    queue<TreeLinkNode*> q;\n    TreeLinkNode *prev, *last;\n    prev = last = root;\n\n    q.push(root);\n    while(!q.empty()) {\n        TreeLinkNode* p = q.front();\n        q.pop();\n\n        prev->next = p;\n        if(p->left ) q.push(p->left);\n        if(p->right) q.push(p->right);\n\n        if(p == last) { // meets last of current level\n            // now, q contains all nodes of next level\n            last = q.back();\n            p->next = NULL; // cut down.\n            prev = q.front();\n        }\n        else {\n            prev = p;\n        }\n    }\n}\n\n// constant space\n// key point: we can use `next` pointer to represent\n//      the buffering queue of level order traversal.\nvoid connect4(TreeLinkNode *root) {\n    if(root == NULL) return;\n\n    TreeLinkNode *head, *tail;\n    TreeLinkNode *prev, *last;\n\n    head = tail = NULL;\n    prev = last = root;\n\n#define push(p) \\\n    if(head == NULL) { head = tail = p; } \\\n    else { tail->next = p; tail = p; }\n\n    push(root);\n    while(head != NULL) {\n        TreeLinkNode* p = head;\n        head = head->next; // pop\n\n        prev->next = p;\n        if(p->left ) push(p->left);\n        if(p->right) push(p->right);\n\n        if(p == last) {\n            last = tail;\n            p->next = NULL; // cut down.\n            prev = head;\n        }\n        else {\n            prev = p;\n        }\n    }\n#undef push\n}\n\nvoid printTree(TreeLinkNode *root){\n    if (root == NULL){\n        return;\n    }\n    printf(\"[%2d] : left[%d], right[%d], next[%d]\\n\",\n            root->val,\n            root->left ? root->left->val : -1,\n            root->right ? root->right->val : -1,\n            root->next?root->next->val : -1 );\n\n    printTree(root->left);\n    printTree(root->right);\n\n}\n\n\nint main()\n{\n    const int cnt = 15; \n    TreeLinkNode a[cnt];\n    for(int i=0; i<cnt; i++){\n        a[i].val = i+1;\n    } \n    \n    for(int i=0, pos=0; pos<cnt-1; i++ ){\n        a[i].left = &a[++pos];\n        a[i].right = &a[++pos];\n    }\n    a[5].left = a[5].right = NULL;\n    a[3].right = NULL;\n\n    //a[1].right = NULL;\n    //a[2].left = NULL;\n\n    //a[3].left = &a[4];\n    //a[6].right= &a[5];\n    TreeLinkNode b(100), c(200);\n    //a[3].left = &b;\n    //a[6].right = &c;\n    a[9].left = &b;\n\n    connect(&a[0]); \n\n    printTree(&a[0]);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/\n// Author : Hao Chen\n// Date   : 2014-06-19\n\n/********************************************************************************** \n* \n* Given a binary tree\n* \n*     struct TreeLinkNode {\n*       TreeLinkNode *left;\n*       TreeLinkNode *right;\n*       TreeLinkNode *next;\n*     }\n* \n* Populate each next pointer to point to its next right node. \n* If there is no next right node, the next pointer should be set to NULL.\n* \n* Initially, all next pointers are set to NULL.\n* \n* Note:\n* \n* You may only use constant extra space.\n* You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).\n* \n* For example,\n* Given the following perfect binary tree,\n* \n*          1\n*        /  \\\n*       2    3\n*      / \\  / \\\n*     4  5  6  7\n* \n* After calling your function, the tree should look like:\n* \n*          1 -> NULL\n*        /  \\\n*       2 -> 3 -> NULL\n*      / \\  / \\\n*     4->5->6->7 -> NULL\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <vector>\n#include <queue>\nusing namespace std;\n\n/**\n * Definition for binary tree with next pointer.\n */\nstruct TreeLinkNode {\n    int val;\n    TreeLinkNode *left, *right, *next;\n    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n    TreeLinkNode() : val(0), left(NULL), right(NULL), next(NULL) {}\n};\n\n\nvoid connect(TreeLinkNode *root) {\n\n    if (root==NULL){\n        return;\n    }\n    if (root->left && root->right){\n        root->left->next = root->right;\n    }\n    if (root->next && root->right){\n        root->right->next = root->next->left;\n    }\n    connect(root->left);\n    connect(root->right);\n\n}\n\nvoid connect1(TreeLinkNode *root) {\n\n    if (root==NULL){\n        return;\n    }\n\n    vector<TreeLinkNode*> v;    \n    v.push_back(root);\n    int i = 0;\n    \n    while (i < v.size()){\n        if (v[i]->left){\n            v.push_back(v[i]->left);\n        }\n        if (v[i]->right) {\n            v.push_back(v[i]->right);\n        }\n        i++;\n    }\n\n    i=1;\n    while(i<v.size()){\n        for (int j=i-1; j<2*(i-1); j++){\n           v[j]->next = v[j+1]; \n        }\n        i *= 2; \n    }\n\n}\n\nvoid connect2(TreeLinkNode *root) {\n\n    if (root==NULL){\n        return;\n    }\n    \n    vector<TreeLinkNode*> v;\n\n    v.push_back(root);\n    \n    while(v.size()>0){\n        \n        if (root->left && root->right && root->left->next == NULL ) {\n            root->left->next = root->right;\n            \n            if (root->next){\n                root->right->next = root->next->left;\n            }\n            \n            v.push_back(root->right);\n            v.push_back(root->left);\n        }\n        root=v.back();\n        v.pop_back();\n    }\n}\n\nvoid connect3(TreeLinkNode *root) {\n    if(root == NULL) return;\n\n    queue<TreeLinkNode*> q;\n    TreeLinkNode *prev, *last;\n    prev = last = root;\n\n    q.push(root);\n    while(!q.empty()) {\n        TreeLinkNode* p = q.front();\n        q.pop();\n\n        prev->next = p;\n        if(p->left ) q.push(p->left);\n        if(p->right) q.push(p->right);\n\n        if(p == last) { // meets last of current level\n            // now, q contains all nodes of next level\n            last = q.back();\n            p->next = NULL; // cut down.\n            prev = q.front();\n        }\n        else {\n            prev = p;\n        }\n    }\n}\n\n// constant space\n// key point: we can use `next` pointer to represent\n//      the buffering queue of level order traversal.\nvoid connect4(TreeLinkNode *root) {\n    if(root == NULL) return;\n\n    TreeLinkNode *head, *tail;\n    TreeLinkNode *prev, *last;\n\n    head = tail = NULL;\n    prev = last = root;\n\n#define push(p) \\\n    if(head == NULL) { head = tail = p; } \\\n    else { tail->next = p; tail = p; }\n\n    push(root);\n    while(head != NULL) {\n        TreeLinkNode* p = head;\n        head = head->next; // pop\n\n        prev->next = p;\n        if(p->left ) push(p->left);\n        if(p->right) push(p->right);\n\n        if(p == last) {\n            last = tail;\n            p->next = NULL; // cut down.\n            prev = head;\n        }\n        else {\n            prev = p;\n        }\n    }\n#undef push\n}\n\nvoid printTree(TreeLinkNode *root){\n    if (root == NULL){\n        return;\n    }\n    printf(\"[%d], left[%d], right[%d], next[%d]\\n\", \n            root->val, \n            root->left ? root->left->val : -1, \n            root->right ? root->right->val : -1, \n            root->next?root->next->val : -1 );    \n\n    printTree(root->left);\n    printTree(root->right);\n \n}\n\nint main()\n{\n    const int cnt = 7; \n    TreeLinkNode a[cnt];\n    for(int i=0; i<cnt; i++){\n        a[i].val = i+1;\n    } \n\n    \n    for(int i=0, pos=0;  pos < cnt-1; i++ ){\n        a[i].left = &a[++pos];\n        a[i].right = &a[++pos];\n    }\n    \n    connect(&a[0]); \n\n    printTree(&a[0]);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/pow/pow.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/powx-n/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Implement pow(x, n).\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n\n/*\n *   Basically, most people think this is very easy as below:\n *\n *      double result = 1.0;\n *      for (int i=0; i<n; i++){\n *           result *=x;\n *      }\n *   \n *   However, \n *\n *     1) We need think about the `n` is negtive number.\n *\n *     2) We need more wisely deal with the following cases:\n *\n *         pow(1, MAX_INT);\n *         pow(-1,BIG_INT);\n *         pow(2, BIG_INT);\n *\n *        To deal with such kind case, we can use x = x*x to reduce the `n` more quickly\n *\n *        so, if `n` is an even number, we can `x = x*x`, and `n = n>>1;`\n *            if `n` is an odd number, we can just `result *= x;`\n *\n */\ndouble pow(double x, int n) {\n\n    bool sign = false;\n    unsigned int exp = n;\n    if(n<0){\n        exp = -n;\n        sign = true;\n    }\n    double result = 1.0;\n    while (exp) {\n        if (exp & 1){\n            result *= x;\n        }\n        exp >>= 1;\n        x *= x;\n    }\n\n    return sign ? 1/result : result;\n\n}\n\nint main(int argc, char** argv){\n    double x=2.0;\n    int n = 3;\n    if (argc==3){\n        x = atof(argv[1]);\n        n = atoi(argv[2]);\n    }\n    printf(\"%f\\n\", pow(x, n));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/powerOfFour/PowerOfFour.cpp",
    "content": "// Source : https://leetcode.com/problems/power-of-four/\n// Author : Hao Chen\n// Date   : 2016-05-29\n\n/*************************************************************************************** \n *\n * Given an integer (signed 32 bits), write a function to check whether it is a power \n * of 4.\n * \n * Example:\n * Given num = 16, return true.\n * Given num = 5, return false.\n * \n * Follow up: Could you solve it without loops/recursion?\n * \n * Credits:Special thanks to @yukuairoy  for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    bool isPowerOfFour(int num) {\n        static int mask = 0b01010101010101010101010101010101;\n        \n        //edge case\n        if (num<=0) return false;\n        \n        // there are multiple bits are 1\n        if ((num & num-1) != 0) return false;\n        \n        // check which one bit is zero, if the place is 1 or 3 or 5 or 7 or 9...,\n        // then it is the power of 4\n        if ((num & mask) != 0) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/powerOfThree/PowerOfThree.cpp",
    "content": "// Source : https://leetcode.com/problems/power-of-three/\n// Author : Hao Chen\n// Date   : 2016-01-14\n\n/*************************************************************************************** \n *\n * Given an integer, write a function to determine if it is a power of three.\n * \n *     Follow up:\n *     Could you do it without using any loop / recursion?\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\nclass Solution {\n\npublic:\n    \n    bool isPowerOfThree(int n) {\n        return isPowerOfThree03(n); //140ms\n        return isPowerOfThree02(n);//130ms\n        return isPowerOfThree01(n); //140ms\n        return isPowerOfThree_loop(n);  //136ms\n        return isPowerOfThree_recursive(n); //168ms\n    }\n    \n    bool isPowerOfThree03(int n) {\n        double logRes = log10(n)/log10(3); \n        return (logRes - int(logRes) == 0);\n    }\n    bool isPowerOfThree02(int n) {\n        return n>0 ? (1162261467%n==0) : false;\n    }\n    \n    void init(unordered_map<int, bool>& power ){\n        int p = 1;\n        power[1]=true;\n        while(1){\n            p *= 3;\n            power[p] = true;\n            if (p > INT_MAX/3) break;\n            \n        }\n    }\n    bool isPowerOfThree01(int n) {\n        static unordered_map<int, bool> power; \n        if (power.size()==0) init(power);\n        return power.find(n) != power.end();\n    }\n    \n    bool isPowerOfThree_loop(int n) {\n        for(;n>0;n /= 3){\n            if (n==1 || n==3) return true;\n            if (n%3 != 0) return false;\n        }\n        return false;\n    }\n    \n    bool isPowerOfThree_recursive(int n) {\n        if ( n == 1 || n == 3) return true;\n        if ( n==0 || n%3 != 0 ) return false;\n        return isPowerOfThree_recursive(n/3);\n    } \n};\n"
  },
  {
    "path": "algorithms/cpp/powerOfTwo/PowerOfTwo.cpp",
    "content": "// Source : https://leetcode.com/problems/power-of-two/\n// Author : Hao Chen\n// Date   : 2015-07-16\n\n/********************************************************************************** \n * \n * Given an integer, write a function to determine if it is a power of two.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n *               \n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n\n    // count the number fo bits 1, if it only has one, then return true\n    bool isPowerOfTwo01(int n) {\n        int cnt = 0; //num of bits 1\n        for(; n>0; n>>=1){\n            if ( n & 1 ) {\n                cnt++;\n                if (cnt>1) return false;\n            }\n        }\n        return cnt==1;\n    }\n    \n    //we notice: 2^n - 1 always be 1111111...\n    //so, (2^n) & (2^n-1) always be zero\n    bool isPowerOfTwo02(int n) {\n        return n<=0 ? false : (n & (n-1)) == 0;\n    }\n    \n    bool isPowerOfTwo(int n) {\n        if (random()%2){\n            return isPowerOfTwo02(n);\n        }\n        return isPowerOfTwo01(n);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/processTasksUsingServers/ProcessTasksUsingServers.cpp",
    "content": "// Source : https://leetcode.com/problems/process-tasks-using-servers/\n// Author : Hao Chen\n// Date   : 2021-05-30\n\n/***************************************************************************************************** \n *\n * You are given two 0-indexed integer arrays servers and tasks of lengths n and m \n * respectively. servers[i] is the weight of the i^th server, and tasks[j] is the time \n * needed to process the j^th task in seconds.\n * \n * You are running a simulation system that will shut down after all tasks are processed. Each server \n * can only process one task at a time. You will be able to process the j^th task starting from the \n * j^th second beginning with the 0^th task at second 0. To process task j, you assign it to the \n * server with the smallest weight that is free, and in case of a tie, choose the server with the \n * smallest index. If a free server gets assigned task j at second t, it will be free again at \n * the second t + tasks[j].\n * \n * If there are no free servers, you must wait until one is free and execute the free tasks as soon as \n * possible. If multiple tasks need to be assigned, assign them in order of increasing index.\n * \n * You may assign multiple tasks at the same second if there are multiple free servers.\n * \n * Build an array ans of length m, where ans[j] is the index of the server the j^th task \n * will be assigned to.\n * \n * Return the array ans.\n * \n * Example 1:\n * \n * Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]\n * Output: [2,2,0,2,1,2]\n * Explanation: Events in chronological order go as follows:\n * - At second 0, task 0 is added and processed using server 2 until second 1.\n * - At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n * - At second 2, task 2 is added and processed using server 0 until second 5.\n * - At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n * - At second 4, task 4 is added and processed using server 1 until second 5.\n * - At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n * \n * Example 2:\n * \n * Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\n * Output: [1,4,1,4,1,3,2]\n * Explanation: Events in chronological order go as follows: \n * - At second 0, task 0 is added and processed using server 1 until second 2.\n * - At second 1, task 1 is added and processed using server 4 until second 2.\n * - At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until \n * second 4. \n * - At second 3, task 3 is added and processed using server 4 until second 7.\n * - At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n * - At second 5, task 5 is added and processed using server 3 until second 7.\n * - At second 6, task 6 is added and processed using server 2 until second 7.\n * \n * Constraints:\n * \n * \tservers.length == n\n * \ttasks.length == m\n * \t1 <= n, m <= 2 * 10^5\n * \t1 <= servers[i], tasks[j] <= 2 * 10^5\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    template<class T>\n    void print(T  q) {\n        cout << \"[\";\n        while(!q.empty()) {\n            auto& p = q.top(); \n            cout << \"[\" << p.first << \",\"<< p.second << \"]\";\n            q.pop();\n        }\n        cout << \"]\" << endl;\n    }\npublic:\n    \n    vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {\n        typedef pair<int,int> IntPair;\n        typedef priority_queue<IntPair, vector<IntPair>, greater<IntPair>> PriorityQueue;\n        \n        // asc sorted by {weight, index}\n        PriorityQueue idle;\n        // asc sorted by {time, index}\n        PriorityQueue busy;\n        \n        for(int i=0; i<servers.size(); i++){\n            idle.push({servers[i], i});\n        }\n        \n        //print(idle);\n        \n        int time = 0;\n        vector<int> ans;\n        for(int i=0; i<tasks.size(); i++) {\n            time = max(i, time);\n\n            //check the tasks finished\n            while(true) { \n                while(!busy.empty()){\n                    auto& t = busy.top().first;\n                    auto& id = busy.top().second;\n                    if (t > time) break;\n                    idle.push({servers[id], id});\n                    busy.pop();\n                }\n                if (!idle.empty())  break;\n                //set the time to the fisrt finish running task \n                time = busy.top().first;\n            }\n            \n            //process the current task\n            auto& id = idle.top().second;\n            ans.push_back(id);\n            busy.push({time + tasks[i], id});\n            idle.pop();\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp",
    "content": "// Source : https://leetcode.com/problems/product-of-array-except-self/\n// Author : Hao Chen\n// Date   : 2015-07-17\n\n/********************************************************************************** \n * \n * Given an array of n integers where n > 1, nums, return an array output such that \n * output[i] is equal to the product of all the elements of nums except nums[i].\n * \n * Solve it without division and in O(n).\n * \n * For example, given [1,2,3,4], return [24,12,8,6].\n * \n * Follow up:\n * Could you solve it with constant space complexity? (Note: The output array does not \n * count as extra space for the purpose of space complexity analysis.)\n *               \n **********************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> productExceptSelf(vector<int>& nums) {\n        \n        int len = nums.size();\n        vector<int> result(len, 1);\n        \n        //from the left to right \n        for (int i=1; i<len; i++) {\n            result[i] = result[i-1]*nums[i-1];\n        }\n        //from the right to left\n        int factorial = 1;\n        for (int i=len-2; i>=0; i--){\n            factorial *= nums[i+1];\n            result[i] *= factorial;\n        }\n        return result;\n    }\n};\n\n\n\n"
  },
  {
    "path": "algorithms/cpp/queriesOnNumberOfPointsInsideACircle/QueriesOnNumberOfPointsInsideACircle.cpp",
    "content": "// Source : https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * You are given an array points where points[i] = [xi, yi] is the coordinates of the i^th point on a \n * 2D plane. Multiple points can have the same coordinates.\n * \n * You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at \n * (xj, yj) with a radius of rj.\n * \n * For each query queries[j], compute the number of points inside the j^th circle. Points on the \n * border of the circle are considered inside.\n * \n * Return an array answer, where answer[j] is the answer to the j^th query.\n * \n * Example 1:\n * \n * Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\n * Output: [3,2,2]\n * Explanation: The points and circles are shown above.\n * queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\n * \n * Example 2:\n * \n * Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\n * Output: [2,3,2,4]\n * Explanation: The points and circles are shown above.\n * queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n * \n * Constraints:\n * \n * \t1 <= points.length <= 500\n * \tpoints[i].length == 2\n * \t0 <= x​​​​​​i, y​​​​​​i <= 500\n * \t1 <= queries.length <= 500\n * \tqueries[j].length == 3\n * \t0 <= xj, yj <= 500\n * \t1 <= rj <= 500\n * \tAll coordinates are integers.\n * \n * Follow up: Could you find the answer for each query in better complexity than O(n)?\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    //refer to: https://stackoverflow.com/a/7227057/13139221\n    bool inCircle( vector<int>& point,  vector<int>& circle ) {\n        int x = point[0], y = point[1];\n        int xo = circle[0], yo = circle[1], r = circle[2];\n        \n        int dx = abs(x-xo);\n        if ( dx > r ) return false;\n        int dy = abs(y-yo);\n        if ( dy > r ) return false;\n        if ( dx + dy <= r ) return true;\n        return ( dx*dx + dy*dy <= r*r );\n    }\npublic:\n    vector<int> countPoints(vector<vector<int>>& points, vector<vector<int>>& queries) {\n        vector<int> result;\n        for(auto& c : queries) {\n            int cnt = 0;\n            for(auto& p : points) {\n                if ( inCircle(p, c) ) cnt++;\n            }\n            result.push_back(cnt);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp",
    "content": "// Source : https://leetcode.com/problems/queue-reconstruction-by-height/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * Suppose you have a random list of people standing in a queue. Each person is \n * described by a pair of integers (h, k), where h is the height of the person and k is \n * the number of people in front of this person who have a height greater than or equal \n * to h. Write an algorithm to reconstruct the queue.\n * \n * Note:\n * The number of people is less than 1,100.\n * \n * Example\n * \n * Input:\n * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]\n * \n * Output:\n * [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]\n ***************************************************************************************/\n\nclass Solution {\n\npublic:\n    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {\n        //sort function\n        auto comp = [](const pair<int, int>& p1, const pair<int, int>& p2)\n                    { return p1.first == p2.first ? p1.second < p2.second : p1.first > p2.first; };\n        //sort the people with their height with descending order\n        // and if the height is same then sort by K with ascending order\n        sort(people.begin(), people.end(), comp);\n        \n        // For example:\n        // Original Queue:  [7,0], [4,4], [7,1], [5,0], [6,1], [5,2]\n        //   Sorted Queue:  [7,0], [7,1], [6,1], [5,0], [5,2], [4,4] \n        \n        \n        // Why do we need to sort like this?\n        //\n        //     ** The position of shorter people is ZERO impacted with higher people. **\n        //    \n        // and, the shortest people has no impacts to all of people. we can simpley insert it to the Kth position\n        //\n        // So, we sorted the people from highest to the shortest, then when we insert the people to another array,\n        //\n        // we always can guarantee the people is going to be inserted has nothing to do with the people has been inserted.\n        //   \n        // Let's continue the about example above\n        //\n        //    [7,0] => []                                then [7,0]\n        //    [7,1] => [7,0]                             then [7,0], [7,1]\n        //    [6,1] => [7,0], [7,1]                      then [7,0], [6,1], [7,1]\n        //    [5,0] => [7,0], [6,1], [7,1]               then [5,0], [7,0], [6,1], [7,1]\n        //    [5,2] => [5,0], [7,0], [6,1], [7,1]        then [5,0], [7,0], [5,2], [6,1], [7,1]\n        //    [4,4] => [5,0], [7,0], [5,2], [6,1], [7,1] then [5,0], [7,0], [5,2], [6,1], [4,4], [7,1]\n        //\n        // We alway can see, the people is going to be inserted has NO IMPACT with the current people.\n        //     \n        //    [6,1] => [7,0], [7,1]  \n        // \n        //    Whatever the people[6,1] placed, it has nothing to do with the people [7,0] [7,1],\n        //    So, we can just insert the people to the place he like - the `Kth` place. \n        //\n        //\n        vector<pair<int, int>> res;\n        for (auto& p : people) {\n            res.insert(res.begin() + p.second, p);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/randomPickIndex/RandomPickIndex.cpp",
    "content": "// Source : https://leetcode.com/problems/random-pick-index/\n// Author : Hao Chen\n// Date   : 2016-11-04\n\n/*************************************************************************************** \n *\n * Given an array of integers with possible duplicates, randomly output the index of a \n * given target number. You can assume that the given target number must exist in the \n * array.\n * \n * Note:\n * The array size can be very large. Solution that uses too much extra space will not \n * pass the judge.\n * \n * Example:\n * \n * int[] nums = new int[] {1,2,3,3,3};\n * Solution solution = new Solution(nums);\n * \n * // pick(3) should return either index 2, 3, or 4 randomly. Each index should have \n * equal probability of returning.\n * solution.pick(3);\n * \n * // pick(1) should return 0. Since in the array only nums[0] is equal to 1.\n * solution.pick(1);\n ***************************************************************************************/\n\nclass Solution {\nprivate:\n    vector<int> nums;    \npublic:\n    Solution(vector<int> nums) {\n        srand(time(0));\n        this->nums = nums;\n    }\n    \n    int pick(int target) {\n\t// we just randomly pick a number from the array,\n        // if the number is target just return the index.\n        // otherwise, keep picking the number randomly.\n        while(true) {\n            int idx = rand() % nums.size();\n            if ( target == nums[idx] ) {\n                return idx;\n            }\n        }\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(nums);\n * int param_1 = obj.pick(target);\n */\n"
  },
  {
    "path": "algorithms/cpp/randomPointInNonOverlappingRectangles/randomPointInNonOverlappingRectangles.cpp",
    "content": "// Source : https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/submissions/ \n// Author : rqj\n// Date   : 2020-10-10\n\n/********************************************************************************** \n *\n * Given a list of non-overlapping axis-aligned rectangles rects, write a function\n * pick which randomly and uniformily picks an integer point in the space covered\n * by the rectangles.\n *\n * Note:\n * 1. An integer point is a point that has integer coordinates. \n * 2. A point on the perimeter of a rectangle is included in the space covered by\n * the rectangles. \n * 3. ith rectangle = rects[i] = [x1,y1,x2,y2], where [x1, y1] are the integer\n * coordinates of the bottom-left corner, and [x2, y2] are the integer coordinates\n * of the top-right corner.\n * 4. length and width of each rectangle does not exceed 2000.\n * 5. 1 <= rects.length <= 100\n * 6. pick return a point as an array of integer coordinates [p_x, p_y]\n * 7. pick is called at most 10000 times.\n *\n * Example 1:\n * Input:\n * [\"Solution\",\"pick\",\"pick\",\"pick\"]\n * [[[[1,1,5,5]]],[],[],[]]\n * Output: [null,[4,1],[4,1],[3,3]]\n * \n * Example 2:\n * Input: \n * [\"Solution\",\"pick\",\"pick\",\"pick\",\"pick\",\"pick\"]\n * [[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]\n * Output: [null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-2]]\n *\n * Explanation of Input Syntax:\n * The input is two lists: the subroutines called and their arguments.\n * Solution's constructor has one argument, the array of rectangles rects. pick\n * has no arguments. Arguments are always wrapped with a list, even if there aren't\n * any.\n *\n **********************************************************************************/\n\nclass Solution {\npublic:\n    //attributes\n    vector<vector<int>> rects_b; //copy of the given 'rects' vector\n    vector<int> points_until; //value of element 'e' = num of points in all rects before 'e', including it\n\n    Solution(vector<vector<int>>& rects) {\n        for (auto &e : rects) {\n            int before = (points_until.size() == 0) ? 0 : points_until.back(); //points before 'e'\n            points_until.push_back((e[2] - e[0] + 1) * (e[3] - e[1] + 1) + before);\n            rects_b = rects;\n        }\n    }\n\n    vector<int> pick() {\n        int ind = rand() % points_until.back(); //randomly choose one of the points counted\n        int rect = upper_bound(points_until.begin(), points_until.end(), ind) - points_until.begin();\n        ind -= (rect == 0) ? 0 : points_until[rect - 1];\n        int row = rects_b[rect][3] - rects_b[rect][1] + 1;\n        return {ind/row + rects_b[rect][0], ind%row + rects_b[rect][1]};\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Immutable.cpp",
    "content": "// Source : https://leetcode.com/problems/range-sum-query-immutable/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2015-11-10\n\n/*************************************************************************************** \n *\n * Given an integer array nums, find the sum of the elements between indices i and j\n * (i ≤ j), inclusive.\n * \n * Example:\n * Given nums = [-2, 0, 3, -5, 2, -1]\n * \n * sumRange(0, 2) -> 1\n * sumRange(2, 5) -> -1\n * sumRange(0, 5) -> -3\n * Note:\n * You may assume that the array does not change.\n * There are many calls to sumRange function.\n *               \n ***************************************************************************************/\n\nclass NumArray {\n/* \n * Solution\n * =========\n *\n * The sum of all the elements starting from position 0 to position i is stored in\n * sums[i]. This way we can reconstruct the sum from position i to position j by\n * subtracting sums[i - 1] from sums[j], leaving us with the sum of the desired elements.\n *\n * Note: we can add a dummy sum at then beginning to simplify the code\n * \n */\nprivate:\n    int size;\n    vector <long long> sums;\npublic:\n    NumArray(vector<int> &nums): size(nums.size()), sums(size+1, 0) {\n        for(int i=0; i<size; i++) {\n            sums[i+1] = sums[i] + nums[i];\n        } \n    }\n    int sumRange(int i, int j) {\n        return sums[j+1] - sums[i];\n    }\n};\n\n\n// Your NumArray object will be instantiated and called as such:\n// NumArray numArray(nums);\n// numArray.sumRange(0, 1);\n// numArray.sumRange(1, 2);\n"
  },
  {
    "path": "algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Mutable/RangeSumQueryMutable.cpp",
    "content": "// Source : https://leetcode.com/problems/range-sum-query-mutable/\n// Author : Hao Chen\n// Date   : 2015-11-24\n\n/*************************************************************************************** \n *\n * Given an integer array nums, find the sum of the elements between indices i and j (i \n * ≤ j), inclusive.\n * \n * The update(i, val) function modifies nums by updating the element at index i to val.\n * \n * Example:\n * \n * Given nums = [1, 3, 5]\n * \n * sumRange(0, 2) -> 9\n * update(1, 2)\n * sumRange(0, 2) -> 8\n * \n * Note:\n * \n * The array is only modifiable by the update function.\n * You may assume the number of calls to update and sumRange function is distributed \n * evenly.\n *\n ***************************************************************************************/\n\n\n// The following idea is using `Binary Index Tree`\n// There are two articles explaine this technique quite well:\n// 1) http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/\n// 2) http://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a\n\nclass NumArray {\nprivate:\n    int _sz;\n    vector<int> _nums;\n    vector<int> _sums;    \npublic:\n    NumArray(vector<int> &nums)  {\n        _sz = nums.size();\n        _nums.resize(_sz+1, 0);\n        _sums.resize(_sz+1, 0);\n        for(int i=0; i< _sz; i++) {\n            update(i, nums[i]);          \n        }\n    }\n\n    void update(int i, int val) {\n        int oldv = _nums[i+1];\n        for(int idx = i+1; idx <= _sz; idx += (idx & (-idx))  ) {\n            _sums[idx] = _sums[idx] - oldv + val;\n        }\n        _nums[i+1] = val;\n    }\n\n    int sumRange(int i, int j) {\n        return sumRange(j+1) - sumRange(i);\n    }\n    \n    int sumRange(int i) {\n        int ret = 0;\n        for(int idx=i; idx>0; idx -= (idx & (-idx)) ) {\n            ret += _sums[idx];\n        }\n        return ret;\n    }\n};\n\n\n// Your NumArray object will be instantiated and called as such:\n// NumArray numArray(nums);\n// numArray.sumRange(0, 1);\n// numArray.update(1, 10);\n// numArray.sumRange(1, 2);\n"
  },
  {
    "path": "algorithms/cpp/rangeSumQuery2D-Immutable/RangeSumQuery2dImmutable.cpp",
    "content": "// Source : https://leetcode.com/problems/range-sum-query-2d-immutable/\n// Author : Hao Chen\n// Date   : 2015-11-14\n\n/*************************************************************************************** \n *\n * Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined \n * by its upper left corner (row1, col1) and lower right corner (row2, col2).\n * \n * The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and \n * (row2, col2) = (4, 3), which contains sum = 8.\n * \n * Example:\n * \n * Given matrix = [\n *   [3, 0, 1, 4, 2],\n *   [5, 6, 3, 2, 1],\n *   [1, 2, 0, 1, 5],\n *   [4, 1, 0, 1, 7],\n *   [1, 0, 3, 0, 5]\n * ]\n * \n * sumRegion(2, 1, 4, 3) -> 8\n * sumRegion(1, 1, 2, 2) -> 11\n * sumRegion(1, 2, 2, 4) -> 12\n * \n * Note:\n * \n * You may assume that the matrix does not change.\n * There are many calls to sumRegion function.\n * You may assume that row1 ≤ row2 and col1 ≤ col2.\n * \n ***************************************************************************************/\n\n\n/*\n * \n * Construct a 2D array `sums[row+1][col+1]`\n * \n * (**notice**: we add additional blank row `sums[0][col+1]={0}` and blank column `sums[row+1][0]={0}` \n * to remove the edge case checking), so, we can have the following definition \n * \n *     `sums[i+1][j+1]` represents the sum of area from `matrix[0][0]` to `matrix[i][j]`\n * \n * To calculate sums, the ideas as below\n * \n *     +-----+-+-------+     +--------+-----+     +-----+---------+     +-----+--------+\n *     |     | |       |     |        |     |     |     |         |     |     |        |\n *     |     | |       |     |        |     |     |     |         |     |     |        |\n *     +-----+-+       |     +--------+     |     |     |         |     +-----+        |\n *     |     | |       |  =  |              |  +  |     |         |  -  |              |\n *     +-----+-+       |     |              |     +-----+         |     |              |\n *     |               |     |              |     |               |     |              |\n *     |               |     |              |     |               |     |              |\n *     +---------------+     +--------------+     +---------------+     +--------------+\n *     \n *        sums[i][j]      =    sums[i-1][j]    +     sums[i][j-1]    -   sums[i-1][j-1]   +  \n * \n *                             matrix[i-1][j-1]\n * \n * So, we use the same idea to find the specific area's sum.\n * \n * \n * \n *     +---------------+   +--------------+   +---------------+   +--------------+   +--------------+\n *     |               |   |         |    |   |   |           |   |         |    |   |   |          |\n *     |   (r1,c1)     |   |         |    |   |   |           |   |         |    |   |   |          |\n *     |   +------+    |   |         |    |   |   |           |   +---------+    |   +---+          |\n *     |   |      |    | = |         |    | - |   |           | - |      (r1,c2) | + |   (r1,c1)    |\n *     |   |      |    |   |         |    |   |   |           |   |              |   |              |\n *     |   +------+    |   +---------+    |   +---+           |   |              |   |              |\n *     |        (r2,c2)|   |       (r2,c2)|   |   (r2,c1)     |   |              |   |              |\n *     +---------------+   +--------------+   +---------------+   +--------------+   +--------------+\n * \n * \n */\n\nclass NumMatrix {\nprivate:\n    int row, col;\n    vector<vector<int>> sums;\npublic:\n    NumMatrix(vector<vector<int>> &matrix) {\n        row = matrix.size();\n        col = row>0 ? matrix[0].size() : 0;\n        sums = vector<vector<int>>(row+1, vector<int>(col+1, 0));\n        for(int i=1; i<=row; i++) {\n            for(int j=1; j<=col; j++) {\n                sums[i][j] = sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] + matrix[i-1][j-1];\n            }\n        }\n    }\n\n    int sumRegion(int row1, int col1, int row2, int col2) {\n        return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1];\n    }\n};\n\n\n// Your NumMatrix object will be instantiated and called as such:\n// NumMatrix numMatrix(matrix);\n// numMatrix.sumRegion(0, 1, 2, 3);\n// numMatrix.sumRegion(1, 2, 3, 4);\n"
  },
  {
    "path": "algorithms/cpp/ransomNote/RansomNote.cpp",
    "content": "// Source : https://leetcode.com/problems/ransom-note/\n// Author : Hao Chen\n// Date   : 2016-08-24\n\n/*************************************************************************************** \n *\n *  Given  an  arbitrary  ransom  note  string  and  another  string  containing \n *  letters from  all  the  magazines,  write  a  function  that  will  return  true \n *  if  the  ransom  \n * note  can  be  constructed  from  the  magazines ;  otherwise,  it  will  return \n *  false.   \n * \n * Each  letter  in  the  magazine  string  can  only  be  used  once  in  your \n *  ransom  note.\n * \n * Note:\n * You may assume that both strings contain only lowercase letters.\n * \n * canConstruct(\"a\", \"b\") -> false\n * canConstruct(\"aa\", \"ab\") -> false\n * canConstruct(\"aa\", \"aab\") -> true\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    bool canConstruct(string ransomNote, string magazine) {\n        unordered_map<char, int> m;\n        for(int i=0; i<magazine.size(); i++) {\n            m[magazine[i]]++;\n        }\n        for (int i=0; i<ransomNote.size(); i++) {\n            char c = ransomNote[i];\n            if (m[c] <=0 ) return false;\n            m[c]--;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/readNCharactersGivenRead4/readNCharactersGivenRead4.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/\n// Author : Hao Chen\n// Date   : 2014-12-01\n\n\n/*\n * The API: int read4(char *buf) reads 4 characters at a time from a file.\n * \n * The return value is the actual number of characters read. \n * For example, it returns 3 if there is only 3 characters left in the file.\n * \n * By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.\n * \n * Note:\n * The read function may be called multiple times.\n */\n\n\n/*\n *  The key to solve this problem is: \n *\n *    You have to buffer the extra data return from `read4()` API, which is for next call for `read()` .\n */\n\n#include <stdio.h>\n#include <string.h>\n// Forward declaration of the read4 API.\nstatic char input[64];\nstatic char *p = input;\n\nint read4(char *buf) {\n\n    int s=0;\n    for (; s<4 && *p!='\\0'; s++){\n        buf[s] = *p;\n        p++;\n    } \n    return s;\n}\n\n\nclass RingBuffer {\n\n    public:\n        RingBuffer(int cap=4): _capacity(cap) {\n            _size = 0;\n\n            _pbuf = new char[_capacity];\n            _p = _pbuf;\n            _pend = _pbuf + _capacity - 1;\n        } \n        ~RingBuffer(){\n            delete _pbuf;\n        }\n        int read(char* buf, int n){\n            //empty, nothing can read\n            if (_size==0) return 0;\n\n            //read `n` or all \n            int s;\n            for (s=0; s<n && s<_size; s++){\n                buf[s] = *_p;\n                _p = (_p < _pend) ? _p + 1 : _pbuf;  \n            }\n            _size -= s;\n            return s;\n        }\n\n        int write(char* buf, int n) {\n            //full, cannot write\n            if (_size >= _capacity) return 0;\n\n            //write `n` or all\n            int s;\n            char *p = _p + _size;\n            for (s=0; s < _capacity - _size && s < n; s++){\n                *p = buf[s];\n                p = (p < _pend) ? p + 1 : _pbuf;\n            }\n            _size += s;\n            return s;\n        }\n\n    private:\n        const int   _capacity;\n        int         _size;\n\n        char*       _pbuf;\n        char*       _p;\n        char*       _pend;\n\n};\n\nclass Solution {\n    public:\n        /**\n         * @param buf Destination buffer\n         * @param n   Maximum number of characters to read\n         * @return    The number of characters read\n         */\n        int read(char *buf, int n) {\n            int buf_size = 0;\n            int api_size = 0;\n\n            //read the data from the RingBuffer at first\n            buf_size = _ring_buffer.read(buf, n);\n            if (buf_size == n) {\n                return n;\n            }\n            n = n - buf_size;\n\n            //read the data from the API at second\n            api_size = read1(buf + buf_size, n);\n\n            return buf_size + api_size;\n        }\n\n        // The read1 implementation is from the `Read N Characters Given Read4` problem\n        // Add the feature - write the extra char(s) into RingBuffer\n        int read1(char *buf, int n) {\n            char _buf[4];   // the buffer for read4()\n            int _n = 0;     // the return for read4()\n            int len = 0;    // total buffer read from read4()\n            int size = 0;   // how many bytes need be copied from `_buf` to `buf`\n            while((_n = read4(_buf)) > 0){\n                //check the space of `buf` whether full or not\n                size = len + _n > n ? n-len : _n;\n                //write the extra char(s) into RingBuffer\n                if (len + _n > n ){\n                    _ring_buffer.write(_buf + size, _n - size);    \n                }\n                strncpy(buf+len, _buf, size);\n                len += size;\n                //buffer is full\n                if (len>=n){\n                    break;\n                }\n            }\n            return len;\n        }\n\n\n    private: \n        RingBuffer _ring_buffer;\n};\n\n\nint main()\n{\n    Solution s;\n    const int buf_len = 10;\n    char buf[buf_len]={0};\n#define SET_INPUT(s)    strcpy(input, s); p=input; printf(\"input data = \\\"%s\\\"\\n\", p);\n#define CLEAR_BUFFER()  memset(buf, 0, sizeof(buf)/sizeof(buf[0]) )\n#define READ(s, buf, n) CLEAR_BUFFER(); printf(\"read(%d) => \",n); s.read(buf, n); printf(\"%s\\n\", buf);\n\n    printf(\"-----------------------------\\n\");\n    SET_INPUT(\"1234abcd1234abcdxyz\");\n    for(int i=0; i<5; i++){\n        READ(s, buf, 4);\n    }\n    printf(\"-----------------------------\\n\");\n    SET_INPUT(\"ab\");\n    READ(s, buf, 1);\n    READ(s, buf, 2);\n\n    printf(\"-----------------------------\\n\");\n    SET_INPUT(\"abcde\");\n    for(int i=0; i<5; i++){\n        READ(s, buf, 1);\n    }\n    printf(\"-----------------------------\\n\");\n    SET_INPUT(\"1234xyzabcd00\");\n    READ(s, buf, 4);\n    for(int i=0; i<3; i++){\n        READ(s, buf, 1);\n    }\n    READ(s, buf, 4);\n    printf(\"-----------------------------\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/readNCharactersGivenRead4/readNCharactersGivenRead4.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/read-n-characters-given-read4/\n// Author : Hao Chen\n// Date   : 2014-11-20\n\n/********************************************************************************** \n * \n * The API: int read4(char *buf) reads 4 characters at a time from a file.\n * \n * The return value is the actual number of characters read. \n * For example, it returns 3 if there is only 3 characters left in the file.\n * \n * By using the read4 API, implement the function int read(char *buf, int n) \n * that reads n characters from the file.\n * \n * Note:\n *   The read function will only be called once for each test case.\n * \n **********************************************************************************/\n\n\n// Forward declaration of the read4 API.\nint read4(char *buf);\n\nclass Solution {\n    public:\n        /**\n         * @param buf Destination buffer\n         * @param n   Maximum number of characters to read\n         * @return    The number of characters read\n         */\n        int read(char *buf, int n) {\n            srand(time(0));\n            if (rand()%2){\n                return read1(buf, n);\n            }\n            return read2(buf, n);\n        }\n\n        //read the data in-place. potential out-of-boundary issue\n        int read1(char *buf, int n) {\n            int len = 0;\n            int size = 0;\n\n            // `buf` could be accessed out-of-boundary \n            while(len <=n && (size = read4(buf))>0){\n                size = len + size > n ?  n - len : size;\n                len += size;\n                buf += size;\n            }\n            return  len;\n        }\n\n        //using a temp-buffer to avoid peotential out-of-boundary issue\n        int read2(char *buf, int n) {\n            char _buf[4];   // the buffer for read4()\n            int _n = 0;     // the return for read4()\n            int len = 0;    // total buffer read from read4()\n            int size = 0;   // how many bytes need be copied from `_buf` to `buf`\n            while((_n = read4(_buf)) > 0){\n                //check the space of `buf` whether full or not\n                size = len + _n > n ? n-len : _n;\n                strncpy(buf+len, _buf, size);\n                len += size;\n                //buffer is full\n                if (len>=n){\n                    break;\n                }\n            }\n            return len;\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/reconstructItinerary/ReconstructItinerary.cpp",
    "content": "// Source : https://leetcode.com/problems/reconstruct-itinerary/\n// Author : Hao Chen\n// Date   : 2017-01-06\n\n/*************************************************************************************** \n *\n * Given a list of airline tickets represented by pairs of departure and arrival \n * airports [from, to], reconstruct the itinerary in order. All of the tickets belong \n * to a man who departs from JFK. Thus, the itinerary must begin with JFK.\n * \n * Note:\n * \n * If there are multiple valid itineraries, you should return the itinerary that has \n * the smallest lexical order when read as a single string. For example, the itinerary \n * [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"].\n * All airports are represented by three capital letters (IATA code).\n * You may assume all tickets form at least one valid itinerary.\n * \n *     Example 1:\n *     tickets = [[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]\n *     Return [\"JFK\", \"MUC\", \"LHR\", \"SFO\", \"SJC\"].\n * \n *     Example 2:\n *     tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\n *     Return [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"].\n *     Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"]. But it \n * is larger in lexical order.\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n/*\n This problem's description really confuse me.\n \n for examples:\n    1) [[\"JFK\", \"PEK\"], [\"JFK\", \"SHA\"], [\"SHA\", \"JFK\"]], which has two itineraries: \n       a) JFK -> PEK, \n       b) JFK -> SHA -> JFK -> PEK\n       The a) is smaller than b), because PEK < SHA, however the b) is correct answer.\n       So, it means we need use all of tickets.\n       \n    2) [[\"JFK\", \"PEK\"], [\"JFK\", \"SHA\"]], which also has two itineraries:\n       a) JFK -> PEK\n       b) JFK -> SHA\n       for my understanding, the JFK -> SHA is the correct one, \n       however, the correct answer is JFK -> SHA -> PEK.\n       I don't understand, why the correct answer is not JFK -> PEK -> SHA\n       That really does not make sense to me.\n       \n All right, we need assume all of the tickets can be connected in one itinerary.\n Then, it's easy to have a DFS algorithm.\n*/\n\n\nclass Solution {\npublic:\n    //DFS\n    void travel(string& start, unordered_map<string, multiset<string>>& map, vector<string>& result) {\n        while (map[start].size() > 0 ) {\n            string next = *(map[start].begin());\n            map[start].erase(map[start].begin());\n            travel(next, map, result);\n        }\n        result.insert(result.begin(), start);\n    }\n    \n    vector<string> findItinerary(vector<pair<string, string>> tickets) {\n        unordered_map<string, multiset<string>> map;\n        for(auto t : tickets) {\n            map[t.first].insert(t.second);\n        }\n        vector<string> result;\n        string start = \"JFK\";\n        travel(start, map, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/recoverATreeFromPreorderTraversal/recoverATreeFromPreorderTraversal.cpp",
    "content": "// Source : https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/\n// Author : Ahmed Morsy\n// Date   : 2019-05-29\n// source : https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/\n/***************************************************************************************************** \n *\n * We run a preorder depth first search on the root of a binary tree.\n * \n * At each node in this traversal, we output D dashes (where D is the depth of this node), then we \n * output the value of this node.  (If the depth of a node is D, the depth of its immediate child is \n * D+1.  The depth of the root node is 0.)\n * \n * If a node has only one child, that child is guaranteed to be the left child.\n * \n * Given the output S of this traversal, recover the tree and return its root.\n * \n * Example 1:\n * \n * Input: \"1-2--3--4-5--6--7\"\n * Output: [1,2,5,3,4,6,7]\n * \n * Example 2:\n * \n * Input: \"1-2--3---4-5--6---7\"\n * Output: [1,2,5,3,null,6,null,4,null,7]\n * \n * Example 3:\n * \n * Input: \"1-401--349---90--88\"\n * Output: [1,401,null,349,88,90]\n * \n * Note:\n * \n * \tThe number of nodes in the original tree is between 1 and 1000.\n * \tEach node will have a value between 1 and 10^9.\n * \n ******************************************************************************************************/\n\n/*  Definition for a binary tree node.\n  struct TreeNode {\n      int val;\n      TreeNode *left;\n      TreeNode *right;\n      TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n  };\n*/  \n\n\nclass Solution {\npublic:\n\n    TreeNode* recoverFromPreorder(string S) {\n        vector<int>values,depth;\n        int cur_val = 0 , cur_depth = 0;\n        bool dash = false;\n        for(char s : S){\n            if(s == '-'){\n                if(!dash){\n                    values.push_back(cur_val);\n                    depth.push_back(cur_depth);\n                    cur_depth = 0;\n                    cur_val = 0;\n                }\n                dash = true;\n                cur_depth++;\n            }\n            else{\n                dash = false;\n                cur_val *= 10;\n                cur_val += s-'0';\n            }\n        }\n        values.push_back(cur_val);\n        depth.push_back(cur_depth);\n\n        unordered_map<TreeNode*,int>depths;\n\n\n        int ptr = 1;\n        TreeNode *root = new TreeNode(values[0]);\n        depths[root] = 0;\n        stack<TreeNode*>st;\n        st.push(root);\n\n        while(ptr < (int)values.size()){\n            TreeNode *cur = st.top();\n            if(depth[ptr] == depths[cur]+1 && (cur->left == NULL || cur->right == NULL)){\n                TreeNode *t = new TreeNode(values[ptr++]);\n                depths[t] = depths[cur]+1;\n                if(cur->left == NULL){\n                    cur->left = t;\n                }\n                else{\n                    cur->right = t;\n                }\n                st.push(t);\n            }\n            else{\n                st.pop();\n            }\n        }\n        return root;\n\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/recover-binary-search-tree/\n// Author : Hao Chen\n// Date   : 2014-10-11\n\n/********************************************************************************** \n* \n* Two elements of a binary search tree (BST) are swapped by mistake.\n* \n* Recover the tree without changing its structure.\n* \n* Note:\n* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n\n//\n// We can convert the BST to a sorted array,  then we can find the two nodes which missed the order.\n//\n// To cover the BST to sorted array, we needn't use an extra array, we just traverse the tree in order.\n//  \n//                   8\n//           _______/ \\_______\n//          /                 \\\n//         4                  12\n//      __/ \\__             __/ \\__\n//     /       \\           /       \\\n//    2         6        10        14\n//   / \\       / \\       / \\       / \\\n//  1   3     5   7     9  11    13  15\n//  \n//  \nclass Solution {\npublic:\n    void recoverTreeHelper(TreeNode *root) {\n        \n        if (root == NULL) return;\n        \n        recoverTreeHelper(root->left);\n        if (prev) {\n            if (prev->val > root->val){\n                if (n1==NULL) {\n                    n1 = prev;\n                }\n                n2 = root;\n            }\n        }\n        prev = root;\n        recoverTreeHelper(root->right);\n    }\n    \n    void recoverTree(TreeNode *root) {\n        n1 = n2 = prev = NULL;\n        recoverTreeHelper(root);\n        if (n1 && n2) {\n            swap(n1->val, n2->val);\n        }\n    }\nprivate:\n    TreeNode *n1, *n2, *prev;\n};\n"
  },
  {
    "path": "algorithms/cpp/rectangleArea/RectangleArea.cpp",
    "content": "// Source : https://leetcode.com/problems/rectangle-area/\n// Author : Hao Chen\n// Date   : 2015-06-12\n\n/********************************************************************************** \n * \n * Find the total area covered by two rectilinear rectangles in a 2D plane.\n * Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.\n * \n *                      Y                                        \n *                      ^                                        \n *                      |                                        \n *                      |                                        \n *                      |                                        \n *                      |                                        \n *                      |     (C,D):(3,4)                        \n *            +------------------+                               \n *            |         |        |                               \n *            |         |        |                               \n *            |         |        |               (G,H):(9,2)     \n *            |         +----------------------------+           \n *            |         |        |                   |           \n *            |         |        |                   |           \n *            |         |        |                   |           \n *            +---------|--------+-------------------|---------> X\n *      (A,B):(-3,0)    |                            |           \n *                      +----------------------------+           \n *                  (E,F):(0,-1)                                 \n *      \n *      \n *      \n * Assume that the total area is never beyond the maximum possible value of int.\n * \n * Credits:Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.\n *               \n **********************************************************************************/\n#include <iostream>\nusing namespace std;\n\nnamespace leetcode \n{\n    class Point {\n        public:\n            Point(int _x, int _y):x(_x),y(_y) {}\n            int x, y;\n    };\n\n    class Rectangle {\n        public:\n            Rectangle(int a, int b, int c, int d):topLeft(a,d), bottomRight(c,b) { }\n            int Area(){\n                return (bottomRight.x - topLeft.x)*(topLeft.y - bottomRight.y); \n            }\n\n            int InclusiveArea (Rectangle &r){\n                // I include it\n                if (r.topLeft.x >= topLeft.x && r.bottomRight.x <= bottomRight.x &&\n                        r.topLeft.y <= topLeft.y && r.bottomRight.y >= bottomRight.y ) {\n                    return this->Area();\n                }\n                // it includes me\n                if (r.topLeft.x <= topLeft.x && r.bottomRight.x >= bottomRight.x &&\n                        r.topLeft.y >= topLeft.y && r.bottomRight.y <= bottomRight.y ) {\n                    return r.Area();\n                }\n                // 0 - no inclusive\n                return 0;\n            }\n\n            int OverlappedArea(Rectangle &r) {\n                int overlap_x = max(0, min(r.bottomRight.x, bottomRight.x) - max(r.topLeft.x, topLeft.x));\n                int overlap_y = max(0, min(r.topLeft.y, topLeft.y) - max(r.bottomRight.y, bottomRight.y));\n                return overlap_x * overlap_y;\n            }\n\n            Point topLeft;\n            Point bottomRight;\n    };\n};\n\n\nint computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {\n    using namespace leetcode;\n    Rectangle r1(A,B,C,D);\n    Rectangle r2(E,F,G,H);\n    int area = r1.InclusiveArea(r2);\n    if (area > 0) return area;\n    return r1.Area() + r2.Area() - r1.OverlappedArea(r2);\n}\n\n\n\nint main() \n{\n    //16\n    cout << \"16 : \" << computeArea(-1, -1, 1, 1, -2, -2, 2, 2) << endl;\n    //16\n    cout << \"16 : \" << computeArea(-2, -2, 2, 2, -1, -1, 1, 1) << endl;\n    //17\n    cout << \"17 : \" << computeArea(-2, -2, 2, 2, -4, 3, -3, 4) << endl;\n    //45\n    cout << \"45 : \" << computeArea(-3, -0, 3, 4, 0, -1, 9, 2) << endl;\n    //24\n    cout << \"24 : \" << computeArea(-2, -2, 2, 2, -3, -3, 3, -1) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/reformatPhoneNumber/ReformatPhoneNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/reformat-phone-number/\n// Author : Hao Chen\n// Date   : 2021-05-07\n\n/***************************************************************************************************** \n *\n * You are given a phone number as a string number. number consists of digits, spaces ' ', and/or \n * dashes '-'.\n * \n * You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and \n * dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or \n * fewer digits. The final digits are then grouped as follows:\n * \n * \t2 digits: A single block of length 2.\n * \t3 digits: A single block of length 3.\n * \t4 digits: Two blocks of length 2 each.\n * \n * The blocks are then joined by dashes. Notice that the reformatting process should never produce any \n * blocks of length 1 and produce at most two blocks of length 2.\n * \n * Return the phone number after formatting.\n * \n * Example 1:\n * \n * Input: number = \"1-23-45 6\"\n * Output: \"123-456\"\n * Explanation: The digits are \"123456\".\n * Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\n * Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \n * \"456\".\n * Joining the blocks gives \"123-456\".\n * \n * Example 2:\n * \n * Input: number = \"123 4-567\"\n * Output: \"123-45-67\"\n * Explanation: The digits are \"1234567\".\n * Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\n * Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \n * \"67\".\n * Joining the blocks gives \"123-45-67\".\n * \n * Example 3:\n * \n * Input: number = \"123 4-5678\"\n * Output: \"123-456-78\"\n * Explanation: The digits are \"12345678\".\n * Step 1: The 1st block is \"123\".\n * Step 2: The 2nd block is \"456\".\n * Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\n * Joining the blocks gives \"123-456-78\".\n * \n * Example 4:\n * \n * Input: number = \"12\"\n * Output: \"12\"\n * \n * Example 5:\n * \n * Input: number = \"--17-5 229 35-39475 \"\n * Output: \"175-229-353-94-75\"\n * \n * Constraints:\n * \n * \t2 <= number.length <= 100\n * \tnumber consists of digits and the characters '-' and ' '.\n * \tThere are at least two digits in number.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string reformatNumber(string number) {\n        string result;\n        for(int i=0, cnt=0; i<number.size(); i++){\n            if(number[i] == ' ' or number[i] == '-') continue;\n            result += number[i] ;\n            cnt++;\n            if (cnt % 3 == 0) result += '-';\n        }\n        \n        int end = result.size()-1;\n        if (result[end] == '-') result.erase(end, 1);\n        if (result[end-1] == '-') swap(result[end-2] , result[end-1]);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/regularExpressionMatching/regularExpressionMatching.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/regular-expression-matching/\n// Author : Hao Chen\n// Date   : 2014-08-24\n\n/********************************************************************************** \n* \n* Implement regular expression matching with support for '.' and '*'.\n* \n* '.' Matches any single character.\n* '*' Matches zero or more of the preceding element.\n* \n* The matching should cover the entire input string (not partial).\n* \n* The function prototype should be:\n* bool isMatch(const char *s, const char *p)\n* \n* Some examples:\n* isMatch(\"aa\",\"a\") → false\n* isMatch(\"aa\",\"aa\") → true\n* isMatch(\"aaa\",\"aa\") → false\n* isMatch(\"aa\", \"a*\") → true\n* isMatch(\"aa\", \".*\") → true\n* isMatch(\"ab\", \".*\") → true\n* isMatch(\"aab\", \"c*a*b\") → true\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <string.h>\n#include <iostream>\n\nusing namespace std;\n\n\nbool isMatch(const char *s, const char *p) {\n\n    if (*p=='\\0') {\n        return *s == '\\0';\n    }\n    //p's length 1 is special case \n    if (*(p+1) == '\\0' || *(p+1) !='*' ) {\n        if (*s=='\\0' || ( *p !='.' && *s != *p )) {\n            return false;\n        }\n        return isMatch(s+1, p+1);\n    }\n    int len = strlen(s);\n    int i = -1;\n    while (i < len && (i <0 || *p=='.' || *p==*(s+i)) ){\n        if (isMatch(s+i+1, p+2)) {\n            return true;\n        }\n        i++;\n    }\n    return false;\n}\n\n\nint main(int argc, char** argv)\n{\n    const char* s = \"aaa\";\n    const char* p = \"a.*\";\n\n    if (argc>2) {\n        s = argv[1];\n        p = argv[2];\n    }\n\n    cout << s << \", \" << p << \" : \" << isMatch(s,p) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/removeDuplicateLetters/RemoveDuplicateLetters.cpp",
    "content": "// Source : https://leetcode.com/problems/remove-duplicate-letters/\n// Author : Hao Chen\n// Date   : 2017-01-02\n\n/*************************************************************************************** \n *\n * Given a string which contains only lowercase letters, remove duplicate letters so \n * that every letter appear once and only once. You must make sure your result is the \n * smallest in lexicographical order among all possible results.\n * \n * Example:\n * \n * Given \"bcabc\"\n * Return \"abc\"\n * \n * Given \"cbacdcbc\"\n * Return \"acdb\"\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n\nclass Solution {\npublic:\n    string removeDuplicateLetters(string s) {\n        const int ASCII_LEN = 256;\n        int counter[ASCII_LEN] = {0};\n        bool visited[ASCII_LEN] = {false};\n        \n        for (char ch : s) {\n            counter[ch]++;\n        }\n        \n        string result;\n        for (char ch : s) {\n            counter[ch]--;\n            // if the current `ch` has already put into the result.\n            if (visited[ch]) continue;\n            \n            // if the current `ch` is smaller than the last one char in result.\n            // and we still have duplicated last-one char behind, so we can remove the current one.\n            while ( !result.empty() && ch < result.back() && counter[result.back()] ) {\n                visited[result.back()] = false;\n                result.pop_back();\n            }\n            result.push_back(ch);\n            visited[ch] = true;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/\n// Author : Hao Chen\n// Date   : 2014-06-29\n\n/********************************************************************************** \n* \n* Follow up for \"Remove Duplicates\":\n* What if duplicates are allowed at most twice?\n* \n* For example,\n* Given sorted array A = [1,1,1,2,2,3],\n* \n* Your function should return length = 5, and A is now [1,1,2,2,3].\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\n\nint removeDuplicates(int A[], int n) {\n    if (n<=2) return n;\n    int pos=0;\n    int cnt=1;\n    for (int i=1; i<n; i++){\n        if (A[i] == A[pos]){\n            cnt++;\n            if (cnt==2){\n                A[++pos] = A[i];\n            }\n        }else{\n            cnt=1;\n            A[++pos] = A[i];\n            \n        }\n    } \n    return pos+1;\n}\n\nvoid printfArray(int A[], int n) {\n    printf(\"{ \");\n    for (int i=0; i<n; i++){\n        printf(\"%d \", A[i]);\n    }\n    printf(\"}\\n\");\n}\n\n\nvoid testSuite(int a[], int n){\n    printfArray(a, n);\n    n = removeDuplicates(a, n);\n    printfArray(a, n);\n    printf(\"------------------\\n\");\n}\n\n#define TEST(a) testSuite(a, sizeof(a)/sizeof(int))\nint main()\n{\n    int a0[] = {1, 2, 3, 4, 5};\n    TEST(a0);\n    int a1[] = {1, 1, 1};\n    TEST(a1);\n    int a2[] = {1, 2, 2};\n    TEST(a2);\n    int a3[] = {1, 1, 2};\n    TEST(a3);\n    int a4[] = {1, 1, 1, 1};\n    TEST(a4);\n    int a5[] = {1, 1, 1, 2};\n    TEST(a5);\n    int a6[] = {1, 2, 2, 2};\n    TEST(a6);\n    int a7[] = {1, 2, 2, 2, 3 };\n    TEST(a7);\n    int a8[] = {1, 2, 2, 2, 3, 3};\n    TEST(a8);\n    int a9[] = {1,1,1,2,2,3};\n    TEST(a9);\n    int a10[] = {1,1,1,2,2,2};\n    TEST(a10);\n    int a11[] = {1,1,1,1,3,3};\n    TEST(a11);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given a sorted array, remove the duplicates in place such that each element appear \n* only once and return the new length.\n* \n* Do not allocate extra space for another array, you must do this in place with constant memory.\n* \n* For example,\n* Given input array A = [1,1,2],\n* \n* Your function should return length = 2, and A is now [1,2].\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    int removeDuplicates(int A[], int n) {\n        \n        if (n<=1) return n;\n        \n        int pos=0;\n        for(int i=0; i<n-1; i++){\n            if (A[i]!=A[i+1]){\n                A[++pos] = A[i+1];\n            }\n        }\n        return pos+1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Given a sorted linked list, delete all nodes that have duplicate numbers, \n* leaving only distinct numbers from the original list.\n* \n* For example,\n* Given 1->2->3->3->4->4->5, return 1->2->5.\n* Given 1->1->1->2->3, return 2->3.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *deleteDuplicates(ListNode *head) {\n    ListNode fake(-1);\n    fake.next = head;\n    head = &fake;\n\n    ListNode *tail=head;\n\n    bool dup = false;\n    for(ListNode *p=head->next;  p && p->next; p=p->next){\n        if (dup==false && p->val == p->next->val){\n            dup = true;            \n            continue;\n        }\n        if (dup==true && p->val != p->next->val){\n            dup = false;\n            tail->next = p->next;\n            continue;\n        }\n        if (dup==false){\n            tail = p;\n        }\n    }\n    if (dup==true){\n        tail->next = NULL;\n    }\n    return head->next;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main()\n{\n    int a[]={1,1,2,3,3};\n    int b[]={1,1,1};\n    int c[]={1,2,3};\n    int d[]={3};\n\n    printList(deleteDuplicates(createList(a, sizeof(a)/sizeof(int))));\n    printList(deleteDuplicates(createList(b, sizeof(b)/sizeof(int))));\n    printList(deleteDuplicates(createList(c, sizeof(c)/sizeof(int))));\n    printList(deleteDuplicates(createList(d, sizeof(d)/sizeof(int))));\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a sorted linked list, delete all duplicates such that each element appear only once.\n* \n* For example,\n* Given 1->1->2, return 1->2.\n* Given 1->1->2->3->3, return 1->2->3.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *deleteDuplicates(ListNode *head) {\n\n    for(ListNode *p=head; p && p->next; ){\n        if (p->val == p->next->val){\n            p->next = p->next->next;\n            continue;\n        }\n        p=p->next;\n    }\n    return head;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main()\n{\n    int a[]={1,1,2,3,3};\n    int b[]={1,1,1};\n\n    printList(deleteDuplicates(createList(a, sizeof(a)/sizeof(int))));\n    printList(deleteDuplicates(createList(b, sizeof(b)/sizeof(int))));\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/removeElement/removeElement.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-element/\n// Author : Hao Chen\n// Date   : 2014-06-19\n\n/********************************************************************************** \n* \n* Given an array and a value, remove all instances of that value in place and return the new length.\n* \n* The order of elements can be changed. It doesn't matter what you leave beyond the new length.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    int removeElement(vector<int>& nums, int val) {\n        int pos = 0;\n        for (int i=0; i<nums.size(); i++){\n            if (nums[i] != val){\n                nums[pos++] = nums[i]; \n            }\n        }\n        return pos;\n    }\n\n    int removeElement(int A[], int n, int elem) {\n        int tail = n-1;\n        int i = 0;\n        while ( i<=tail ){\n            if (A[i]==elem){\n                A[i] = A[tail--];\n                continue;\n            }\n            i++;\n        }\n        \n        return tail+1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/removeInvalidParentheses/RemoveInvalidParentheses.cpp",
    "content": "// Source : https://leetcode.com/problems/remove-invalid-parentheses/\n// Author : Hao Chen\n// Date   : 2015-11-11\n\n/*************************************************************************************** \n *\n * Remove the minimum number of invalid parentheses in order to make the input string \n * valid. Return all possible results.\n * \n * Note: The input string may contain letters other than the parentheses ( and ). \n * \n * Examples:\n * \n * \"()())()\" -> [\"()()()\", \"(())()\"]\n * \"(a)())()\" -> [\"(a)()()\", \"(a())()\"]\n * \")(\" -> [\"\"]\n * \n * Credits:Special thanks to @hpplayer for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_set>\nusing namespace std;\n\n//DFS \nvoid removeInvalidParenthesesHelper(string& s, int index, int pair,\n                                    int remove_left, int remove_right, \n                                    string solution, unordered_set<string>& result) {\n\n    char ch = s[index];\n\n    //recusive ending \n    if ( ch == '\\0' ) {\n        if (pair==0 && remove_left==0 && remove_right==0 ) {\n            result.insert(solution);\n        }\n        return;\n    }\n    //other char, move to next one\n    if ( ch != '(' && ch != ')' ) {\n        removeInvalidParenthesesHelper(s, index+1, pair, remove_left, remove_right, solution+ch, result);\n        return;\n    }\n    \n    //if we meet left one, and we need remove left one, \n    //then we have two choices : remove it, OR keep it.\n    if ( ch == '(' ) {\n        //revmoe it\n        if (remove_left > 0 ) { \n            removeInvalidParenthesesHelper(s, index+1, pair, remove_left-1, remove_right, solution, result);\n        }\n        //keep it\n        removeInvalidParenthesesHelper(s, index+1, pair+1, remove_left, remove_right, solution+ch, result);\n    }\n    \n    //if we meet right one, and we need to remove right one,\n    //then we have two choices as well: remove it, or keep it if there are some left already.\n    if ( ch == ')' ) {\n        if (remove_right > 0 ) {\n            removeInvalidParenthesesHelper(s, index+1, pair, remove_left, remove_right-1, solution, result);\n        }\n        if (pair > 0){\n            removeInvalidParenthesesHelper(s, index+1, pair-1, remove_left, remove_right, solution+ch, result);\n        }\n    }\n\n\n}\n\nvector<string> removeInvalidParentheses(string s) {\n\n    //Calculating how many left/right parentheses need be removed!\n    int remove_left = 0, remove_right = 0;\n    for(auto c : s) {\n        if ( c == '(' ) {\n            remove_left++;\n        }else if ( c == ')' ){\n            if (remove_left > 0) {\n                remove_left--; // if we matched\n            }else{\n                remove_right++;\n            }\n        }\n    }\n\n    unordered_set<string> result;\n    removeInvalidParenthesesHelper(s, 0, 0, remove_left, remove_right, \"\", result);\n    return vector<string>( result.begin(), result.end() );\n}\n\n\nvoid printVector(vector<string> result) {\n    for( int i=0; i<result.size(); i++) {\n        cout << i << \") \" << result[i] << endl;\n    }\n}\n\n\nint main(int argc, char** argv) {\n    string s = \"()())()\";\n    if (argc>1) {\n        s = argv[1];\n    }\n    cout << s << endl;\n    printVector( removeInvalidParentheses(s) );\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/removeKDigits/RemoveKDigits.cpp",
    "content": "// Source : https://leetcode.com/problems/remove-k-digits/\n// Author : Hao Chen\n// Date   : 2016-11-11\n\n/*************************************************************************************** \n *\n * Given a non-negative integer num represented as a string, remove k digits from the \n * number so that the new number is the smallest possible.\n * \n * Note:\n * \n * The length of num is less than 10002 and will be ≥ k.\n * The given num does not contain any leading zero.\n * \n * Example 1:\n * \n * Input: num = \"1432219\", k = 3\n * Output: \"1219\"\n * Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which \n * is the smallest.\n * \n * Example 2:\n * \n * Input: num = \"10200\", k = 1\n * Output: \"200\"\n * Explanation: Remove the leading 1 and the number is 200. Note that the output must \n * not contain leading zeroes.\n * \n * Example 3:\n * \n * Input: num = \"10\", k = 2\n * Output: \"0\"\n * Explanation: Remove all the digits from the number and it is left with nothing which \n * is 0.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    string removeKdigits_pick(string& num, int k) {\n        \n        int len = num.size();\n        string result;\n        \n        int idx = 0;\n        for (int i=0; i < len - k; i++) {\n            int min_idx = idx;\n            for (int j=min_idx; j<=i+k; j++) {\n                if (num[min_idx] > num[j])  min_idx = j;\n            }\n            \n            //don't put zero at the beginning\n            if ( !(result.empty() && num[min_idx]=='0') ){\n                result.push_back(num[min_idx]);\n            }\n            \n            //select the number started from next one, to make the order correctness.\n            idx = min_idx + 1;\n        }\n        \n        if (result.empty()) result = \"0\";\n        return result;\n    }\n    \n    string removeKdigits_remove(string& num, int k) {\n        if ( num.size() <= k ) return \"0\";\n        int left_len = num.size() - k;\n        int idx = 0;\n        for (int i=0; i<k ;i++){\n            int len = num.size();\n            for (int j=0; j<num.size()-1; j++) {\n                //if the current is bigger than next one, then revmoe the current one.\n                //In other word, we always pick the smaller one number.\n                if ( num[j] > num[j+1] ) {\n                    num.erase(j, 1);\n                    idx = j;\n                    break;\n                }\n            }\n        }\n        \n        //remove all of ZEROs at the beginning.\n        for (int i=0; i<= num.size(); i++) {\n            if (num[i] != '0' || i == num.size()) {\n                num.erase(0, i);\n                break;\n            }\n        }\n        \n        // if the digits in the array are sorted, \n        // then, we need remove the digits at the ends.\n        if (num.size() > left_len ) {\n            num.erase(num.begin() + left_len, num.end());\n        }\n        \n        if (num.empty()) num = \"0\";\n        return num;\n    }\n    \n    string removeKdigits(string num, int k) {\n        srand(time(0));\n        if (rand() % 2 ) {\n            return removeKdigits_pick(num, k);\n        } else {\n            return removeKdigits_remove(num, k);\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/removeLinkedListElements/RemoveLinkedListElements.cpp",
    "content": "// Source : https://leetcode.com/problems/remove-linked-list-elements/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Remove all elements from a linked list of integers that have value val.\n * \n * Example\n * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,  val = 6\n * Return: 1 --> 2 --> 3 --> 4 --> 5\n * \n * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* removeElements(ListNode* head, int val) {\n        static ListNode dummy(-1);\n        dummy.next = head;\n        ListNode *p = &dummy;\n        \n        while( p->next) {\n            if (p->next->val == val) {\n                p->next = p->next->next;\n            }else{\n                p = p->next;\n            }\n        }\n        \n        return dummy.next;\n    }\n};\n\n\n"
  },
  {
    "path": "algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a linked list, remove the nth node from the end of list and return its head.\n* \n* For example,\n* \n*    Given linked list: 1->2->3->4->5, and n = 2.\n* \n*    After removing the second node from the end, the linked list becomes 1->2->3->5.\n* \n* Note:\n* Given n will always be valid.\n* Try to do this in one pass.\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *removeNthFromEnd(ListNode *head, int n) {\n        if (head==NULL || n<=0){\n            return NULL;\n        }\n        ListNode fakeHead(0);\n        fakeHead.next=head;\n        head=&fakeHead;\n        \n        ListNode *p1, *p2;\n        p1=p2=head;\n        for(int i=0; i<n; i++){\n            if (p2==NULL) return NULL;\n            p2=p2->next;\n        }\n        while (p2->next!=NULL){\n            p2=p2->next;\n            p1=p1->next;\n        }\n        \n        p1->next = p1->next->next;\n        return head->next;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reorderList/reorderList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reorder-list/\n// Author : Hao Chen\n// Date   : 2014-06-17\n\n/********************************************************************************** \n* \n* Given a singly linked list L: L0→L1→…→Ln-1→Ln,\n* reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…\n* \n* You must do this in-place without altering the nodes' values.\n* \n* For example,\n* Given {1,2,3,4}, reorder it to {1,4,2,3}.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n/**\n * Definition for singly-linked list.\n */\nclass ListNode {\npublic:\n    int val;\n    ListNode *next;\n    ListNode():val(0), next(NULL) {}\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nclass Solution {\npublic:\n    void reorderList(ListNode *head) {\n        ListNode *pMid = findMidPos(head);\n        pMid = reverseList(pMid);\n        head = Merge(head, pMid);\n    }\n    \nprivate:\n    ListNode* findMidPos(ListNode *head){\n\n        ListNode *p1, *p2, *p=NULL;\n        p1 = p2 = head;\n        \n        while(p1!=NULL && p2!=NULL && p2->next!=NULL){\n            p = p1;\n            p1 = p1->next;\n            p2 = p2->next->next;\n        }\n\n        if(p!=NULL){\n            p->next = NULL;\n        }\n        \n        return p1;\n    }\n    \n    ListNode* reverseList(ListNode *head){\n        ListNode* h = NULL;\n        ListNode *p;\n        while (head!=NULL){\n            p = head;\n            head = head->next;\n            p->next = h;\n            h = p;\n        }\n        return h;\n    }\n    \n    ListNode* Merge(ListNode *h1, ListNode* h2) {\n        ListNode *p1=h1, *p2=h2, *p1nxt, *p2nxt;\n        while(p1!=NULL && p2!=NULL){\n            p1nxt = p1->next;\n            p2nxt = p2->next;\n            \n            p1->next = p2;\n            p2->next = p1nxt;\n            \n            if (p1nxt==NULL){\n                p2->next = p2nxt;\n                break;\n            }\n            p1=p1nxt;\n            p2=p2nxt;\n        }\n    }\n};\n\nvoid printList(ListNode *h){\n    while(h!=NULL){\n        printf(\"%d->\", h->val);\n        h = h->next;\n    }\n    printf(\"nil\\n\");\n}\n\nint main(int argc, char** argv)\n{\n    int size = atoi(argv[1]);\n    ListNode* n = new ListNode[size] ;\n\n    for(int i=0; i<size; i++){\n        n[i].val = i;\n        if( i+1 < size) {\n            n[i].next = &n[i+1];\n        }\n    }\n\n\n    Solution s;\n    s.reorderList(&n[0]);\n    printList(&n[0]);\n    \n    \n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/repeatedDNASequences/repeatedDNASequences.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/repeated-dna-sequences/\n// Author : Hao Chen\n// Date   : 2015-02-09\n\n/********************************************************************************** \n * \n * All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, \n *\n * For example: \"ACGAATTCCG\". \n * When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.\n * \n * Write a function to find all the 10-letter-long sequences (substrings) that \n * occur more than once in a DNA molecule.\n * \n * For example,\n * \n * Given s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\",\n * \n * Return:\n * [\"AAAAACCCCC\", \"CCCCCAAAAA\"].\n * \n *               \n **********************************************************************************/\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <functional>\n#include <unordered_map>\nusing namespace std;\n\nconst int MAX_LEN = 10;\n\nint ACGT2Int(char ch){\n    switch(ch){\n        case 'A': return 0;\n        case 'C': return 1;\n        case 'G': return 2;\n        case 'T': return 3;\n    }\n    return -1;\n}\nint DNASeqs2Int(string &s, int begin){\n    int result=0;\n    for(int i=0; i<MAX_LEN; i++){\n        result = result*4 + ACGT2Int(s[i+begin]);\n    }\n    return result;\n}\n\nvector<string> findRepeatedDnaSequences_01(string s) {\n    unordered_map<int, int> stat;\n\n    vector<string> result;\n\n    for( int i=0; i+MAX_LEN<=s.size(); i++ ){\n\n        int hash_code = DNASeqs2Int(s, i);\n        stat[hash_code]++;\n        if (stat[hash_code]==2){\n            result.push_back(s.substr(i, MAX_LEN));\n        }\n    }\n\n    return result;        \n}\n\nvector<string> findRepeatedDnaSequences_02(string s) {\n    unordered_map<size_t, int> stat;\n    hash<string> hash_func;\n\n    vector<string> result;\n\n    for( int i=0; i+MAX_LEN<=s.size(); i++ ){\n        string word = s.substr(i, MAX_LEN);\n        size_t hash_code = hash_func(word);\n        stat[hash_code]++;\n        if (stat[hash_code]==2){\n            result.push_back(word);\n        }\n    }\n\n    return result;\n}\n\nvector<string> findRepeatedDnaSequences(string s) {\n    srand(time(0));\n    if (random()%2){\n        return findRepeatedDnaSequences_01(s);\n    }\n    return findRepeatedDnaSequences_02(s);\n}\n\nvoid printVector( vector<string> v ) {\n    cout << \"[ \" ;\n    for(int i=0; i<v.size(); i++ ){\n        cout << v[i] << (i<v.size()-1 ? \", \" : \"\");\n    }\n    cout << \" ]\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    string s =  \"GAGAGAGAGAGAG\" ;\n    if (argc > 1){\n        s = argv[1];\n    }\n    printVector(findRepeatedDnaSequences(s));\n}\n"
  },
  {
    "path": "algorithms/cpp/replaceAllDigitsWithCharacters/ReplaceAllDigitsWithCharacters.cpp",
    "content": "// Source : https://leetcode.com/problems/replace-all-digits-with-characters/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * You are given a 0-indexed string s that has lowercase English letters in its even indices and \n * digits in its odd indices.\n * \n * There is a function shift(c, x), where c is a character and x is a digit, that returns the x^th \n * character after c.\n * \n * \tFor example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.\n * \n * For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).\n * \n * Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed \n * 'z'.\n * \n * Example 1:\n * \n * Input: s = \"a1c1e1\"\n * Output: \"abcdef\"\n * Explanation: The digits are replaced as follows:\n * - s[1] -> shift('a',1) = 'b'\n * - s[3] -> shift('c',1) = 'd'\n * - s[5] -> shift('e',1) = 'f'\n * \n * Example 2:\n * \n * Input: s = \"a1b2c3d4e\"\n * Output: \"abbdcfdhe\"\n * Explanation: The digits are replaced as follows:\n * - s[1] -> shift('a',1) = 'b'\n * - s[3] -> shift('b',2) = 'd'\n * - s[5] -> shift('c',3) = 'f'\n * - s[7] -> shift('d',4) = 'h'\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \ts consists only of lowercase English letters and digits.\n * \tshift(s[i-1], s[i]) <= 'z' for all odd indices i.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string replaceDigits(string s) {\n        for(int i=0; i<s.size(); i+=2) {\n            s[i+1] = s[i] + s[i+1] - '0';\n        }\n        return  s;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/restoreIPAddresses/restoreIPAddresses.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/restore-ip-addresses/\n// Author : Hao Chen\n// Date   : 2014-08-26\n\n/********************************************************************************** \n* \n* Given a string containing only digits, restore it by returning all possible valid IP address combinations.\n* \n* For example:\n* Given \"25525511135\",\n* \n* return [\"255.255.11.135\", \"255.255.111.35\"]. (Order does not matter)\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\nvoid restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result);\n\nvector<string> restoreIpAddresses(string s) {\n    vector<string> result;\n    string ip;\n    restoreIpAddressesHelper(s, 0, 0, ip, result);\n    return result;\n}\n\nvoid restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result) {\n\n    int len = s.size();\n    if ( len - start < 4-partNum  || len - start > (4-partNum)*3 ) {\n        return;\n    }\n\n    if (partNum == 4 && start == len){\n        ip.erase(ip.end()-1, ip.end());\n        result.push_back(ip);\n        return;\n    }\n\n    int num = 0;\n    for (int i=start; i<start+3; i++){\n        num = num*10 + s[i]-'0';\n        if (num<256){\n            ip+=s[i];\n            restoreIpAddressesHelper(s, i+1, partNum+1, ip+'.', result);\n        }         \n        //0.0.0.0 valid, but 0.1.010.01 is not\n        if (num == 0) {\n            break;\n        }\n    }\n       \n}\n\n\nint main(int argc, char**argv)\n{\n    string s = \"25525511135\";\n    if (argc>1){\n        s = argv[1];\n    }\n\n    vector<string> result = restoreIpAddresses(s);\n\n    cout << s << endl;\n    for(int i=0; i<result.size(); i++){\n        cout << '\\t' << result[i] << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/restoreTheArrayFromAdjacentPairs/RestoreTheArrayFromAdjacentPairs.cpp",
    "content": "// Source : https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/\n// Author : Hao Chen\n// Date   : 2021-03-28\n\n/***************************************************************************************************** \n *\n * There is an integer array nums that consists of n unique elements, but you have forgotten it. \n * However, you do remember every pair of adjacent elements in nums.\n * \n * You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] \n * indicates that the elements ui and vi are adjacent in nums.\n * \n * It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in \n * adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any \n * order.\n * \n * Return the original array nums. If there are multiple solutions, return any of them.\n * \n * Example 1:\n * \n * Input: adjacentPairs = [[2,1],[3,4],[3,2]]\n * Output: [1,2,3,4]\n * Explanation: This array has all its adjacent pairs in adjacentPairs.\n * Notice that adjacentPairs[i] may not be in left-to-right order.\n * \n * Example 2:\n * \n * Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]\n * Output: [-2,4,1,-3]\n * Explanation: There can be negative numbers.\n * Another solution is [-3,1,4,-2], which would also be accepted.\n * \n * Example 3:\n * \n * Input: adjacentPairs = [[100000,-100000]]\n * Output: [100000,-100000]\n * \n * Constraints:\n * \n * \tnums.length == n\n * \tadjacentPairs.length == n - 1\n * \tadjacentPairs[i].length == 2\n * \t2 <= n <= 10^5\n * \t-10^5 <= nums[i], ui, vi <= 10^5\n * \tThere exists some nums that has adjacentPairs as its pairs.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n        // only two numbers have one neighbour\n        // start from one of them to travel all number.\n        \n        unordered_map<int, vector<int>> dict;\n        for(auto& pair : adjacentPairs) {\n            dict[pair[0]].push_back(pair[1]);\n            dict[pair[1]].push_back(pair[0]);\n        }\n        \n        int end[2]; int i=0;\n        for (auto& [key, pair] : dict) {\n            if(pair.size()==1) end[i++] = key;\n            if (i>1) break;\n        }\n        //cout << \"start=\" << end[0] <<\", end=\" << end[1] << endl;\n        vector<int> result(1, end[0]);\n        int start = end[0];\n        int prev = -1;\n        while ( start != end[1] ) {\n            auto& v = dict[start];\n            for(int i= 0; i< v.size(); i++) {\n                if (v[i] == prev) continue;\n                result.push_back(v[i]);\n                prev = start;\n                start = v[i];\n                break;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reverseBits/reverseBits.cpp",
    "content": "// Source : https://leetcode.com/problems/reverse-bits/\n// Author : Hao Chen\n// Date   : 2015-03-30\n\n/********************************************************************************** \n* \n* Reverse bits of a given 32 bits unsigned integer.\n* \n* For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), \n* return 964176192 (represented in binary as 00111001011110000010100101000000).\n* \n* Follow up:\n* If this function is called many times, how would you optimize it?\n* \n* Related problem: Reverse Integer\n* \n* Credits:Special thanks to @ts for adding this problem and creating all test cases.\n*               \n**********************************************************************************/\n\n\n\nclass Solution {\npublic:\n    uint32_t reverseBits(uint32_t n) {\n        uint32_t ret=0;\n        for(int i=0; i<32; i++) {\n            ret = (ret*2) + (n & 0x1);\n            n /=2 ;\n        }\n        return ret;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reverseInteger/reverseInteger.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reverse-integer/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Reverse digits of an integer.\n* \n* Example1: x =  123, return  321\n* Example2: x = -123, return -321\n* \n* \n* Have you thought about this?\n* \n* Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!\n* \n* > If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.\n* \n* > Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, \n*   then the reverse of 1000000003 overflows. How should you handle such cases?\n* \n* > Throw an exception? Good, but what if throwing an exception is not an option? \n*   You would then have to re-design the function (ie, add an extra parameter).\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n\n//Why need the INT_MIN be defined like that?\n//Please take a look: \n//  http://stackoverflow.com/questions/14695118/2147483648-0-returns-true-in-c\n#define INT_MAX     2147483647\n#define INT_MIN     (-INT_MAX - 1)\nint reverse(int x) {\n    int y=0;\n    int n;\n    while( x != 0){\n        n = x%10;\n        //Checking the over/underflow.\n        //Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it.\n        if (y > INT_MAX/10 || y < INT_MIN/10){\n             return 0;\n        }\n        y = y*10 + n;\n        x /= 10;\n    }\n    return y;\n}\n\n#define TEST(n, e)  printf(\"%12d  =>  %-12d    %s!\\n\",  n, reverse(n),  e == reverse(n)?\"passed\":\"failed\")\n\nint main(int argc, char**argv)\n{\n    //basic cases\n    TEST(  123,  321);\n    TEST( -123, -321);\n    TEST( -100,   -1);\n    TEST( 1002, 2001);\n    //big integer\n    TEST( 1463847412,  2147483641);\n    TEST(-2147447412, -2147447412);\n    TEST( 2147447412,  2147447412);\n    //overflow\n    TEST( 1000000003, 0);\n    TEST( 2147483647, 0);\n    TEST(-2147483648, 0);\n    //customized cases\n    if (argc<2){\n        return 0;\n    }\n    printf(\"\\n\");\n    for (int i=1; i<argc; i++) {\n        int n = atoi(argv[i]); \n        printf(\"%12d  =>  %-12d    %s!\\n\",  n, reverse(n), reverse(reverse(n))==n ? \"passed\":\"failed\");\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/reverseLinkedList/reverseLinkedList.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reverse-linked-list-ii/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Reverse a linked list from position m to n. Do it in-place and in one-pass.\n* \n* For example:\n* Given 1->2->3->4->5->NULL, m = 2 and n = 4,\n* \n* return 1->4->3->2->5->NULL.\n* \n* Note:\n* Given m, n satisfy the following condition:\n* 1 ≤ m ≤ n ≤ length of list.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\n\nListNode *reverseBetween(ListNode *head, int m, int n) {\n\n    if (head==NULL || m>=n) return head;\n\n    ListNode fake(0);\n    fake.next = head;\n    ListNode *pBegin=&fake, *pEnd=&fake;\n\n    int distance = n - m ;\n    while(pEnd && distance>0){\n        pEnd = pEnd->next;\n        distance--;\n    } \n    while(pBegin && pEnd && m-1>0) {\n        pBegin = pBegin->next;\n        pEnd = pEnd->next;\n        m--;\n    }\n    if (pBegin==NULL || pEnd==NULL || pEnd->next == NULL){\n        return head;\n    }\n    \n    ListNode *p = pBegin->next;\n    ListNode *q = pEnd->next->next;\n    \n    ListNode *pHead = q;\n    while(p != q){\n        ListNode* node = p->next;\n        p->next = pHead;\n        pHead = p;\n        p = node;\n    }\n    pBegin->next = pHead;\n\n    return fake.next;\n    \n}\n\n\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int *a, int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\nListNode* createList(int len) {\n    int *a = new int[len];\n    for(int i=0; i<len; i++){\n        a[i] = i+1;\n    }\n    ListNode* h =  createList(a, len);\n    delete[] a;\n    return h;\n}\n\nint main(int argc, char** argv)\n{\n    int l=5;\n    int  m=2, n=4;\n    \n    if (argc>1){\n        l = atoi(argv[1]);\n    }\n    if (argc>2) {\n        m = atoi(argv[2]);\n    }\n    if (argc>3) {\n        n = atoi(argv[3]);\n    }\n    \n    ListNode* h = createList(l);\n    printList( h );\n    printList( reverseBetween(h , m, n) );\n\n    \n}\n"
  },
  {
    "path": "algorithms/cpp/reverseLinkedList/reverseLinkedList.cpp",
    "content": "// Source : https://leetcode.com/problems/reverse-linked-list/\n// Author : Hao Chen\n// Date   : 2015-06-09\n\n/********************************************************************************** \n * \n * Reverse a singly linked list.\n * \n * click to show more hints.\n * \n * Hint:\n * A linked list can be reversed either iteratively or recursively. Could you implement both?\n * \n *               \n **********************************************************************************/\n\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* reverseList_iteratively(ListNode* head) {\n        ListNode *h=NULL, *p=NULL;\n        while (head){\n            p = head->next;\n            head->next = h;\n            h = head;\n            head = p;\n        }\n        return h;\n    }\n    ListNode* reverseList_recursively(ListNode* head) {\n        if (head==NULL || head->next==NULL) return head;\n        ListNode *h = reverseList_recursively(head->next);\n        head->next->next = head;\n        head->next = NULL;\n        return h;\n        \n    }\n    ListNode* reverseList(ListNode* head) {\n        return reverseList_iteratively(head);\n        return reverseList_recursively(head);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reverseNodesInKGroup/reverseNodesInKGroup.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reverse-nodes-in-k-group/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n* \n* If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.\n* \n* You may not alter the values in the nodes, only nodes itself may be changed.\n* \n* Only constant memory is allowed.\n* \n* For example,\n* Given this linked list: 1->2->3->4->5\n* \n* For k = 2, you should return: 2->1->4->3->5\n* \n* For k = 3, you should return: 3->2->1->4->5\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *reverseList(ListNode *&head, int k);\n\nListNode *reverseKGroup(ListNode *head, int k) {\n\n    if (k<=0) return head;\n    ListNode fake(0);\n    fake.next = head;\n    ListNode* p = &fake;\n\n    while(p){\n        p->next = reverseList(p->next, k);\n        for(int i=0; p && i<k; i++){\n            p = p->next;\n        }\n    }\n\n    return fake.next;\n}\n\nListNode *reverseList(ListNode *&head, int k){\n    ListNode* pEnd=head;\n    while (pEnd && k>0){\n        pEnd = pEnd->next;\n        k--;\n    }\n    if (k>0) return head;\n\n    ListNode *pHead=pEnd, *p=head;\n    while(p != pEnd){\n        ListNode *q = p->next;\n        p->next = pHead;\n        pHead = p;\n        p = q;\n    }\n    return pHead;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main(int argc, char** argv)\n{\n    int a[] = {1,2,3,4,5,6,7,8,9,10};\n    ListNode* pList = createList(a, sizeof(a)/sizeof(int));\n\n    int k =2;\n    if (argc>1){\n        k = atoi(argv[1]);\n    }\n\n    pList = reverseKGroup(pList, k);\n    printList(pList);\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/reverseString/ReverseString.cpp",
    "content": "// Source : https://leetcode.com/problems/reverse-string/\n// Author : Hao Chen\n// Date   : 2016-05-29\n\n/*************************************************************************************** \n *\n * Write a function that takes a string as input and returns the string reversed.\n * \n * Example:\n * Given s = \"hello\", return \"olleh\".\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    string reverseString(string s) {\n        int len = s.size();\n        for (int i=0; i<len/2; i++) {\n           char ch = s[i];\n           s[i] = s[len-i-1];\n           s[len-i-1] = ch;\n        } \n        return s;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp",
    "content": "// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/\n// Author : Calinescu Valentin, Hao Chen\n// Date   : 2016-04-30\n\n/*************************************************************************************** \n *\n * Write a function that takes a string as input and reverse only the vowels of a \n * string.\n * \n * Example 1:\n * Given s = \"hello\", return \"holle\".\n * \n * Example 2:\n * Given s = \"leetcode\", return \"leotcede\".\n * \n ***************************************************************************************/\n\n//Author: Calinescu Valentin\nclass Solution {\npublic:\n    string reverseVowels(string s) {\n        list <char> vowels;\n        set <char> vows;\n        vows.insert('a');\n        vows.insert('A');\n        vows.insert('e');\n        vows.insert('E');\n        vows.insert('i');\n        vows.insert('I');\n        vows.insert('o');\n        vows.insert('O');\n        vows.insert('u');\n        vows.insert('U');\n        string result;\n        for(int i = 0; i < s.size(); i++)\n        {\n            if(vows.find(s[i]) != vows.end())\n                vowels.push_back(s[i]);\n        }\n        for(int i = 0; i < s.size(); i++)\n        {\n            if(vows.find(s[i]) != vows.end())\n            {\n                result.push_back(vowels.back());\n                vowels.pop_back();\n            }\n            else\n                result.push_back(s[i]);\n        }\n        return result;\n    }\n};\n\n\n// Author: Hao Chen\n// 1) preset a dictionary table to look up vowels\n// 2) we have two pointer, the `left` one search vowels from the beginning to then end, the `right` one search from the end to the beginning.\n// 3) swap the left one and the right one until left >= right.\nclass Solution {\nprivate:\n   bool vowelsTable[256];\npublic:\n    Solution(){\n        memset(vowelsTable, 0, sizeof(vowelsTable));\n        vowelsTable['a']=true;\n        vowelsTable['e']=true;\n        vowelsTable['i']=true;\n        vowelsTable['o']=true;\n        vowelsTable['u']=true;\n        \n        vowelsTable['A']=true;\n        vowelsTable['E']=true;\n        vowelsTable['I']=true;\n        vowelsTable['O']=true;\n        vowelsTable['U']=true;\n    }\n    bool isVowels(char ch) {\n        return vowelsTable[ch];\n    }\n    string reverseVowels(string s) {\n        int left=0, right=s.size()-1;\n        while ( left < right ) {\n            while( !isVowels( s[left]) ) left++;\n            while( !isVowels( s[right] ) ) right--;\n            if (left >= right) break;\n            swap(s[left], s[right]);\n            left++; right--;\n        }\n        return s;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/reverseWordsInAString/reverseWordsInAString.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/\n// Author : Hao Chen\n// Date   : 2015-02-09\n\n/********************************************************************************** \n * \n * Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. \n * \n * The input string does not contain leading or trailing spaces and the words are always separated by a single space. \n * \n * For example,\n *  Given s = \"the sky is blue\",\n *  return \"blue is sky the\". \n * \n * Could you do it in-place without allocating extra space? \n * \n * \n **********************************************************************************/\n\n#include <ctype.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nvoid swap(char &a, char &b) {\n    char temp = a;\n    a = b;\n    b = temp;\n}\nvoid reverse(string &s, int begin, int end) {\n    while(begin < end) {\n        swap(s[begin++], s[end--]);\n    }\n}\nvoid reverseWords(string &s) {\n\n    if (s.size()<=1) return;\n\n    // reverse the whole string\n    reverse(s, 0, s.size()-1);\n\n    // reverse the each word\n    for ( int begin=0, i=0; i<=s.size(); i++ ) {\n        if ( isblank(s[i]) || s[i] == '\\0') {\n            reverse(s, begin, i-1);\n            begin = i+1;\n        }\n    }\n}\n\n\nint main(int argc, char** argv)\n{\n    string s = \"the sky is blue\";\n    if ( argc > 1 ) {\n        s = argv[1];\n    }\n    \n    cout << s << endl;\n    reverseWords(s);\n    cout << s << endl;\n    \n}\n"
  },
  {
    "path": "algorithms/cpp/reverseWordsInAString/reverseWordsInAString.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/\n// Author : Hao Chen, Siwei Xu\n// Date   : 2014-06-16\n\n/********************************************************************************** \n* \n* Given an input string, reverse the string word by word.\n* \n* For example,\n* Given s = \"the sky is blue\",\n* return \"blue is sky the\".\n* \n* \n* Clarification:\n* \n* What constitutes a word?\n* A sequence of non-space characters constitutes a word.\n* Could the input string contain leading or trailing spaces?\n* Yes. However, your reversed string should not contain leading or trailing spaces.\n* How about multiple spaces between two words?\n* Reduce them to a single space in the reversed string.\n* \n*               \n**********************************************************************************/\n\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>  // for std::reverse\nusing namespace std;\n\nvoid reverseWords(string &s) {\n    \n    bool wordStart = false;\n    vector<string> v;\n    \n    const char *pHead =s.c_str();\n    const char *pStr, *pBegin, *pEnd;\n   \n    for (pStr=pHead; *pStr!='\\0'; pStr++) {\n        if (!isspace(*pStr) && wordStart == false){\n            wordStart = true;\n            pBegin = pStr;\n            continue;\n        }\n        \n        if(isspace(*pStr) && wordStart==true){\n            wordStart=false;\n            pEnd = pStr;\n            v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );\n        }\n        \n    }\n\n    if (wordStart==true){\n        pEnd = pStr;\n        v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );\n    }\n    \n    if (v.size()>0){\n        s.clear();\n        char space=' ';\n        vector<string>::iterator it;\n        for (it=v.begin(); it!=v.end(); ++it) {\n            s = s + *it;\n            s.push_back(space);\n        }\n        s.erase(s.end()-1);\n    }else{\n            s.clear();\n    }\n    cout << \"[\" << s << \"]\" <<endl;\n}\n\n// inspired from <Programming Pearls> -- Handwaving\nvoid reverseWords2(string &s) {\n    if (s.length() == 0) return;\n\n    string result = \"\";\n    if (s[s.length()-1] == ' ') {\n        int last = s.find_last_not_of(' ') + 1;\n        s.erase(last, s.length() - last);\n    }\n\n    int first = s.find_first_not_of(' ', 0);\n    while (first != string::npos) {\n        int wend = s.find(' ', first);  // word end\n        if (wend == string::npos) wend = s.length();\n\n        string word = s.substr(first, wend - first);\n        reverse(word.begin(), word.end());\n        result += word;\n\n        first = s.find_first_not_of(' ', wend); // next word\n        if (first == string::npos) break;\n\n        result += ' ';\n    }\n    reverse(result.begin(), result.end());\n    s.swap(result);\n}\n\n\n// C solution in O(1) space\nvoid reverse(char *b, char *e) {\n    for (--e; e - b > 0; b++, e--) {\n        char t = *b;\n        *b = *e;\n        *e = t;\n    }\n}\n\nvoid reverseWords(char *s) {\n    char *p = s, *ws = NULL, *last = s;\n\n    while (*p && *p == ' ') p++; // skip leading space\n    ws = p;\n\n    for ( ; *p; p++) {\n        while (*p && *p != ' ') p++; // find word end\n\n        reverse(ws, p);\n        strncpy(last, ws, p-ws);\n        last += (p-ws);\n\n        while (*p && *p == ' ') p++; // for next word\n        ws = p;\n\n        if (*p == '\\0') break;\n        *last++ = ' ';\n    }\n    reverse(s, last);\n    *last = '\\0';\n}\n\nvoid test() {\n#define TEST(str) do {       \\\n    char* s = strdup(str);   \\\n    printf(\"\\\"%s\\\" => \", s); \\\n    reverseWords(s);         \\\n    printf(\"\\\"%s\\\"\\n\\n\", s); \\\n    free(s);                 \\\n    } while (0)\n\n    TEST(\"  the    blue   sky  is blue    \");\n    TEST(\"  \");\n}\n\n\nmain()\n{\n   string s;\n   reverseWords(s);\n   s=\" \";\n   reverseWords(s);\n   s=\"1 \";\n   reverseWords(s);\n   s=\"love\";\n   reverseWords(s);\n   s=\"i love cpp\";\n   reverseWords(s);\n\n   test();\n}    \n"
  },
  {
    "path": "algorithms/cpp/romanToInteger/romanToInteger.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/roman-to-integer/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Given a roman numeral, convert it to an integer.\n* \n* Input is guaranteed to be within the range from 1 to 3999.\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint romanCharToInt(char ch){\n    int d = 0;\n    switch(ch){\n        case 'I':  \n            d = 1;  \n            break;  \n        case 'V':  \n            d = 5;  \n            break;  \n        case 'X':  \n            d = 10;  \n            break;  \n        case 'L':  \n            d = 50;  \n            break;  \n        case 'C':  \n            d = 100;  \n            break;  \n        case 'D':  \n            d = 500;  \n            break;  \n        case 'M':  \n            d = 1000;  \n            break;  \n    }\n    return d;\n}\nint romanToInt(string s) {\n    if (s.size()<=0) return 0;\n    int result = romanCharToInt(s[0]);\n    for (int i=1; i<s.size(); i++){\n        int prev = romanCharToInt(s[i-1]);\n        int curr = romanCharToInt(s[i]);\n        //if left<right such as : IV(4), XL(40), IX(9) ...\n        if (prev < curr) {\n            result = result - prev + (curr-prev);\n        }else{\n            result += curr;\n        }\n    }\n    return result;\n}\n\nint main(int argc, char**argv)\n{\n    string s(\"XL\");\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << s << \" : \" << romanToInt(s) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/rotateArray/rotateArray.cpp",
    "content": "// Source : https://leetcode.com/problems/rotate-array/\n// Author : Hao Chen\n// Date   : 2015-03-30\n\n/********************************************************************************** \n* \n* Rotate an array of n elements to the right by k steps.\n* For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. \n* \n* Note:\n* Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.\n* \n* Hint:\n* Could you do it in-place with O(1) extra space?\n* \n* Related problem: Reverse Words in a String II\n* \n* Credits:Special thanks to @Freezen for adding this problem and creating all test cases.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\nusing namespace std;\n\n\nvoid reverseArray(int nums[],int start, int end){\n    int temp;\n    while(start < end){\n        int temp = nums[start];\n        nums[start++] = nums[end];\n        nums[end--] = temp;\n    }\n}\n\n/*\n * this solution is so-called three times rotate method\n * because (X^TY^T)^T = YX, so we can perform rotate operation three times to get the result\n * obviously, the algorithm consumes O(1) space and O(n) time\n */\n\nvoid rotate1(int nums[], int n, int k) {\n    if (k<=0) return;\n    k %= n; \n    reverseArray(nums, n-k, n-1);\n    reverseArray(nums, 0, n-k-1);\n    reverseArray(nums, 0, n-1);    \n}\n\n/*\n * How to change [0,1,2,3,4,5,6] to [4,5,6,0,1,2,3] by k = 3?\n *\n * We can change by following rules: \n *\n *     [0]->[3], [3]->[6], [6]->[2],  [2]->[5], [5]->[1], [1]->[4]\n *    \n *\n */\nvoid rotate2(int nums[], int n, int k) {\n    if (k<=0) return;\n    k %= n;\n    int currIdx=0, newIdx=k;\n    int tmp1 = nums[currIdx], tmp2; \n    int origin = 0;\n\n    for(int i=0; i<n; i++){\n\n        tmp2 = nums[newIdx];\n        nums[newIdx] = tmp1;\n        tmp1 = tmp2; \n\n        currIdx = newIdx;\n\n        //if we meet a circle, move the next one\n        if (origin == currIdx) {\n            origin = ++currIdx;\n            tmp1 = nums[currIdx];\n        }\n        newIdx = (currIdx + k) % n;\n\n    } \n}\n\nvoid rotate(int nums[], int n, int k) {\n    if (random()%2==0) {\n        cout << \"[1] \";\n        return rotate1(nums, n, k);\n    }\n    cout << \"[2] \";\n    return rotate2(nums, n, k);\n}\n\nvoid printArray(int nums[], int n) {\n    cout << \"[ \" ;\n    for(int i=0; i<n; i++) {\n        cout << nums[i] << ((i==n-1)? \" \" : \", \");\n    }\n    cout << \"]\" << endl;\n}\n\nvoid initArray(int nums[], int n) {\n    for(int i=0; i<n; i++) {\n        nums[i] = i;\n    }\n}\n\n\nint main(int argc, char**argv) {\n    \n    srand(time(0));\n\n    int nums[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\n    const int n = sizeof(nums)/sizeof(int);\n\n    for (int i=0; i<n; i++) {\n        initArray(nums, n);\n        rotate(nums, n, i);\n        printArray(nums, n);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/rotateFunction/RotateFunction.cpp",
    "content": "// Source : https://leetcode.com/problems/rotate-function/\n// Author : Hao Chen\n// Date   : 2016-11-03\n\n/*************************************************************************************** \n *\n * Given an array of integers A and let n to be its length.\n * \n * Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we \n * define a \"rotation function\" F on A as follow:\n * \n * F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].\n * \n * Calculate the maximum value of F(0), F(1), ..., F(n-1). \n * \n * Note:\n * n is guaranteed to be less than 105.\n * \n * Example:\n * \n * A = [4, 3, 2, 6]\n * \n * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\n * F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\n * F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\n * F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\n * \n * So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n ***************************************************************************************/\n\n\n// \n// Asumming we have 4 numbers: a, b, c, d, then\n//   F(0) = 0a + 1b + 2c + 3d\n//   F(1) = 3a + 0b + 1c + 2d\n//   F(2) = 2a + 3b + 0c + 1d\n//   F(3) = 1a + 2b + 3c + 0d\n//\n// We can see how F(n) transfrom to F(n+1) \n//   F(0) - F(1) = -3a + b + c + d  \n//   F(1) - F(2) = a + -3b + c + d\n//   F(2) - F(3) = a + b + -3c + d\n//   F(3) - F(0) = a + b + c + -3d\n//   \n// So, we can tansfrom to the following experssion: \n// \n//   F(1) = F(0) - (a+b+c+d) + 4a  \n//   F(2) = F[1] - (a+b+c+d) + 4b\n//   F(3) = F[2] - (a+b+c+d) + 4c\n// \n// Then, we can see this fomular:\n//\n//   F(n) = F(n-1) - sum(array) + len(array) * array[n-1]\n//   \nclass Solution {\npublic:    \n    int maxRotateFunction(vector<int>& A) {\n        int sum = 0;\n        int F = 0;\n        for (int i=0; i < A.size(); i++) {\n            sum += A[i];\n            F += (i * A[i]);\n        }\n        int maxF = F;\n        int len = A.size();\n        //cout << \"F(0) = \" << maxF <<endl;\n        for (int i=1; i< len; i++) {\n            F = F - sum + len * A[i-1];\n            //cout << \"F(\" << i << \") = \" << F << endl;\n            maxF = max(maxF, F);\n        }\n        \n        return maxF;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/rotateImage/rotateImage.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/rotate-image/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* You are given an n x n 2D matrix representing an image.\n* Rotate the image by 90 degrees (clockwise).\n* Follow up:\n* Could you do this in-place?\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid rotate(vector<vector<int> > &matrix) {\n\n    int n = matrix.size();\n\n    for( int i=0; i<n/2; i++ ){\n        int low=i, high=n-i-1;\n        for (int j=low; j<high; j++){\n            int tmp;\n            tmp = matrix[i][j];\n            // left to top \n            matrix[i][j] = matrix[n-j-1][i];\n            // bottom to left\n            matrix[n-j-1][i] = matrix[n-i-1][n-j-1];\n            // right to bottom\n            matrix[n-i-1][n-j-1] = matrix[j][n-i-1];\n            // top to right\n            matrix[j][n-i-1] = tmp;\n        }\n    }\n}\n\nvoid printMatrix(vector<vector<int> > &matrix) \n{\n    for(int i=0; i<matrix.size(); i++){\n        for(int j=0; j< matrix[i].size(); j++) {\n            printf(\"%3d \", matrix[i][j]) ;\n        }\n        cout << endl;\n    }\n    cout << endl;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 2;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector< vector<int> > matrix;\n    for (int i=1; i<=n; i++) {\n        vector<int> v;\n        for(int j=1; j<=n; j++){\n            v.push_back( (i-1)*n + j );\n        }\n        matrix.push_back(v);\n    }\n\n    printMatrix(matrix);\n    rotate(matrix);\n    printMatrix(matrix);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/rotateList/rotateList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/rotate-list/\n// Author : Hao Chen\n// Date   : 2014-06-20\n\n/********************************************************************************** \n* \n* Given a list, rotate the list to the right by k places, where k is non-negative.\n* \n* For example:\n* Given 1->2->3->4->5->NULL and k = 2,\n* return 4->5->1->2->3->NULL.\n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *rotateRight(ListNode *head, int k) {\n        if (!head || k<=0){\n            return head;\n        }\n        \n        //find the length of List\n        int len=1;\n        ListNode *p=head;\n        while( p->next != NULL ){\n            p = p->next;\n            len++;\n        }\n        //connect the tail to head\n        p->next = head;\n        //find the left place (take care the case - k > len)\n        k = len - k % len;\n        \n        //find the place\n        for(int i=0; i<k; i++){\n            p = p->next;\n        }\n        \n        //break the list\n        head = p->next;\n        p->next = NULL;\n        \n        return head;\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/rotatingTheBox/RotatingTheBox.cpp",
    "content": "// Source : https://leetcode.com/problems/rotating-the-box/\n// Author : Hao Chen\n// Date   : 2021-05-22\n\n/***************************************************************************************************** \n *\n * You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the \n * box is one of the following:\n * \n * \tA stone '#'\n * \tA stationary obstacle '*'\n * \tEmpty '.'\n * \n * The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each \n * stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity \n * does not affect the obstacles' positions, and the inertia from the box's rotation does not affect \n * the stones' horizontal positions.\n * \n * It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the \n * box.\n * \n * Return an n x m matrix representing the box after the rotation described above.\n * \n * Example 1:\n * \n * Input: box = [[\"#\",\".\",\"#\"]]\n * Output: [[\".\"],\n *          [\"#\"],\n *          [\"#\"]]\n * \n * Example 2:\n * \n * Input: box = [[\"#\",\".\",\"*\",\".\"],\n *               [\"#\",\"#\",\"*\",\".\"]]\n * Output: [[\"#\",\".\"],\n *          [\"#\",\"#\"],\n *          [\"*\",\"*\"],\n *          [\".\",\".\"]]\n * \n * Example 3:\n * \n * Input: box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n *               [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n *               [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\n * Output: [[\".\",\"#\",\"#\"],\n *          [\".\",\"#\",\"#\"],\n *          [\"#\",\"#\",\"*\"],\n *          [\"#\",\"*\",\".\"],\n *          [\"#\",\".\",\"*\"],\n *          [\"#\",\".\",\".\"]]\n * \n * Constraints:\n * \n * \tm == box.length\n * \tn == box[i].length\n * \t1 <= m, n <= 500\n * \tbox[i][j] is either '#', '*', or '.'.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    void rotate(vector<vector<char>>& src, vector<vector<char>>& dest) {\n        int m = src.size();\n        for(int row=0; row<dest.size(); row++) {\n            for(int col=0; col<dest[row].size(); col++) {\n                dest[row][col] = src[m-col-1][row];\n            }\n        }\n    }\n    void gravity(vector<vector<char>>& box) {\n        int m = box.size();\n        int n = box[0].size();\n        for(int col=0; col<n; col++) {\n            int bottom = m - 1;\n            for(int row=m-1; row>=0; row-- ) {\n                \n                if (box[row][col] == '#') {\n                    box[row][col] = '.';\n                    box[bottom][col] = '#';\n                    bottom--;\n                }else if (box[row][col] == '*') {\n                    bottom = row-1;\n                }\n            }\n        }\n    }\n    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {\n        int row = box.size();\n        int col = box[0].size();\n        vector<vector<char>> result(col, vector<char>(row,'.'));\n        rotate(box, result);\n        gravity(result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sameTree/sameTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/same-tree/\n// Author : Hao Chen\n// Date   : 2014-06-27\n\n/********************************************************************************** \n* \n* Given two binary trees, write a function to check if they are equal or not.\n* \n* Two binary trees are considered equal if they are structurally identical and the nodes have the same value.\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n    bool isSameTree(TreeNode *p, TreeNode *q) {\n        if (random()%2){\n            return isSameTree1(p, q);\n        }\n        return isSameTree2(p, q);\n    }\n    \n    bool isSameTree1(TreeNode *p, TreeNode *q) {\n        if(!p && !q) return true;  \n        if(!p || !q) return false;  \n        return (p->val == q->val) &&  \n                isSameTree(p->left, q->left) &&   \n                isSameTree(p->right, q->right);\n    }\n    \n    bool isSameTree2(TreeNode *p, TreeNode *q) {\n        \n        queue<TreeNode*> q1, q2;\n        q1.push(p);\n        q2.push(q);\n        while (q1.size()>0 && q2.size()>0 ){\n            TreeNode* p1 = q1.front();\n            q1.pop();\n            TreeNode* p2 = q2.front();\n            q2.pop();\n            if (!p1 && !p2) continue;\n            if (!p1 || !p2)  return false;\n\n            if ( p1->val != p2->val) {\n                return false;\n            }\n\n            q1.push(p1->left);\n            q2.push(p2->left);\n\n            q1.push(p1->right);\n            q2.push(p2->right);\n\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/satisfiabilityOfEqualityEquations/SatisfiabilityOfEqualityEquations.cpp",
    "content": "// Source : https://leetcode.com/problems/satisfiability-of-equality-equations/\n// Author : Hao Chen\n// Date   : 2019-03-25\n\n/***************************************************************************************************** \n *\n * Given an array equations of strings that represent relationships between variables, each string \n * equations[i] has length 4 and takes one of two different forms: \"a==b\" or \"a!=b\".  Here, a and b \n * are lowercase letters (not necessarily different) that represent one-letter variable names.\n * \n * Return true if and only if it is possible to assign integers to variable names so as to satisfy all \n * the given equations.\n * \n * Example 1:\n * \n * Input: [\"a==b\",\"b!=a\"]\n * Output: false\n * Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the \n * second.  There is no way to assign the variables to satisfy both equations.\n * \n * Example 2:\n * \n * Input: [\"b==a\",\"a==b\"]\n * Output: true\n * Explanation: We could assign a = 1 and b = 1 to satisfy both equations.\n * \n * Example 3:\n * \n * Input: [\"a==b\",\"b==c\",\"a==c\"]\n * Output: true\n * \n * Example 4:\n * \n * Input: [\"a==b\",\"b!=c\",\"c==a\"]\n * Output: false\n * \n * Example 5:\n * \n * Input: [\"c==c\",\"b==d\",\"x!=z\"]\n * Output: true\n * \n * Note:\n * \n * \t1 <= equations.length <= 500\n * \tequations[i].length == 4\n * \tequations[i][0] and equations[i][3] are lowercase letters\n * \tequations[i][1] is either '=' or '!'\n * \tequations[i][2] is '='\n * \n ******************************************************************************************************/\n\n\nclass Solution {\nprivate:\n    map<char, char>  eq_map; // the table store the equivalent relationship\n    void init() {\n        for (char ch='a'; ch<='z'; ch++) {\n            eq_map[ch] = ch;\n        }\n    }\npublic:\n    Solution() {\n        init();\n    }\n    \n    // find the tail node, \n    // if a == b == c == d, find(a) would return d;\n    //                      find(b) would return d;\n    char find(char ch) {\n        while(ch != eq_map[ch]) {\n            ch = eq_map[ch];\n        }\n        return ch;\n    }\n    \n    //join x equivalent chain with y equivalent chain\n    void join(char x, char y) {\n        char tx = find(x);\n        char ty = find(y);\n        if (tx != ty) { \n            eq_map[tx] = ty;\n        }\n    }\n\n    bool equationsPossible(vector<string>& equations) {\n        for (auto e : equations ) {\n            if (e[1] == '=' && e[0] != e[3]) { // equal\n                join(e[0], e[3]);\n            }\n        }\n        for (auto e : equations) {\n            if (e[1] == '!' && (e[0] == e[3] || find(e[0]) == find(e[3]) ) ) { \n                return false;\n            }\n        }\n        return true;\n    }\n};\n\n\n"
  },
  {
    "path": "algorithms/cpp/scrambleString/scrambleString.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/scramble-string/\n// Author : Hao Chen\n// Date   : 2014-10-09\n\n/********************************************************************************** \n* \n* Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.\n* \n* Below is one possible representation of s1 = \"great\":\n* \n*     great\n*    /    \\\n*   gr    eat\n*  / \\    /  \\\n* g   r  e   at\n*            / \\\n*           a   t\n* \n* To scramble the string, we may choose any non-leaf node and swap its two children.\n* \n* For example, if we choose the node \"gr\" and swap its two children, it produces a scrambled string \"rgeat\".\n* \n*     rgeat\n*    /    \\\n*   rg    eat\n*  / \\    /  \\\n* r   g  e   at\n*            / \\\n*           a   t\n* \n* We say that \"rgeat\" is a scrambled string of \"great\".\n* \n* Similarly, if we continue to swap the children of nodes \"eat\" and \"at\", it produces a scrambled string \"rgtae\".\n* \n*     rgtae\n*    /    \\\n*   rg    tae\n*  / \\    /  \\\n* r   g  ta  e\n*        / \\\n*       t   a\n* \n* We say that \"rgtae\" is a scrambled string of \"great\".\n* \n* Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\n// The recursive way is quite simple.\n//    1) break the string to two parts: \n//          s1[0..j]   s1[j+1..n]\n//          s2[0..j]   s2[j+1..n]\n//    2) then\n//          isScramble(s1[0..j], s2[0..j]) &&  isScramble(s1[j+1..n], s2[j+1..n])\n//        OR\n//          isScramble(s1[0..j], s2[j+1, n]) &&  isScramble(s1[j+1..n], s2[0..j])\nbool isScramble_recursion(string s1, string s2) {\n\n    if (s1.size()!= s2.size() || s1.size()==0 || s2.size()==0) {\n        return false;\n    }\n    if (s1 == s2){\n        return true;\n    } \n    string ss1 = s1;\n    string ss2 = s2;\n    sort(ss1.begin(), ss1.end()); \n    sort(ss2.begin(), ss2.end()); \n    if (ss1 != ss2 ) {\n        return false;\n    }\n\n    for (int i=1; i<s1.size(); i++) {\n        if ( isScramble_recursion(s1.substr(0,i), s2.substr(0,i)) && \n             isScramble_recursion(s1.substr(i, s1.size()-i), s2.substr(i, s2.size()-i)) ) {\n            return true;\n        }\n        if ( isScramble_recursion(s1.substr(0,i), s2.substr(s2.size()-i, i)) && \n             isScramble_recursion(s1.substr(i, s1.size()-i), s2.substr(0, s2.size()-i)) ) {\n            return true;\n        }\n    }\n\n    return false;\n    \n}\n\n/* \n *  Definition\n *  \n *      dp[k][i][j] means:\n *  \n *         a) s1[i] start from 'i'\n *         b) s2[j] start from 'j'\n *         c) 'k' is the length of substring\n *  \n *  Initialization     \n *  \n *      dp[1][i][j] = (s1[i] == s2[j] ? true : false)\n *  \n *  Formula\n *  \n *      same as the above recursive method idea\n *  \n *      dp[k][i][j] = \n *          dp[divk][i][j] && dp[k-divk][i+divk][j+divk] ||\n *          dp[divk][i][j+k-divk] && dp[k-divk][i+divk][j]\n *  \n *      `divk` mean split the k to two parts, so 0 <= divk <= k;\n*/\nbool isScramble_dp(string s1, string s2) {\n\n    if (s1.size()!= s2.size() || s1.size()==0 || s2.size()==0) {\n        return false;\n    }\n    if (s1 == s2){\n        return true;\n    }\n\n    const int len = s1.size();    \n    \n    // dp[len+1][len][len]\n    vector< vector< vector<bool> > > dp(len+1, vector< vector<bool> >(len, vector<bool>(len) ) );\n   \n    // ignor the k=0, just for readable code.\n\n    // initialization k=1\n    for (int i=0; i<len; i++){\n        for (int j=0; j<len; j++) {\n            dp[1][i][j] = (s1[i] == s2[j]);\n        }\n    } \n    // start from k=2 to len, O(n^4) loop. \n    for (int k=2; k<=len; k++){\n        for (int i=0; i<len-k+1; i++){\n            for (int j=0; j<len-k+1; j++){\n                dp[k][i][j] = false;\n                for (int divk = 1; divk < k && dp[k][i][j]==false; divk++){\n                    dp[k][i][j] = ( dp[divk][i][j] && dp[k-divk][i+divk][j+divk] ) ||\n                                  ( dp[divk][i][j+k-divk] && dp[k-divk][i+divk][j] );\n                }\n            }\n        }\n    }\n    \n    return dp[len][0][0];\n}\n\nbool isScramble(string s1, string s2) {\n\n    srand(time(0));\n\n    if (random()%2) {\n        cout << \"---- recursion ---\" << endl;\n        return isScramble_recursion(s1, s2);\n    }\n    cout << \"---- dynamic programming ---\" << endl;\n    return isScramble_dp(s1, s2);\n}\n\nint main(int argc, char** argv)\n{\n    string s1=\"great\", s2=\"rgtae\";\n    if (argc>2){\n        s1 = argv[1];\n        s2 = argv[2];\n    }\n    cout << s1 << \", \" << s2 << endl;\n    cout << isScramble(s1, s2) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/search2DMatrix/search2DMatrix.II.cpp",
    "content": "// Source : https://leetcode.com/problems/search-a-2d-matrix-ii/\n// Author : Hao Chen\n// Date   : 2015-08-15\n\n/********************************************************************************** \n * \n * Write an efficient algorithm that searches for a value in an m x n matrix. This \n * matrix has the following properties:\n * \n * Integers in each row are sorted in ascending from left to right.\n * Integers in each column are sorted in ascending from top to bottom.\n * \n * For example,\n * \n * Consider the following matrix:\n * \n * [\n *   [1,   4,  7, 11, 15],\n *   [2,   5,  8, 12, 19],\n *   [3,   6,  9, 16, 22],\n *   [10, 13, 14, 17, 24],\n *   [18, 21, 23, 26, 30]\n * ]\n * \n * Given target = 5, return true.\n * Given target = 20, return false.\n *               \n *               \n * \n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    \n    bool binary_search(vector<int> &v, int target) {\n        int low = 0;\n        int high = v.size()-1;\n        while(low <= high) {\n            int mid = low + (high - low)/2;\n            if (target == v[mid]) return true;\n            if (target < v[mid]) {\n                high = mid -1;\n            }else {\n                low = mid + 1;\n            }\n        }\n        \n        return false;\n    }\n    \n    //using binary_search() to search each rows - slow O(n*log(n))\n    //the run time is around 140ms for all test case\n    bool searchMatrix01(vector<vector<int>>& matrix, int target) {\n        if (matrix.size() == 0 || matrix[0].size()==0) return false;\n        for (int i=0; i<matrix.size(); i++){\n            if (target < matrix[i][0] ) return false;\n            if (binary_search(matrix[i], target))  return true;\n\n        }\n        return false;\n    }\n    \n    \n    //start the liner search from top right corner of matrix. - O(m+n)\n    //the run time is around 64ms\n    bool searchMatrix02(vector<vector<int>>& matrix, int target) {\n        if (matrix.size() == 0 || matrix[0].size()==0) return false;\n        int row=0,  col = matrix[0].size() - 1; \n        while (row < matrix.size() && col >=0 ) {\n            if (target == matrix[row][col]) return true;\n            if (target < matrix[row][col]) {\n                col--;\n            }else{\n                row++;\n            }\n            \n        }\n        return false;\n    }\n    \n    //a bit optimization for methed 2 - the run time is 68ms\n    bool searchMatrix021(vector<vector<int>>& matrix, int target) {\n        if (matrix.size() == 0 || matrix[0].size()==0) return false;\n        int row=0,  col = matrix[0].size() - 1; \n        while (row < matrix.size() && col >=0 ) {\n            if (target == matrix[row][col]) return true;\n            while ( col>=0 && target < matrix[row][col]) {\n                col--;\n            }\n            while(col >=0 && row < matrix.size() && target > matrix[row][col]){\n                row++;\n            }\n            \n        }\n        return false;\n    }\n\n    //Optimization: using binary search methed to move `low` and `row` \n    //However, the run time is 112ms\n    bool searchMatrix022(vector<vector<int>>& matrix, int target) {\n        if (matrix.size() == 0 || matrix[0].size()==0) return false;\n        \n        int row=0,  col = matrix[0].size() - 1; \n        \n        while (row < matrix.size() && col >=0 ) {\n            \n            if (target == matrix[row][col]) return true;\n            \n            if (target < matrix[row][col]) {\n                int start=0, end=col;\n                while(start <= end){\n                    int mid = start + (end - start)/2;\n                    if (target == matrix[row][mid]) return true;\n                    if (target > matrix[row][mid]) {\n                        start = mid + 1;\n                    }else {\n                        end = mid - 1;\n                    }\n                }\n                col = end; \n            }else{\n                int start=row, end=matrix.size()-1;\n                while(start<=end){\n                    int mid = start + (end - start)/2;\n                    if (target == matrix[mid][col]) return true;\n                    if (target > matrix[mid][col]) {\n                        start = mid + 1;\n                    }else{\n                        end = mid -1;\n                    }\n                }\n                row = start;\n            }\n            \n        }\n        return false;\n    }\n    \n    \n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        return searchMatrix022(matrix, target); //112ms\n        return searchMatrix021(matrix, target); //68ms\n        return searchMatrix02(matrix, target); //64ms\n        return searchMatrix01(matrix, target); //148ms\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/search2DMatrix/search2DMatrix.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/search-a-2d-matrix/\n// Author : Hao Chen\n// Date   : 2014-06-23\n\n/********************************************************************************** \n* \n* Write an efficient algorithm that searches for a value in an m x n matrix. \n* This matrix has the following properties:\n* \n* Integers in each row are sorted from left to right.\n* The first integer of each row is greater than the last integer of the previous row.\n* \n* For example,\n* \n* Consider the following matrix:\n* \n* [\n*   [1,   3,  5,  7],\n*   [10, 11, 16, 20],\n*   [23, 30, 34, 50]\n* ]\n* \n* Given target = 3, return true.\n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        return searchMatrix01(matrix, target);\n        return searchMatrix02(matrix, target);\n    }\n\n    //Just simply convert the 2D matrix to 1D array.\n    bool searchMatrix01(vector<vector<int>>& matrix, int target) {\n        int row = matrix.size();\n        int col = row>0 ? matrix[0].size() : 0;\n        \n        int len = row * col;\n        int low = 0, high = len -1;\n        while (low <= high) {\n            \n            int mid = low + (high - low) / 2;\n            int r = mid / col;\n            int c = mid % col;\n \n            int n = matrix[r][c];\n            if (n == target) return true;\n            if (n < target) low = mid+1;\n            else high = mid -1;\n        }\n        return false;\n    }\n\n\n\n    bool searchMatrix02(vector<vector<int> > &matrix, int target) {\n        \n        int idx = vertical_binary_search(matrix, target);\n        if (idx<0){\n            return false;\n        }\n        \n        idx = binary_search(matrix[idx], target);\n        \n        return (idx < 0 ? false : true);\n        \n    }\n    int vertical_binary_search(vector< vector<int> > v, int key){\n        int low = 0;\n        int high = v.size()-1;\n        while(low <= high){\n            int mid = low + (high-low)/2;\n            if (v[mid][0] == key){\n                return mid;\n            }\n            if (key < v[mid][0]){\n                high = mid - 1;\n                continue;\n            }\n            if (key > v[mid][0]){\n                low = mid + 1;\n                continue;\n            }\n        }\n        return low-1;        \n    }\n    \n    int binary_search(vector<int> v, int key) {\n        int low = 0;\n        int high = v.size()-1;\n        while(low <= high){\n            int mid = low + (high-low)/2;\n            if (v[mid] == key){\n                return mid;\n            }\n            if (key < v[mid]){\n                high = mid - 1;\n                continue;\n            }\n            if (key > v[mid]){\n                low = mid + 1;\n                continue;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/searchForRange/searchForRange.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/search-for-a-range/\n// Author : Hao Chen\n// Date   : 2014-06-26\n\n/********************************************************************************** \n* \n* Given a sorted array of integers, find the starting and ending position of a given target value.\n* \n* Your algorithm's runtime complexity must be in the order of O(log n).\n* \n* If the target is not found in the array, return [-1, -1].\n* \n* For example,\n* Given [5, 7, 7, 8, 8, 10] and target value 8,\n* return [3, 4].\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nint binary_search(int A[], int low, int high, int key);\n\n/*\n *   O(log n) solution must be something like binary search.\n *\n *   So, we can use the binary search to find the one postion - `pos`\n *   \n *   then, we can keep using the binary search find the target in A[0..pos-1] and A[pos+1..n]\n *\n *   The code below is self-explaination\n */\nvector<int> searchRange(int A[], int n, int target) {\n    int pos = binary_search(A, 0, n-1, target);\n\n    vector<int> v;\n    int low = -1, high = -1;\n    if (pos >=0){\n        low = high = pos;\n        int l = low;\n        do {\n            low = l;\n            l = binary_search(A, 0, low - 1, target);\n        }while (l>=0);\n\n        int h = high;\n        do {\n            high = h;\n            h = binary_search(A, high + 1, n-1, target);\n        }while (h>=0);\n    }\n\n    v.push_back(low);\n    v.push_back(high);\n    return v;\n\n}\n\nint binary_search(int A[], int low, int high, int key){\n\n    while (low<=high) {\n        int mid = low + (high-low)/2;\n        if (A[mid] == key) {\n            return mid;\n        }\n        if (key > A[mid]) {\n            low = mid + 1;\n        }\n        if (key < A[mid]) {\n            high = mid - 1;\n        }\n    }\n    return -1;\n}\n\nvoid printVector( vector<int>&  pt)\n{\n    cout << \"{ \";\n    for(int j=0; j<pt.size(); j++){\n        cout << pt[j] << \" \";\n    }\n    cout << \"} \" << endl;\n}\n\n\nint main()\n{\n    const int cnt=6;\n    int a[cnt] ={5, 7, 7, 8, 8, 10};\n\n    vector<int> v;\n    v = searchRange(a, cnt, 8);     \n    printVector(v);    \n\n\n    int b[cnt] ={5, 5, 5, 8, 8, 10};\n    v = searchRange(b, cnt, 5);     \n    printVector(v);    \n\n    int c[cnt] ={5, 5, 5, 5, 5, 5};\n    v = searchRange(c, cnt, 5);     \n    printVector(v);    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/searchInRotatedSortedArray/searchInRotatedSortedArray.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/\n// Author : Hao Chen\n// Date   : 2014-06-29\n\n/********************************************************************************** \n* \n* Follow up for \"Search in Rotated Sorted Array\":\n* What if duplicates are allowed?\n* \n* Would this affect the run-time complexity? How and why?\n* \n* Write a function to determine if a given target is in the array.\n*               \n**********************************************************************************/\n\n// Using the same idea \"Search in Rotated Sorted Array\"\n// but need be very careful about the following cases:\n//   [3,3,3,4,5,6,3,3] \n//   [3,3,3,3,1,3]\n// After split, you don't know which part is rotated and which part is not.\n// So, you have to skip the ducplication\n//   [3,3,3,4,5,6,3,3] \n//          ^       ^\n//   [3,3,3,3,1,3]\n//            ^ ^\nclass Solution {\npublic:\n    bool search(int A[], int n, int key) {\n        if (n<=0) return false;\n    \n        if (n==1){\n            return (A[0]==key) ? true : false;\n        }\n        int low=0, high=n-1;\n        while( low<=high ){\n    \n            if (A[low] < A[high] && ( key < A[low] || key > A[high]) ) {\n                 return false;\n            }\n            \n            //if dupilicates, remove the duplication\n            while (low < high && A[low]==A[high]){\n                low++;\n            }\n    \n            int mid = low + (high-low)/2;\n            if ( A[mid] == key ) return true;\n    \n            //the target in non-rotated array\n            if (A[low] < A[mid] && key >= A[low] && key< A[mid]){\n                high = mid - 1;\n                continue;\n            }\n            //the target in non-rotated array\n            if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){\n                low = mid + 1;\n                continue;\n            }\n            //the target in rotated array\n            if (A[low] > A[mid] ){\n                high = mid - 1;\n                continue;\n            }\n            //the target in rotated array\n            if (A[mid] > A[high] ){\n                low = mid + 1;\n                continue;\n            }\n            \n            //reach here means nothing found.\n            low++;\n        }\n        return false;\n    }\n    \n    \n};\n"
  },
  {
    "path": "algorithms/cpp/searchInRotatedSortedArray/searchInRotatedSortedArray.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array/\n// Author : Hao Chen\n// Date   : 2014-06-28\n\n/********************************************************************************** \n* \n* Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n* \n* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n* \n* You are given a target value to search. If found in the array return its index, otherwise return -1.\n* \n* You may assume no duplicate exists in the array.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint binary_search(int A[], int n, int key); \nint binary_search(int A[], int l, int h, int key); \nint rotate_search(int A[], int l, int h, int key);\n\nint search1(int A[], int n, int target);\nint search2(int A[], int n, int target); \n\nint search(int A[], int n, int target) {\n    if (random()%2){\n        return search1(A, n, target);\n    }\n    return search2(A, n, target);\n}\n/*\n *    Using binary search idea, \n *    1) Spliting the array to two part, one part should be non-rotated, another one is rotated.\n *    2) Checking the \"key\" whether is possible in non-rotated sorted part.\n *        2.1) if it is, then go to the classcial binary searh.\n *        2.2) if it not, then keep spliting the rorated part.\n *\n */\nint search1(int A[], int n, int key) {\n    if (n<=0) return -1;\n\n    if (n==1){\n        return (A[0]==key) ? 0 : -1;\n    }\n    int low=0, high=n-1;\n    while( low<=high ){\n\n        if (A[low] <= A[high] && ( key < A[low] || key > A[high]) ) {\n             return -1;\n        }\n\n        int mid = low + (high-low)/2;\n        if ( A[mid] == key ) return mid;\n    \n        //the target in non-rotated array\n        if (A[low] < A[mid] && key >= A[low] && key< A[mid]){\n            high = mid - 1;\n            continue;\n        }\n        //the target in non-rotated array\n        if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){\n            low = mid + 1;\n            continue;\n        }\n        //the target in rotated array\n        if (A[low] > A[mid] ){\n            high = mid - 1;\n            continue;\n        }\n        //the target in rotated array\n        if (A[mid] > A[high] ){\n            low = mid + 1;\n            continue;\n        }\n    }\n    return -1;\n}\n\nint search2(int A[], int n, int target) {\n    if (n<=0) return -1;\n\n    if (n==1){\n        return A[0]==target?0:-1;\n    }        \n\n    if ( A[0] < A[n-1] ){\n        return binary_search(A, n, target);\n    }else{\n        return rotate_search(A, 0, n-1, target);\n    }\n}\n\nint rotate_search(int A[], int low, int high, int key ) {\n    \n    if (low > high){\n        return -1;\n    }\n    if (low==high){\n        return A[low]==key?low:-1;\n    }        \n    \n    int mid = low + (high-low)/2;\n    if ( A[mid] == key ) return mid;\n\n    if (A[low] < A[mid] && key >= A[low] && key< A[mid]){\n        return binary_search(A, low, mid-1, key);\n    }\n    if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){\n        return binary_search(A, mid+1, high, key);\n    }\n    if (A[low] > A[mid] ){\n        return rotate_search(A, low, mid-1, key);\n    }\n    if (A[mid] > A[high] ){\n        return rotate_search(A, mid+1, high, key);\n    }\n    return -1;\n}\n\nint binary_search(int A[], int n, int key) {\n    int low = 0;\n    int high = n-1;\n    while (low <= high){\n        int mid = low +(high-low)/2;\n        if (A[mid] == key){\n            return mid;\n        }\n        if ( key> A[mid] ) {\n            low = mid+1;\n        }else{\n            high = mid-1;\n        }\n    }\n    return -1;\n}\n\nint binary_search(int A[], int low, int high, int key) {\n    //(low+high)/2 could encounter overflow issue\n    int mid = low+(high-low)/2;\n    if (low > high){\n        return -1;\n    }\n    if (A[mid]==key){\n        return mid;\n    }\n    if (key > A[mid]){\n        binary_search(A, mid+1, high, key);\n    }else{\n        binary_search(A, low, mid-1, key);\n    }\n\n}\n\nvoid rotate_array(int a[], int n, int pos){\n    int i, from=0;\n    pos = pos % n;\n    if (n<=0) return;\n\n    int tmp = a[0];\n    \n    for(int i=0, step=0; step<n && i<pos; step++){\n        int to;\n        if (from-pos < 0) {\n            to = n-pos+from; \n        }else{\n            to = from-pos;\n        }\n        int t ;\n        t = a[to];\n        a[to] = tmp; \n        tmp = t;\n        from = to;\n        if ( to == i ){\n            i++;\n            from++;\n            tmp = a[from];\n        }\n    }\n    \n}\n\nvoid printArray(int A[], int n) {\n    printf(\"{\");\n    for(int i=0; i<n; i++) {\n        printf(\"%d, \", A[i]);\n    }\n    printf(\"}\\n\");\n}\n\nint main(int argc, char** argv)\n{\n\n    int cnt=20;\n\n    if (argc>1) {\n        cnt = atoi(argv[1]);\n    }\n\n    srand(time(NULL)); \n\n   for(int n=0; n<=cnt; n++) {\n        printf(\"--------------------------------------\\n\");\n        int *a = new int[cnt];\n        for(int i=0; i<cnt; i++){\n            a[i]=i*2;\n        }\n        //printArray(a, cnt);\n        int rotate = random() % cnt;\n        //rotate=2;\n        //printf(\"rotate=%d\\n\", rotate);\n        rotate_array(a, cnt, rotate);\n        printArray(a, cnt);\n        int target = random() % (2*cnt);\n        //target=6;\n        printf(\"target=%d\\n\", target);\n    \n        int idx = search(a, cnt, target);\n        if ( idx<0 ){\n            printf(\"not found!\\n\");\n        }else{\n            printf(\"a[%d] = %d\\n\", idx, a[idx]); \n        }\n        \n        delete[] a;\n   }\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/searchInsertPosition/searchInsertPosition.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/search-insert-position/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given a sorted array and a target value, return the index if the target is found. \n* If not, return the index where it would be if it were inserted in order.\n* \n* You may assume no duplicates in the array.\n* \n* Here are few examples.\n* [1,3,5,6], 5 → 2\n* [1,3,5,6], 2 → 1\n* [1,3,5,6], 7 → 4\n* [1,3,5,6], 0 → 0\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n\n\nint binary_search(int A[], int n, int key) {\n    int low = 0;\n    int high = n-1;\n    while (low <= high){\n        int mid = low +(high-low)/2;\n        if (A[mid] == key){\n            return mid;\n        }\n        if ( key> A[mid] ) {\n            low = mid+1;\n        }else{\n            high = mid-1;\n        }\n    }\n    return low;\n}\nint searchInsert(int A[], int n, int target) {\n    if (n==0) return n;\n    return binary_search(A, n, target);\n}\n\nint main()\n{\n    int a[]={1,3,5,6};\n    printf(\"%d -> %d\\n\", 5, searchInsert(a, 4, 5));\n    printf(\"%d -> %d\\n\", 2, searchInsert(a, 4, 2));\n    printf(\"%d -> %d\\n\", 7, searchInsert(a, 4, 7));\n    printf(\"%d -> %d\\n\", 0, searchInsert(a, 4, 0));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/seatReservationManager/SeatReservationManager.cpp",
    "content": "// Source : https://leetcode.com/problems/seat-reservation-manager/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * Design a system that manages the reservation state of n seats that are numbered from 1 to n.\n * \n * Implement the SeatManager class:\n * \n * \tSeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from \n * 1 to n. All seats are initially available.\n * \tint reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its \n * number.\n * \tvoid unreserve(int seatNumber) Unreserves the seat with the given seatNumber.\n * \n * Example 1:\n * \n * Input\n * [\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \n * \"unreserve\"]\n * [[5], [], [], [2], [], [], [], [], [5]]\n * Output\n * [null, 1, 2, null, 2, 3, 4, 5, null]\n * \n * Explanation\n * SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\n * seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is \n * 1.\n * seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which \n * is 2.\n * seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\n * seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which \n * is 2.\n * seatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which \n * is 3.\n * seatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is \n * 4.\n * seatManager.reserve();    // The only available seat is seat 5, so return 5.\n * seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].\n * \n * Constraints:\n * \n * \t1 <= n <= 10^5\n * \t1 <= seatNumber <= n\n * \tFor each call to reserve, it is guaranteed that there will be at least one unreserved seat.\n * \tFor each call to unreserve, it is guaranteed that seatNumber will be reserved.\n * \tAt most 10^5 calls in total will be made to reserve and unreserve.\n ******************************************************************************************************/\n\nclass SeatManager {\nprivate:\n    set<int> idle;\npublic:\n    SeatManager(int n) {\n        for(int i=1; i<=n; i++) {\n            idle.insert(i);\n        }\n    }\n    \n    int reserve() {\n        auto it = idle.begin();\n        auto seat = *it;\n        idle.erase(it);\n        return seat;\n    }\n    \n    void unreserve(int seatNumber) {\n        idle.insert(seatNumber);\n    }\n};\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager* obj = new SeatManager(n);\n * int param_1 = obj->reserve();\n * obj->unreserve(seatNumber);\n */\n"
  },
  {
    "path": "algorithms/cpp/secondLargestDigitInAString/SecondLargestDigitInAString.cpp",
    "content": "// Source : https://leetcode.com/problems/second-largest-digit-in-a-string/\n// Author : Hao Chen\n// Date   : 2021-03-22\n\n/***************************************************************************************************** \n *\n * Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 \n * if it does not exist.\n * \n * An alphanumeric string is a string consisting of lowercase English letters and digits.\n * \n * Example 1:\n * \n * Input: s = \"dfa12321afd\"\n * Output: 2\n * Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\n * \n * Example 2:\n * \n * Input: s = \"abc1111\"\n * Output: -1\n * Explanation: The digits that appear in s are [1]. There is no second largest digit. \n * \n * Constraints:\n * \n * \t1 <= s.length <= 500\n * \ts consists of only lowercase English letters and/or digits.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int secondHighest(string s) {\n        int first = -1, second = -1;\n        for (auto& c : s){\n            if (c >='0' && c<='9') {\n                int n = c - '0';\n                if ( n > first) {\n                    second = first;\n                    first = n;\n                }else if (n < first && n > second) {\n                    second = n;\n                }\n            }\n        }\n        return second;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sentenceScreenFitting/main.cpp",
    "content": "//\n//  main.cpp\n//  LeeteCodeOJ#418\n//\n//  Created by Wang Yi on 25/10/16.\n//  Copyright (c) 2016 Wang Yi. All rights reserved.\n//\n\n#include <iostream>\n#include <string>\n#include <string.h>\n#include <sstream>\n#include <vector>\n#include \"sentenceScreenFitting.h\"\n#define N 100\n#define M 10\n\nusing std::vector;\n\nint main(int argc, const char * argv[]) {\n    int rows, cols, ret;\n//    int i=0;\n//    char stc[N][M];\n    vector<string> sentence;\n    std::string word;\n    std::string line;\n    std::stringstream numbers, split;\n    \n    std::getline(std::cin, line);\n    numbers << line;\n    numbers >> rows >> cols;\n    std::getline(std::cin, line);\n    split << line;\n\n    while (split >> word){\n        sentence.push_back(word);\n//        strcpy(stc[i++], word.c_str());\n    }\n    \n    Solution solution;\n    ret = solution.wordsTyping(sentence, rows, cols);\n//    ret = SentenceScreenFitting(stc, rows, cols, i);\n    std::cout << ret << std::endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp",
    "content": "//\n//  OJ#418.cpp\n//  LeeteCodeOJ#418\n//\n//  Created by Wang Yi on 25/10/16.\n//  Copyright (c) 2016 Wang Yi. All rights reserved.\n//\n\n\n/**********************************************************************************\n *  \n *  Given a rows x cols screen and a sentence represented by a list of words, find \n *  how many times the given sentence can be fitted on the screen.\n *  \n *  Note:\n *  \n *      A word cannot be split into two lines.\n *      The order of words in the sentence must remain unchanged.\n *      Two consecutive words in a line must be separated by a single space.\n *      Total words in the sentence won't exceed 100.\n *      Length of each word won't exceed 10.\n *      1 ≤ rows, cols ≤ 20,000.\n *  \n *   \n *  \n *  Example 1:\n *  \n *  Input:\n *  rows = 2, cols = 8, sentence = [\"hello\", \"world\"]\n *  \n *  Output: \n *  1\n *  \n *  Explanation:\n *  hello---\n *  world---\n *  \n *  The character '-' signifies an empty space on the screen.\n *  \n *   \n *  \n *  Example 2:\n *  \n *  Input:\n *  rows = 3, cols = 6, sentence = [\"a\", \"bcd\", \"e\"]\n *  \n *  Output: \n *  2\n *  \n *  Explanation:\n *  a-bcd- \n *  e-a---\n *  bcd-e-\n *  \n *  The character '-' signifies an empty space on the screen.\n *  \n *   \n *  \n *  Example 3:\n *  \n *  Input:\n *  rows = 4, cols = 5, sentence = [\"I\", \"had\", \"apple\", \"pie\"]\n *  \n *  Output: \n *  1\n *  \n *  Explanation:\n *  I-had\n *  apple\n *  pie-I\n *  had--\n *  \n *  The character '-' signifies an empty space on the screen.\n *  \n *  *********************************************************************************/\n\n\n#include \"sentenceScreenFitting.h\"\n#include <string.h>\n#include <iomanip>\n#include <iostream>\n#define FOR(START, END) for((START)=0;(START)<(END);(START)+=1) {\n#define END ;}\n#define N 100\n\n// first brute force solution\nint SentenceScreenFitting(char stc[][M], int row, int col, size_t l)\n{\n    int i, j, t, s, k=0, ret=0;\n    int len[N] = {0};\n    FOR(i, l) len[i] = (int)strlen(stc[i]) END\n    \n    FOR(i, row)\n    j = col;\n    t = k;\n    while (j - len[k] >= 0) {\n        j -= len[k] + 1;\n        if (k+1 > l-1){\n            FOR(s, k-t) std::cout << stc[t+s] << ' ' END;\n            std::cout << stc[t+s];\n            if (j - len[0] >= 0)\n                std::cout << ' ';\n            k = 0;\n            t = 0;\n            ret++;\n        } else{\n            k++;\n        }\n    }\n    FOR(s, k-t-1) std::cout << stc[t+s] << ' ' END;\n    if (k-t > 0)\n        std::cout << stc[t+s];\n\n    std::cout << std::setfill ('-') << std::setw(j == col ? col:j+1) << \"\" << std::endl;\n    END\n    \n    return ret;\n}\n\n/*\nint Solution::wordsTyping(vector<string>& sentence, int rows, int cols)\n{\n    int i, j, t, s, k=0, ret=0, l=(int)sentence.size();\n    int len[N] = {0};\n    FOR(i, l) len[i] = (int)sentence[i].size() END\n    \n    FOR(i, rows)\n    j = cols;\n    t = k;\n    while (j - len[k] >= 0) {\n        j -= len[k] + 1;\n        if (k+1 > l-1){\n//            FOR(s, k-t) std::cout << sentence[t+s] << ' ' END;\n//            std::cout << sentence[t+s];\n//            if (j - len[0] >= 0)\n//                std::cout << ' ';\n            k = 0;\n            t = 0;\n            ret++;\n        } else{\n            k++;\n        }\n    }\n//    FOR(s, k-t-1) std::cout << sentence[t+s] << ' ' END;\n//    if (k-t > 0)\n//        std::cout << sentence[t+s];\n//    \n//    std::cout << std::setfill ('-') << std::setw(j == cols ? cols:j+1) << \"\" << std::endl;\n    END\n    \n    return ret;\n}\n*/\n\n// second boosting\nint Solution::wordsTyping(vector<string>& sentence, int rows, int cols)\n{\n    int i, j, k=0, ret=0, l=(int)sentence.size();\n//    int t, s;\n    int jump = 0;\n    int len[N] = {0};\n    FOR(i, l) len[i] = (int)sentence[i].size();jump += len[i] END\n    jump += l;\n    \n    FOR(i, rows)\n    j = cols;\n//    t = k;\n    \n    if (k == 0){\n        ret += j / jump;\n        j = j % jump;\n    }\n    \n    while (j - len[k] >= 0) {\n        j -= len[k] + 1;\n        if (k+1 > l-1){\n            //            FOR(s, k-t) std::cout << sentence[t+s] << ' ' END;\n            //            std::cout << sentence[t+s];\n            //            if (j - len[0] >= 0)\n            //                std::cout << ' ';\n            k = 0;\n//            t = 0;\n            ret += j / jump + 1;\n            j = j % jump;\n        } else {\n            k++;\n        }\n    }\n    //    FOR(s, k-t-1) std::cout << sentence[t+s] << ' ' END;\n    //    if (k-t > 0)\n    //        std::cout << sentence[t+s];\n    //\n    //    std::cout << std::setfill ('-') << std::setw(j == cols ? cols:j+1) << \"\" << std::endl;\n    END\n    \n    return ret;\n}\n"
  },
  {
    "path": "algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.h",
    "content": "//\n//  OJ#418.h\n//  LeeteCodeOJ#418\n//\n//  Created by Wang Yi on 25/10/16.\n//  Copyright (c) 2016 Wang Yi. All rights reserved.\n//\n\n#ifndef __LeeteCodeOJ_418__OJ_418__\n#define __LeeteCodeOJ_418__OJ_418__\n\n#define M 10\n\n#include <stdio.h>\n#include <string>\n#include <vector>\n\nusing std::vector;\nusing std::string;\n\nint SentenceScreenFitting(char stc[][M], int row, int col, size_t l);\n\nclass Solution {\npublic:\n    int wordsTyping(vector<string>& sentence, int rows, int cols);\n};\n\n#endif /* defined(__LeeteCodeOJ_418__OJ_418__) */\n"
  },
  {
    "path": "algorithms/cpp/sentenceSimilarity/SentenceSimilarity.III.cpp",
    "content": "// Source : https://leetcode.com/problems/sentence-similarity-iii/\n// Author : Hao Chen\n// Date   : 2021-04-06\n\n/***************************************************************************************************** \n *\n * A sentence is a list of words that are separated by a single space with no leading or trailing \n * spaces. For example, \"Hello World\", \"HELLO\", \"hello world hello world\" are all sentences. Words \n * consist of only uppercase and lowercase English letters.\n * \n * Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence \n * (possibly empty) inside one of these sentences such that the two sentences become equal. For \n * example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by \n * inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2.\n * \n * Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. \n * Otherwise, return false.\n * \n * Example 1:\n * \n * Input: sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"\n * Output: true\n * Explanation: sentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".\n * \n * Example 2:\n * \n * Input: sentence1 = \"of\", sentence2 = \"A lot of words\"\n * Output: false\n * Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the \n * other.\n * \n * Example 3:\n * \n * Input: sentence1 = \"Eating right now\", sentence2 = \"Eating\"\n * Output: true\n * Explanation: sentence2 can be turned to sentence1 by inserting \"right now\" at the end of the \n * sentence.\n * \n * Example 4:\n * \n * Input: sentence1 = \"Luky\", sentence2 = \"Lucccky\"\n * Output: false\n * \n * Constraints:\n * \n * \t1 <= sentence1.length, sentence2.length <= 100\n * \tsentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.\n * \tThe words in sentence1 and sentence2 are separated by a single space.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    bool isWord(char ch) {\n        return (ch >='a' && ch <= 'z' ) || ( ch >='A' && ch <= 'Z');\n    }\n    bool isSpace(char ch) {\n        return (ch == ' ');\n    }\n    void split(string& s, vector<string>& words) {\n        s += ' ';\n        int start=0, end=0;\n        while(start < s.size()) {\n            while(isSpace(s[start])) start++;\n            end = start;\n            while(!isSpace(s[end])) end++;\n            words.push_back(s.substr(start, end-start));\n            start = end + 1;\n        }\n    }\n    void print(vector<string>& v) {\n        cout << \"[\";\n        for(int i=0; i<v.size()-1; i++) {\n            cout << v[i] << \", \";\n        }\n        cout << v[v.size()-1] << \"]\" << endl;\n    }\npublic:\n    bool areSentencesSimilar(string sentence1, string sentence2) {\n        string& longstr = sentence1.size() >= sentence2.size() ? sentence1 : sentence2;\n        string& shortstr = sentence1.size() < sentence2.size() ? sentence1 : sentence2;\n        if ( longstr == shortstr ) return true;\n        \n        vector<string> words1, words2;\n        split(shortstr, words1);\n        split(longstr, words2);\n        //print(words1); print(words2);\n        \n        int left=0, right=words1.size()-1;\n        while(left< words1.size() && words1[left] == words2[left]) left++;\n        \n        int delta = words2.size() - words1.size();\n        while(right>=left && words1[right] == words2[delta+right]) right--;\n        //cout << left << \":\" << right << \":\" << delta << endl;\n        \n        return left > right;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/serializeAndDeserializeBinaryTree/SerializeAndDeserializeBinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/\n// Author : Hao Chen\n// Date   : 2015-11-10\n\n/*************************************************************************************** \n *\n * Serialization is the process of converting a data structure or object into a \n * sequence of bits so that it can be stored in a file or memory buffer, or transmitted \n * across a network connection link to be reconstructed later in the same or another \n * computer environment. \n * \n * Design an algorithm to serialize and deserialize a binary tree. There is no \n * restriction on how your serialization/deserialization algorithm should work. You \n * just need to ensure that a binary tree can be serialized to a string and this string \n * can be deserialized to the original tree structure.\n * \n * For example, you may serialize the following tree\n * \n *     1\n *    / \\\n *   2   3\n *      / \\\n *     4   5\n * \n * as \"[1,2,3,null,null,4,5]\", just the same as how LeetCode OJ serializes a binary \n * tree. You do not necessarily need to follow this format, so please be creative and \n * come up with different approaches yourself.\n * \n * Note: Do not use class member/global/static variables to store states. Your \n * serialize and deserialize algorithms should be stateless.\n * \n * Credits:Special thanks to @Louis1992 for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\nusing namespace std;\n\n/**\n * Definition for a binary tree node.\n */\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\n\nclass Codec {\n    \npublic:\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        return serialize02(root);\n        return serialize01(root);\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) {\n        return deserialize02(data);\n        return deserialize01(data);\n    }      \n    \n\n/*\n * ===============================================================================\n *  Using pre-order to serialize and deserialize the tree. \n * ===============================================================================\n */\npublic:\n    // Encodes a tree to a single string.\n    string serialize01(TreeNode* root) {\n         string result;\n         vector<TreeNode*> v;\n         serializeHelper(root, v);\n         for(int i=0; i<v.size(); i++){\n             result = result + (v[i]==NULL ? \"#\" : to_string(v[i]->val)) + \" \";\n         }\n         return result;\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize01(string data) {\n        vector<TreeNode*> v;\n        split(data, ' ', v);\n\n        int index = 0;\n        return deserializeHelper(v, index);\n\n    }    \n\nprivate:\n\n    void serializeHelper(TreeNode* root, vector<TreeNode*>& v) {\n        if (root==NULL) {\n            v.push_back(NULL);\n        }else{\n            v.push_back(root);\n            serializeHelper(root->left, v);\n            serializeHelper(root->right, v);\n        }\n    }\n   \n\n    TreeNode* deserializeHelper(vector<TreeNode*> &v, int& index) {\n\n        if (index >= v.size() ) return NULL;\n\n        TreeNode* root = v[index++];\n        if (root) {\n            root->left = deserializeHelper(v, index);\n            root->right = deserializeHelper(v, index);\n        }\n        return root;\n    }\n\n\n   void split(const string &s, char delim, vector<TreeNode*> &elems) {\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            TreeNode* node =  (item==\"#\" ? NULL : new TreeNode( stoi(item)) );\n            elems.push_back(node);\n        }\n\n    }\n    \n\n/*\n * ===============================================================================\n *  Using sstream instead of vector to improve the performance\n * ===============================================================================\n */\n\npublic:\n    // Encodes a tree to a single string.\n    string serialize02(TreeNode* root) {\n        ostringstream out;\n        serialize(root, out);\n        return out.str();\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize02(string data) {\n        istringstream in(data);\n        return deserialize(in);\n    } \n    \nprivate:\n   void serialize(TreeNode* root, ostringstream& out) {\n        if (root==NULL) {\n            out << \"# \";\n            return;\n        }\n        out << root->val << \" \";\n        serialize(root->left, out);\n        serialize(root->right, out);\n    }\n\n    TreeNode* deserialize(istringstream& in) {\n        string val;\n        in >> val;\n        if (val == \"#\" || val.empty() ) return NULL;\n\n        TreeNode* node = new TreeNode(stoi(val));\n        node->left = deserialize(in);\n        node->right = deserialize(in);\n        return node;\n    }\n};\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec;\n// codec.deserialize(codec.serialize(root));\n\n\nint main(int argc, char** argv) \n{\n    string s = \"1 2 3 # # 4 5\";\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << s << endl;\n    Codec codec;\n    cout << codec.serialize(codec.deserialize(s)) << endl;\n    \n    return 0;\n    \n}\n"
  },
  {
    "path": "algorithms/cpp/setMatrixZeroes/setMatrixZeroes.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/set-matrix-zeroes/\n// Author : Hao Chen\n// Date   : 2014-06-23\n\n/********************************************************************************** \n* \n* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.\n* \n* click to show follow up.\n* \n* Follow up:\n* \n* Did you use extra space?\n* A straight forward solution using O(mn) space is probably a bad idea.\n* A simple improvement uses O(m + n) space, but still not the best solution.\n* Could you devise a constant space solution?\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n    void setZeroes(vector<vector<int> > &matrix) {\n        if(random()%2){\n            setZeroes1(matrix);\n        }\n        setZeroes2(matrix);\n    }\n    \n    void setZeroes1(vector<vector<int> > &matrix) {\n        \n        int bRow = false, bCol=false;\n        \n        for (int r=0; r<matrix.size(); r++){\n            for(int c=0; c<matrix[r].size(); c++){\n                if (matrix[r][c]==0){\n                    if (r==0) bRow = true;\n                    if (c==0) bCol = true;\n                    matrix[0][c] = matrix[r][0] = 0;\n                }\n            }\n        }\n        \n        for (int r=1; r<matrix.size(); r++){\n            for(int c=1; c<matrix[r].size(); c++){\n                if (matrix[0][c]==0 || matrix[r][0]==0) {\n                    matrix[r][c]=0;\n                }\n            }\n        }\n        if (bRow){\n            for(int c=0; c<matrix[0].size(); c++) matrix[0][c] = 0;\n        }\n        if (bCol){\n            for(int r=0; r<matrix.size(); r++) matrix[r][0] = 0;\n        }\n\n    }\n    \n    void setZeroes2(vector<vector<int> > &matrix) {\n\n        bool *row = new bool[matrix.size()]();\n        bool *col = new bool[matrix[0].size()]();\n        for (int r=0; r<matrix.size(); r++){\n            for(int c=0; c<matrix[r].size(); c++){\n                if (matrix[r][c]==0){\n                    row[r]=true;\n                    col[c]=true;\n                }\n            }\n        }\n        \n        for (int r=0; r<matrix.size(); r++){\n            for(int c=0; c<matrix[r].size(); c++){\n                if (row[r] || col[c]) {\n                    matrix[r][c]=0;\n                }\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/shortEncodingOfWords/ShortEncodingOfWords.cpp",
    "content": "// Source : https://leetcode.com/problems/short-encoding-of-words/\n// Author : Hao Chen\n// Date   : 2020-10-02\n/***************************************************************************************************** \n *\n * Given a list of words, we may encode it by writing a reference string S and a list of indexes A.\n * \n * For example, if the list of words is [\"time\", \"me\", \"bell\"], we can write it as S = \"time#bell#\" \n * and indexes = [0, 2, 5].\n * \n * Then for each index, we will recover the word by reading from the reference string from that index \n * until we reach a \"#\" character.\n * \n * What is the length of the shortest reference string S possible that encodes the given words?\n * \n * Example:\n * \n * Input: words = [\"time\", \"me\", \"bell\"]\n * Output: 10\n * Explanation: S = \"time#bell#\" and indexes = [0, 2, 5].\n * \n * Note:\n * \n * \t1 <= words.length <= 2000.\n * \t1 <= words[i].length <= 7.\n * \tEach word has only lowercase letters.\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    static bool comp(string a,string b){\n        return a.size() < b.size();\n    }\n    int minimumLengthEncoding(vector<string>& words) {\n        sort(words.begin(),words.end(),comp);\n        int ans = 0;\n        int count = 0;\n        unordered_map<string,int> M;\n        for(int i = 0 ; i < words.size() ; i++){\n            string temp = \"\";\n            for(int k = words[i].size() - 1 ; k >= 0 ; k--){\n                temp = words[i][k] + temp;\n                M[temp]++;\n            }\n        }\n        for(int i = 0 ; i < words.size() ; i++){\n            ans = ans + words[i].size();\n            count++;\n            if(M[words[i]] > 1){\n                ans = ans - words[i].size();\n                count--;\n                M[words[i]]--;\n            }\n        }\n        return ans + count;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/shortestPalindrome/ShortestPalindrome.cpp",
    "content": "// Source : https://leetcode.com/problems/shortest-palindrome/\n// Author : Hao Chen\n// Date   : 2015-06-11\n\n/********************************************************************************** \n * \n * Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. \n * Find and return the shortest palindrome you can find by performing this transformation.\n * \n * For example: \n * Given \"aacecaaa\", return \"aaacecaaa\".\n * Given \"abcd\", return \"dcbabcd\".\n * \n * Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. \n * Thanks to @Freezen for additional test cases.\n *               \n **********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\n\nbool isPalindrome(string& s, int begin, int end) {\n    for (; begin<end; begin++, end-- ) {\n        if ( s[begin] != s[end] ) {\n            return false;\n        }\n    }\n    return true;\n}\n\n// Burst Force - - Time Limit Error\nstring shortestPalindrome_bf(string& s) {\n    int len = s.size();\n    int i;\n    for (i=len-1; i>=0; i--) {\n        if (isPalindrome(s, 0, i)) { \n            i++;\n            break;\n        }\n    }\n    string t = s.substr(i, len-i);\n    reverse(t.begin(), t.end());\n    return t+s;\n}\n\n//Dynamic Programming - Memory Limit Exceeded & Time Limit Error\n//  Using the method of finding longest palindrome\nstring shortestPalindrome_dp(string& s) {\n    int len = s.size();\n    if (len <=1 ) return s;\n\n    //find longest palindrome, see \"Longest Palindromic Substring\"\n    vector< vector<bool> > dp(len, vector<bool>(len, false));\n    for (int i=len-1; i>=0; i--){\n        for(int j=i; j<len; j++){\n            if (i==j || ((j-i==1 || dp[i+1][j-1]) && s[i]==s[j]) ) {\n                dp[i][j] = true;\n            }\n        } \n    }  \n\n    /*\n     *   // only use two lines  -- still have Time Limit Error\n     *\n     *   vector< vector<bool> > dp(2, vector<bool>(len, false));\n     *   for (int i=len-1; i>=0; i--){\n     *       for(int j=i; j<len; j++){\n     *           if (i==j || ((j-i==1 || dp[(i+1)%2][j-1]) && s[i]==s[j]) ) {\n     *               dp[i%2][j] = true;\n     *           }\n     *       }\n     *   }\n     */\n    \n    //find the longest palindrome which start from first char.\n    int pos = 0;\n    for (int i=1; i<len; i++)  {\n        if (dp[0][i]) {\n            pos = i+1;\n        } \n    }\n    string t = s.substr(pos, len - pos);\n    reverse(t.begin(), t.end());\n    return t+s;\n    \n}\n\n/*\n *   The core of KMP algorithm needs to build a partial match table for pattern, \n *   which can determin how many chars need to skip if mismatch happens.\n *\n *   The best explaination of the idea of the KMP algorithm is:\n *   http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/\n *\n *   Here, we can use KMP algorithm to solve this problem.\n *\n *   1) We need construct a mirror string base on original string. and use a uniq char for seperator.\n *\n *       considering the original string is \"abab\", then the mirror string is \"abab#baba\" (# is seperator)\n *\n *   2) Build the KMP partial match table for this pattern.\n *\n *       a b a b # b a b a\n *       0 0 1 2 0 0 1 2 3\n *\n *   3) Checking the last position of partial match table, it is 3. it means:\n *\n *      For the entire pattern (mirror string), there has max 3 length of sub-string is both prefix and suffix.\n *      \n *      This sub-string is \"aba\".\n *\n *   4) The result of 3) is really useful to solve this shorest  palindrome problem.\n *\n *      Because \"aba\" is the pattern which in original string and its reversed version.\n *\n *      ( Note: The uniq char is used for making the noise, which can make sure \n *              the original string and its reversed version won't be mixed.\n *              then, the common prefix and suffix sub-string is right )\n *\n *      So, if a sub-string \"aba\" is existed in both original string and its reversed version,\n *      which means, this is the longest prefix palindrome.\n *\n *    5) Then, we can take rest suffix, and reverse it and put it in front of original string.\n *\n */\n\nstring shortestPalindrome_kmp(string& s) {  \n    int len = s.size();\n    if(len <= 1) return s;\n    \n    string pattern = s + '\\0' + string(s.rbegin(), s.rend());  \n\n    //construct the partial match table\n    vector<int> prefix( pattern.size() );  \n    prefix[0] = 0;\n    for(int i = 1; i < prefix.size(); i++) {  \n        int j = prefix[i-1];  \n        while( j > 0 && pattern[i] != pattern[j] ) {\n            j = prefix[j-1];  \n        }\n        if ( pattern[i] == pattern[j] ) {\n            j++;  \n        }\n        prefix[i] = j;  \n    }  \n\n#ifdef _DEBUG\n    cout << endl;\n    for(int i=0; i<pattern.size(); i++){\n        \n        cout << (pattern[i] ? pattern[i] : '#') << \"  \";\n    }\n    cout << endl;\n    for(int i=0; i<prefix.size(); i++) {\n        cout << prefix[i] << \"  \";\n    }\n    cout << endl;\n    cout << \"-->\" << s.substr(0, prefix.back()) << \" \" << s.substr(prefix.back()) << endl;\n#endif\n\n    int pos = s.size() - prefix.back();  \n    return string(s.rbegin(), s.rbegin() + pos) + s;  \n}  \n\n\nstring shortestPalindrome(string s) {\n    return shortestPalindrome_kmp(s); \n    return shortestPalindrome_dp(s); //Memory Limit Error\n    return shortestPalindrome_bf(s); //Time Limit Error\n}\n#define TEST(s)  cout << s << \" : \" << shortestPalindrome(s) << endl\n\nint main(int argc, char**argv)\n{\n    string s = \"aabba\";\n    if (argc>1){\n        s = argv[1];\n    }\n    TEST(s);\n    TEST(\"a\");\n    TEST(\"ab\");\n    TEST(\"aba\");\n    TEST(\"abab\");\n    TEST(\"aabb\");\n    TEST(\"aacecaaa\");\n    TEST(\"abcd\");\n    TEST(\"aaabcb\");\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/shuffleAnArray/ShuffleAnArray.cpp",
    "content": "// Source : https://leetcode.com/problems/shuffle-an-array/\n// Author : Hao Chen\n// Date   : 2016-08-24\n\n/*************************************************************************************** \n *\n * Shuffle a set of numbers without duplicates.\n * \n * Example:\n * \n * // Init an array with set 1, 2, and 3.\n * int[] nums = {1,2,3};\n * Solution solution = new Solution(nums);\n * \n * // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must \n * equally likely to be returned.\n * solution.shuffle();\n * \n * // Resets the array back to its original configuration [1,2,3].\n * solution.reset();\n * \n * // Returns the random shuffling of array [1,2,3].\n * solution.shuffle();\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    Solution(vector<int> nums) : _nums(nums), _solution(nums) {\n        srand(time(NULL));\n    }\n    \n    /** Resets the array to its original configuration and return it. */\n    vector<int> reset() {\n        return _solution = _nums;\n    }\n    \n    /** Returns a random shuffling of the array. */\n    vector<int> shuffle() {\n        //Fisher Yates\n        //https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n        \n        int i = _solution.size();\n        \n        while ( --i > 0 ) {\n            int j = rand() % (i+1);\n            swap(_solution[i], _solution[j]);\n        }\n        return _solution;\n    }\nprivate:\n    vector<int> _nums, _solution;\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(nums);\n * vector<int> param_1 = obj.reset();\n * vector<int> param_2 = obj.shuffle();\n */\n"
  },
  {
    "path": "algorithms/cpp/shuffleString/ShuffleString.cpp",
    "content": "// Source : https://leetcode.com/problems/shuffle-string/submissions/\n// Author : Hao Chen\n// Date   : 2021-03-29\n\n/***************************************************************************************************** \n *\n * Given a string s and an integer array indices of the same length.\n * \n * The string s will be shuffled such that the character at the i^th position moves to indices[i] in \n * the shuffled string.\n * \n * Return the shuffled string.\n * \n * Example 1:\n * \n * Input: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\n * Output: \"leetcode\"\n * Explanation: As shown, \"codeleet\" becomes \"leetcode\" after shuffling.\n * \n * Example 2:\n * \n * Input: s = \"abc\", indices = [0,1,2]\n * Output: \"abc\"\n * Explanation: After shuffling, each character remains in its position.\n * \n * Example 3:\n * \n * Input: s = \"aiohn\", indices = [3,1,4,2,0]\n * Output: \"nihao\"\n * \n * Example 4:\n * \n * Input: s = \"aaiougrt\", indices = [4,0,2,6,7,3,1,5]\n * Output: \"arigatou\"\n * \n * Example 5:\n * \n * Input: s = \"art\", indices = [1,0,2]\n * Output: \"rat\"\n * \n * Constraints:\n * \n * \ts.length == indices.length == n\n * \t1 <= n <= 100\n * \ts contains only lower-case English letters.\n * \t0 <= indices[i] < n\n * \tAll values of indices are unique (i.e. indices is a permutation of the integers from 0 to n \n * - 1).\n ******************************************************************************************************/\n\nclass Solution {\npublic:    \n    string restoreString(string s, vector<int>& indices) {\n        string result(s.size(), ' ');\n        for (int i = 0; i < indices.size(); i++) {\n            result[indices[i]] = s[i];\n        }\n        return result;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/shuffleTheArray/ShuffleTheArray.cpp",
    "content": "// Source : https://leetcode.com/problems/shuffle-the-array/\n// Author : Hao Chen\n// Date   : 2020-10-02\n\n/***************************************************************************************************** \n *\n * Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\n * \n * Return the array in the form [x1,y1,x2,y2,...,xn,yn].\n * \n * Example 1:\n * \n * Input: nums = [2,5,1,3,4,7], n = 3\n * Output: [2,3,5,4,1,7] \n * Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\n * \n * Example 2:\n * \n * Input: nums = [1,2,3,4,4,3,2,1], n = 4\n * Output: [1,4,2,3,3,2,4,1]\n * \n * Example 3:\n * \n * Input: nums = [1,1,2,2], n = 2\n * Output: [1,2,1,2]\n * \n * Constraints:\n * \n * \t1 <= n <= 500\n * \tnums.length == 2n\n * \t1 <= nums[i] <= 10^3\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> shuffle(vector<int>& nums, int n) {\n        vector<int> result;\n        for (int i=0; i<n; i++) {\n            result.push_back(nums[i]);\n            result.push_back(nums[i+n]);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp",
    "content": "// Source : https://leetcode.com/problems/sign-of-the-product-of-an-array/\n// Author : Hao Chen\n// Date   : 2021-04-11\n\n/***************************************************************************************************** \n *\n * There is a function signFunc(x) that returns:\n * \n * \t1 if x is positive.\n * \t-1 if x is negative.\n * \t0 if x is equal to 0.\n * \n * You are given an integer array nums. Let product be the product of all values in the array nums.\n * \n * Return signFunc(product).\n * \n * Example 1:\n * \n * Input: nums = [-1,-2,-3,-4,3,2,1]\n * Output: 1\n * Explanation: The product of all values in the array is 144, and signFunc(144) = 1\n * \n * Example 2:\n * \n * Input: nums = [1,5,0,2,-3]\n * Output: 0\n * Explanation: The product of all values in the array is 0, and signFunc(0) = 0\n * \n * Example 3:\n * \n * Input: nums = [-1,1,-1,1,-1]\n * Output: -1\n * Explanation: The product of all values in the array is -1, and signFunc(-1) = -1\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 1000\n * \t-100 <= nums[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int arraySign(vector<int>& nums) {\n        int negtive=0;\n        for(auto& n : nums) {\n            if (n==0) return 0;\n            if (n < 0) negtive++;\n        }\n        return negtive % 2 == 0 ? 1 : -1;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/simplifyPath/simplifyPath.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/simplify-path/\n// Author : Hao Chen\n// Date   : 2014-10-09\n\n/********************************************************************************** \n* \n* Given an absolute path for a file (Unix-style), simplify it.\n* \n* For example,\n* path = \"/home/\", => \"/home\"\n* path = \"/a/./b/../../c/\", => \"/c\"\n* \n* \n* Corner Cases:\n* \n* Did you consider the case where path = \"/../\"?\n* In this case, you should return \"/\".\n* Another corner case is the path might contain multiple slashes '/' together, such as \"/home//foo/\".\n* In this case, you should ignore redundant slashes and return \"/home/foo\".\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <sstream>\nusing namespace std;\n\n\nvector<string> &split(const string &s, char delim, vector<string> &elems) {\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        elems.push_back(item);\n    }\n    return elems;\n}\n\n\nvector<string> split(const string &s, char delim) {\n    vector<string> elems;\n    split(s, delim, elems);\n    return elems;\n}\n\n\nstring simplifyPath(string path) {\n\n    string result;\n    vector<string> elems = split(path, '/'); \n   \n    int ignor = 0;\n    for(int i=elems.size()-1; i>=0; i--) {\n         \n        if (elems[i]==\"\" || elems[i]==\".\" ){\n            continue;\n        }\n        if (elems[i]==\"..\"){\n            ignor++;\n            continue;\n        }\n        if (ignor>0){\n            ignor--;\n            continue;\n        }\n        if (result.size()==0){\n            result = \"/\" + elems[i];\n        }else{ \n            result = \"/\" + elems[i] + result;\n        }\n    }\n\n    return  result.size() ? result : \"/\";\n        \n}\n\nint main(int argc, char** argv)\n{\n    string path(\"/a/./b/../../c/\");\n    if (argc > 1 ){\n        path = argv[1];\n    }\n\n    cout << path << \" : \" << simplifyPath(path) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/singleNumber/singleNumber.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/single-number-ii/\n// Author : Hao Chen\n// Date   : 2014-06-17\n\n/********************************************************************************** \n* \n* Given an array of integers, every element appears three times except for one. Find that single one.\n* \n* Note:\n* Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    Solution(){\n        srand(time(0));\n    }\n    \n    //random invoker\n    int singleNumber(int A[], int n) {\n        if (rand()%2){\n            return singleNumber_1(A, n);\n        }\n        return singleNumber_2(A, n);\n    }\n\n    /*\n     *  This solution is clear & straightforward implementation.\n     *  \n     *  We use an array of 32 length(e.g. count[32]) to count the the bits for all of numbers. \n     *\n     *  Because the same number appear 3 times, which means the sum of i-th bits for all numbers should be 3 times.\n     *\n     *  In other word, the sum of the i-th bits mod 3, it must be 0 or 1. 1 means that is the single number bit.\n     *\n     * This solution can be easy to extend to \"every element appears k times except for one.\"\n     *\n     */\n    int singleNumber_1(int A[], int n) {\n        int count[32] = {0};\n        int result = 0;\n        for (int i = 0; i < 32; i++) {\n            for (int j = 0; j < n; j++) {\n                if ((A[j] >> i) & 1) {\n                    count[i]++;\n                }\n            }\n            result |= ((count[i] % 3) << i);\n        }\n        return result;\n    }\n\n\n    /*\n     *   The following solution is popular solution on Internet, but it looks it's not easy to understand.\n     *\n     *   Actually, it just optimizes the above soultion.\n     *\n     *   Let's see how it improve the above.\n     *\n     *   We use three bitmasks, \n     *    1) `ones`     as a bitmask which represents the i-th bit had appeared once.\n     *    2) `twos`     as a bitmask which represents the i-th bit had appeared twice.\n     *    3) `threes`   as a bit mask which represents the i-th bit had appeared three times.\n     *\n     *    When the i-th bit had appeared for the third time, clear the i-th bit of both `ones` and `twos` to 0.\n     *    The final answer will be the value of `ones`\n     *\n     */\n    int singleNumber_2(int A[], int n) {\n        int ones = 0, twos = 0, threes = 0;\n        for (int i = 0; i < n; i++) {\n            // `ones & A[i]` the result is the bitmask which the bits appeared twice\n            twos |= ones & A[i]; \n            // XOR means remove the bit which appeared twice int `ones` \n            ones ^= A[i];\n            // count the `three`\n            threes = ones & twos;\n            // clear the `ones` and `twos` if the i-th bit had appeared three times.\n            ones &= ~threes;\n            twos &= ~threes;\n        }\n        return ones;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/singleNumber/singleNumber.III.cpp",
    "content": "// Source : https://leetcode.com/problems/single-number-iii/\n// Author : Hao Chen\n// Date   : 2016-01-16\n\n/*************************************************************************************** \n *\n * Given an array of numbers nums, in which exactly two elements appear only once and \n * all the other elements appear exactly twice. Find the two elements that appear only \n * once.\n * \n * For example:\n * \n * Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].\n * \n * Note:\n * \n * The order of the result is not important. So in the above example, [5, 3] is also \n * correct.\n * Your algorithm should run in linear runtime complexity. Could you implement it using \n * only constant space complexity?\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n ***************************************************************************************/\n\n\n/*\n * For the problem - only one number appears once when all other numbers appears exactly twice.\n * \n * We know, we can XOR all of the array elements. Since X^X is zero, and X^0 is X, \n * so all of the duplicated number will zero themselves out, and the only number would be the result.\n * \n * However, this solution cannot be applied directly to finding two numbers that appear once each. \n * \n * Suppose that these numbers that appear once are X and Y, and all other numbers appear twice. \n * If we decide to XOR all the array's elements, the overall result would actually be `X^Y`. \n * \n * Unfortunately, there is no way to extract J and K out of their XOR. \n * \n * But since X and Y are different, we are sure that X^Y is different than zero. \n * \n * This information is valuable in sense that we know pieces of information that differ.\n * If we pick up any bit that is 1 in X XOR Y, we can use it as a mask to test each element of the array. \n * \n * Obviously, that mask will be the discriminator between X and Y - \n * \n *    Only one of them will have value 1 at that particular position.\n *         \n *         \n * Now that we have the mask with exactly one bit set to 1, we can walk through the array once again. \n * \n * But this time we are going to maintain two XORed results. \n * \n *   - One for numbers that have bit 1 at the mask's position \n *   - Another for numbers that have bit 0 at that position\n *   \n * In this way, we are sure that all duplicates will go into the same pile. \n * \n * But likewise, we are sure that X and Y will go into separate piles. \n * \n * So, the overall result is that \n *  - the first XORed result will be equal to X \n *  - and the second XORed result will be equal to Y\n *  \n*/\n\nclass Solution {\npublic:\n    vector<int> singleNumber(vector<int>& nums) {\n        int allxor = 0;\n        for (int n : nums) {\n            allxor ^= n;\n        }\n        int mask = 1;\n        while ( (mask & allxor) == 0 ) {\n            mask <<= 1;\n        }\n\n        int zero = 0;\n        int one = 0;\n        for (int n : nums) {\n            if (n & mask ){\n                one ^= n;\n            }else {\n                zero ^= n;\n            }\n        }\n        \n        vector<int> result;\n        result.push_back(zero);\n        result.push_back(one);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/singleNumber/singleNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/single-number/\n// Author : Hao Chen\n// Date   : 2014-06-17\n\n/********************************************************************************** \n* \n* Given an array of integers, every element appears twice except for one. Find that single one.\n* \n* Note:\n* Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n// This is classical interview question\n// As we know, the same number XOR together will be 0,\n// So, XOR all of numbers, the result is the number which only appears once. \nint singleNumber(int A[], int n) {\n    int s = 0;\n    for(int i=0; i<n; i++){\n        s = s^A[i];\n    }\n    return s;\n}\n\nint main()\n{\n    int a[]={1,1,2,2,3};\n    printf(\"%d\\n\", singleNumber(a,5));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/singleThreadedCpu/SingleThreadedCpu.cpp",
    "content": "// Source : https://leetcode.com/problems/single-threaded-cpu/\n// Author : Hao Chen\n// Date   : 2021-04-20\n\n/***************************************************************************************************** \n *\n * You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where \n * tasks[i] = [enqueueTimei, processingTimei] means that the i^​​​​​​th​​​​ task will be available to \n * process at enqueueTimei and will take processingTimei to finish processing.\n * \n * You have a single-threaded CPU that can process at most one task at a time and will act in the \n * following way:\n * \n * \tIf the CPU is idle and there are no available tasks to process, the CPU remains idle.\n * \tIf the CPU is idle and there are available tasks, the CPU will choose the one with the \n * shortest processing time. If multiple tasks have the same shortest processing time, it will choose \n * the task with the smallest index.\n * \tOnce a task is started, the CPU will process the entire task without stopping.\n * \tThe CPU can finish a task then start a new one instantly.\n * \n * Return the order in which the CPU will process the tasks.\n * \n * Example 1:\n * \n * Input: tasks = [[1,2],[2,4],[3,2],[4,1]]\n * Output: [0,2,3,1]\n * Explanation: The events go as follows: \n * - At time = 1, task 0 is available to process. Available tasks = {0}.\n * - Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n * - At time = 2, task 1 is available to process. Available tasks = {1}.\n * - At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n * - Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. \n * Available tasks = {1}.\n * - At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n * - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. \n * Available tasks = {1}.\n * - At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n * - At time = 10, the CPU finishes task 1 and becomes idle.\n * \n * Example 2:\n * \n * Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\n * Output: [4,3,2,0,1]\n * Explanation: The events go as follows:\n * - At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n * - Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n * - At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n * - At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n * - At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n * - At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n * - At time = 40, the CPU finishes task 1 and becomes idle.\n * \n * Constraints:\n * \n * \ttasks.length == n\n * \t1 <= n <= 10^5\n * \t1 <= enqueueTimei, processingTimei <= 10^9\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    template<typename T>\n    void print(T q) { \n        while(!q.empty()) {\n            auto t = q.top();\n            cout << t[2]<< \"[\" << t[0] <<\",\"<< t[1] << \"] \";\n            q.pop();\n        }\n        std::cout << '\\n';\n    }\npublic:\n    vector<int> getOrder(vector<vector<int>>& tasks) {\n        // push the index into each task.\n        // [enQueueTime, ProcessingTime, index]\n        for(int i=0; i<tasks.size(); i++){\n            tasks[i].push_back(i); \n        }\n        \n        //Sort the tasks by enQueueTtime\n        sort(tasks.begin(), tasks.end(), [&](vector<int>& lhs, vector<int>& rhs) {\n            return lhs[0] < rhs[0];\n        });\n        \n        //Sort function for tasks priority queue.\n        auto comp = [&](vector<int>& lhs, vector<int>& rhs){\n            // if the processing time is same ,get the smaller index\n            if (lhs[1] == rhs[1]) return lhs[2] > rhs[2]; \n            // choosing the shorter processing time.\n            return lhs[1] > rhs[1];\n        };\n\n        priority_queue<vector<int>, std::vector<vector<int>>, decltype(comp)> q (comp);\n        vector<int> result;\n        \n        int i = 0;\n        while (i < tasks.size()) {\n            long time = tasks[i][0];\n            int start = i;\n            for (;i < tasks.size() && tasks[start][0] == tasks[i][0];i++ ) {\n                q.push(tasks[i]);\n            }\n            //print(q);\n           \n            while(!q.empty()){\n                //processing the task\n                auto t = q.top(); q.pop();\n                //cout << \"DEQUEUE: \" <<  t[2] << \":[\" << t[0] <<\",\"<< t[1] << \"]\"<< endl;\n                result.push_back(t[2]);\n                \n                //enQueue the tasks when CPU proceing the current task\n                time += t[1];\n                for(;i < tasks.size() && tasks[i][0] <= time; i++) {\n                    //cout << \"ENQUEUE: \" <<  tasks[i][2] << \":[\" << tasks[i][0] <<\",\"<< tasks[i][1] << \"]\"<< endl;\n                    q.push(tasks[i]);\n                }\n                //print(q);\n                //cout << endl;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/slidingWindowMaximum/SlidingWindowMaximum.cpp",
    "content": "// Source : https://leetcode.com/problems/sliding-window-maximum/\n// Author : Hao Chen\n// Date   : 2015-07-19\n\n/********************************************************************************** \n * \n * Given an array nums, there is a sliding window of size k which is moving from the \n * very left of the array to the very right. You can only see the k numbers in the \n * window. Each time the sliding window moves right by one position.\n * \n * For example,\n * Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.\n *\n * Window position                Max\n * ---------------               -----\n * [1  3  -1] -3  5  3  6  7       3\n *  1 [3  -1  -3] 5  3  6  7       3\n *  1  3 [-1  -3  5] 3  6  7       5\n *  1  3  -1 [-3  5  3] 6  7       5\n *  1  3  -1  -3 [5  3  6] 7       6\n *  1  3  -1  -3  5 [3  6  7]      7\n * \n * Therefore, return the max sliding window as [3,3,5,5,6,7].\n * \n * Note: \n * You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty \n * array.\n * \n * Follow up:\n * Could you solve it in linear time?\n * \n *   How about using a data structure such as deque (double-ended queue)?\n *   The queue size need not be the same as the window’s size.\n *   Remove redundant elements and the queue should store only elements that need to be \n * considered.\n * \n **********************************************************************************/\n#include <iostream>\n#include <vector>\n#include <deque>\n#include <set>\nusing namespace std;\n\n//O(nlog(k)\nvector<int> maxSlidingWindow02(vector<int>& nums, int k) {\n    vector<int> result;\n\n    //using multiset for collecting the window data (O(nlog(k) time complexity)\n    multiset<int> w;\n\n    for(int i=0; i<nums.size(); i++) {\n        //remove the left item which leaves window \n        if (i >= k) {\n            w.erase(w.find(nums[i-k]));\n        }\n        //insert the right itme which enter the window\n        w.insert(nums[i]);\n        if (i>=k-1) {\n            result.push_back(*w.rbegin());\n        }\n    }\n\n    return result;\n}\n\n//O(n)\nvector<int> maxSlidingWindow01(vector<int>& nums, int k) {\n    vector<int> result;\n\n    //using multiset for collecting the window data (O(nlog(k) time complexity)\n    deque<int> q;\n\n    for(int i=0; i<nums.size(); i++) {\n        //remove the left item which leaves window \n        if (!q.empty() && q.front() == i - k) {\n            q.pop_front();\n        }\n        //remove all num which less than current number from the back one by one\n        while (!q.empty() && nums[q.back()] < nums[i]) {\n            q.pop_back();\n        }\n        //insert the right itme which enter the window\n        q.push_back(i);\n        if (i>=k-1) {\n            result.push_back(nums[q.front()]);\n        }\n    }\n\n    return result;\n}\n\nvector<int> maxSlidingWindow(vector<int>& nums, int k) {\n    return maxSlidingWindow01(nums, k);\n    return maxSlidingWindow02(nums, k);\n}\n\nvoid printVector( vector<int>& v ) {\n    cout << \"{ \";\n    for(int i=0; i<v.size(); i++) {\n        cout << v[i] << (i==v.size() ? \" \": \", \");\n    }\n    cout << \"}\" << endl;\n}\n\nint main(int argc, char** argv) \n{\n    int a[] = {1,3,-1,-3,5,3,6,7};\n    int k = 3;\n    vector<int> nums(a, a+sizeof(a)/sizeof(a[0]));\n    printVector(nums);\n    vector<int> result = maxSlidingWindow(nums, k);\n    printVector(result);\n}\n"
  },
  {
    "path": "algorithms/cpp/smallestStringStartingFromLeaf/SmallestStringStartingFromLeaf.cpp",
    "content": "// Source : https://leetcode.com/problems/smallest-string-starting-from-leaf/\n// Author : Hao Chen\n// Date   : 2019-02-05\n\n/***************************************************************************************************** \n *\n * Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to \n * 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.\n * \n * Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\n * \n * (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, \"ab\" is \n * lexicographically smaller than \"aba\".  A leaf of a node is a node that has no children.)\n * \n * Example 1:\n * \n * Input: [0,1,2,3,4,3,4]\n * Output: \"dba\"\n * \n * Example 2:\n * \n * Input: [25,1,3,1,3,0,2]\n * Output: \"adz\"\n * \n * Example 3:\n * \n * Input: [2,2,1,null,1,0,null,0]\n * Output: \"abc\"\n * \n * Note:\n * \n * \tThe number of nodes in the given tree will be between 1 and 1000.\n * \tEach node in the tree will have a value between 0 and 25.\n * \n ******************************************************************************************************/\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    string smallestFromLeaf(TreeNode* root) {\n        string str, result=\"{\"; //'z'+1;\n        smallestFromLeafHelper(root, str, result);\n        return result;\n    }\n    \n    void smallestFromLeafHelper(TreeNode* root, string str, string& result) {\n        if (root->left == NULL && root->right == NULL) {\n            str.insert(0, 1, char(root->val+'a'));\n            result = min(result, str);\n            return;\n        }\n        \n        str.insert(0, 1, char(root->val+'a'));\n        \n        if (root->left) {\n            smallestFromLeafHelper(root->left, str, result);\n        }\n        if (root->right) {\n            smallestFromLeafHelper(root->right, str, result);\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sortArrayByParity/SortArrayByParity.II.cpp",
    "content": "// Source : https://leetcode.com/problems/sort-array-by-parity-ii/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * Given an array A of non-negative integers, half of the integers in A are odd, and half of the \n * integers are even.\n * \n * Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.\n * \n * You may return any answer array that satisfies this condition.\n * \n * Example 1:\n * \n * Input: [4,2,5,7]\n * Output: [4,5,2,7]\n * Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n * \n * Note:\n * \n * \t2 <= A.length <= 20000\n * \tA.length % 2 == 0\n * \t0 <= A[i] <= 1000\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool isEven(int &x) {\n        return x % 2 == 0;\n    }\n    vector<int> sortArrayByParityII(vector<int>& A) {\n        //two pointer, `even` and `odd`,\n        //  - `even` pointer step into even position\n        //  - `odd` pointer step into odd position.\n        // if `even` points to odd number, and `odd` points to even number switch them.\n        int even = 0;\n        int odd = 1;\n        while(even < A.size() && odd < A.size() ) {\n            if ( !isEven(A[even]) && isEven(A[odd]) ) swap( A[even], A[odd] );\n            if ( isEven(A[even]) ) even += 2;\n            if ( !isEven(A[odd]) ) odd += 2;\n        }\n        return A;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sortArrayByParity/SortArrayByParity.cpp",
    "content": "// Source : https://leetcode.com/problems/sort-array-by-parity/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * Given an array A of non-negative integers, return an array consisting of all the even elements of \n * A, followed by all the odd elements of A.\n * \n * You may return any answer array that satisfies this condition.\n * \n * Example 1:\n * \n * Input: [3,1,2,4]\n * Output: [2,4,3,1]\n * The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n * \n * Note:\n * \n * \t1 <= A.length <= 5000\n * \t0 <= A[i] <= 5000\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    bool isEven(int& x) {\n        return x % 2 == 0;\n    }\n    vector<int> sortArrayByParity(vector<int>& A) {\n        //two pointer, one from left to right, another from right to left\n        // if left is odd number and right is even number, switch them\n        int l=0, r=A.size()-1;\n        while ( l < r ) {\n            if ( !isEven(A[l]) && isEven(A[r]) ) swap(A[l], A[r]);\n            if ( isEven(A[l]) ) l++;\n            if ( !isEven(A[r]) ) r--;\n        }\n        return A;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sortColors/sortColors.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/sort-colors/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Given an array with n objects colored red, white or blue, sort them so that objects of \n* the same color are adjacent, with the colors in the order red, white and blue.\n* \n* Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n* \n* Note:\n* You are not suppose to use the library's sort function for this problem.\n* \n* Follow up:\n*  > A rather straight forward solution is a two-pass algorithm using counting sort.\n*  > First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array \n*    with total number of 0's, then 1's and followed by 2's.\n*  > Could you come up with an one-pass algorithm using only constant space?\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n\nvoid swap(int*a, int*b)\n{\n    int t;\n    t=*a;\n    *a = *b;\n    *b = t;\n}\nvoid sortColors(int a[], int n) {\n    int zero=0, two=n-1;\n    for(int i=0; i<=two; i++ ){\n        if (a[i]==0){\n            swap(&a[zero], &a[i]);\n            zero++;\n        }\n        if (a[i]==2){\n            swap(&a[two], &a[i]);\n            two--; \n            i--;\n        }\n    }\n    \n}\n\nvoid printArray(int a[], int n) {\n    for(int i=0; i<n; i++){\n        printf(\"%d \", a[i]);\n    }\n    printf(\"\\n\");\n}\n\nint main(int argc, char** argv)\n{\n    int n = 7;\n    if (argc>1)\n        n = atoi(argv[1]);\n\n    srand(time(NULL));\n\n    int *a = new int[n];\n    for (int i=0; i<n; i++){\n        a[i] = random()%3;\n    }\n    printArray(a, n);\n    sortColors(a, n);\n    printArray(a, n);\n\n    delete[] a;\n}\n\n"
  },
  {
    "path": "algorithms/cpp/sortList/sortList.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/sort-list/\n// Author : Hao Chen\n// Date   : 2014-07-06\n\n/********************************************************************************** \n* \n* Sort a linked list in O(n log n) time using constant space complexity.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n\nListNode *mergeTwoLists(ListNode* head1, ListNode* head2);\n\nListNode *sortList(ListNode *head) {\n    if (head==NULL || head->next == NULL){\n        return head;\n    }\n    //find the middle place\n    ListNode *p1=head, *p2=head->next; \n\n    while(p2 && p2->next){\n        p1 = p1->next;\n        p2 = p2->next->next;\n    }\n    p2 = p1->next;\n    p1->next = NULL;\n    return mergeTwoLists(sortList(head), sortList(p2));\n}\n\n\nListNode *mergeTwoLists(ListNode* head1, ListNode* head2){\n    ListNode *p1 = head1,  *p2=head2;\n    static ListNode dummy(0);\n\n    ListNode *tail = &dummy;\n\n    while(p1 && p2){\n        if(p1->val < p2->val){\n            tail->next = p1;\n            p1 = p1->next;\n        }else{\n            tail->next = p2;\n            p2 = p2->next;\n        }\n        tail = tail->next;\n    }\n    if (p1) tail->next = p1;\n    if (p2) tail->next = p2;\n\n    return dummy.next;\n}\n\nvoid printList(ListNode* h)\n{\n    while(h!=NULL){\n        printf(\"%d \", h->val);\n        h = h->next;\n    }\n    printf(\"\\n\");\n}\n\nListNode* createList(int a[], int n)\n{\n    ListNode *head=NULL, *p=NULL;\n    for(int i=0; i<n; i++){\n        if (head == NULL){\n            head = p = new ListNode(a[i]);\n        }else{\n            p->next = new ListNode(a[i]);\n            p = p->next;\n        }\n    }\n    return head;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n = 10;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    srand(time(NULL));\n\n    int *a = new int[n];\n    for(int i=0; i<n; i++){\n        a[i] = random()%n + 1;\n    }\n\n    ListNode *p = createList(a, n);\n    printList(p);\n    printList(sortList(p));\n\n    delete[] a;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/sortingTheSentence/SortingTheSentence.cpp",
    "content": "// Source : https://leetcode.com/problems/sorting-the-sentence/\n// Author : Hao Chen\n// Date   : 2021-05-22\n\n/***************************************************************************************************** \n *\n * A sentence is a list of words that are separated by a single space with no leading or trailing \n * spaces. Each word consists of lowercase and uppercase English letters.\n * \n * A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging \n * the words in the sentence.\n * \n * \tFor example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" \n * or \"is2 sentence4 This1 a3\".\n * \n * Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original \n * sentence.\n * \n * Example 1:\n * \n * Input: s = \"is2 sentence4 This1 a3\"\n * Output: \"This is a sentence\"\n * Explanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove \n * the numbers.\n * \n * Example 2:\n * \n * Input: s = \"Myself2 Me1 I4 and3\"\n * Output: \"Me Myself and I\"\n * Explanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the \n * numbers.\n * \n * Constraints:\n * \n * \t2 <= s.length <= 200\n * \ts consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.\n * \tThe number of words in s is between 1 and 9.\n * \tThe words in s are separated by a single space.\n * \ts contains no leading or trailing spaces.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string sortSentence(string s) {\n        const int MAX_WORDS = 9;\n        string ss[MAX_WORDS];\n        string word;\n        for(int i=0; i<s.size(); i++){\n            char ch = s[i];\n            \n            if (ch >='0' && ch <='9'){\n                ss[ch-'0'-1] = word;\n                word = \"\";\n            }else if (ch != ' ') {\n                word += ch;\n            }\n        }\n        \n        for(int i=1; i < MAX_WORDS; i++){\n            if (ss[i].size() <= 0 ) continue;\n            ss[0] = ss[0] +\" \" + ss[i];\n        }\n        return ss[0];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/spiralMatrix/spiralMatrix.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/spiral-matrix-ii/\n// Author : Hao Chen\n// Date   : 2014-06-30\n\n/********************************************************************************** \n* \n* Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.\n* \n* For example,\n* Given n = 3,\n* \n* You should return the following matrix:\n* \n* [\n*  [ 1, 2, 3 ],\n*  [ 8, 9, 4 ],\n*  [ 7, 6, 5 ]\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector<vector<int> > generateMatrix(int n, int m);\n\nvector<vector<int> > generateMatrix(int n) {\n    return generateMatrix(n, n);\n}\n\nvector<vector<int> > generateMatrix(int n, int m) {\n    vector< vector <int> > matrix(n);\n    if (n<=0) return matrix;\n    for(int i=0; i<n; i++){\n        vector<int> v(m);\n        matrix[i] = v;\n    }\n\n    int row=n, col=m;\n    int r, c;\n    int cnt=1;\n    for (r=0, c=0; r<(row+1)/2 && c<(col+1)/2; r++, c++){\n        //top\n        for(int i=c; i<col-c; i++){\n            matrix[r][i] = cnt++;\n        }\n        //right\n        for(int i=r+1; i<row-r; i++){\n            matrix[i][col-c-1] = cnt++;\n        }\n        //bottom\n        for(int i=col-c-2; row-r-1>r && i>=c; i--){\n            matrix[row-r-1][i] = cnt++;\n        }\n        //left\n        for(int i=row-r-2; col-c-1>c && i>r; i--){\n            matrix[i][c] = cnt++;\n        }\n        \n    }\n    return matrix;\n}\n\n\nvoid printArray(vector<int> v)\n{\n    cout << \"[\";\n    for(int j=0; j<v.size(); j++) {\n        printf(\" %02d\", v[j]);\n    }\n    cout << \"]\" << endl;;\n}\n\nvoid printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        printArray(vv[i]);\n    }\n    cout << endl;\n}\n\n\nint main(int argc, char** argv)\n{\n    int n=3, m=3;\n    if (argc>1){\n        m = n = atoi(argv[1]);\n    }\n    if (argc>2){\n        m = atoi(argv[2]);\n    }\n    vector< vector<int> > matrix = generateMatrix(n, m);\n    printMatrix(matrix);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/spiralMatrix/spiralMatrix.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/spiral-matrix/\n// Author : Hao Chen\n// Date   : 2014-06-30\n\n/********************************************************************************** \n* \n* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\n* \n* For example,\n* Given the following matrix:\n* \n* [\n*  [ 1, 2, 3 ],\n*  [ 4, 5, 6 ],\n*  [ 7, 8, 9 ]\n* ]\n* \n* You should return [1,2,3,6,9,8,7,4,5].\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector<int> spiralOrder(vector<vector<int> > &matrix) {\n    vector <int> v;\n    int row = matrix.size();\n    if (row<=0) return v;\n    int col = matrix[0].size();\n    if (col<=0) return v;\n    int r, c;\n    for (r=0, c=0; r<(row+1)/2 && c<(col+1)/2; r++, c++){\n        //top\n        for(int i=c; i<col-c; i++){\n            v.push_back(matrix[r][i]);\n        }\n        //right\n        for(int i=r+1; i<row-r; i++){\n            v.push_back(matrix[i][col-c-1]);\n        }\n        //bottom\n        for(int i=col-c-2; row-r-1>r && i>=c; i--){\n            v.push_back(matrix[row-r-1][i]);\n        }\n        //left\n        for(int i=row-r-2; col-c-1>c && i>r; i--){\n            v.push_back(matrix[i][c]);\n        }\n        \n    }\n    return v;\n}\n\n\nvoid printArray(vector<int> v)\n{\n    cout << \"[\";\n    for(int j=0; j<v.size(); j++) {\n        printf(\" %02d\", v[j]);\n    }\n    cout << \"]\" << endl;;\n}\n\nvoid printMatrix(vector< vector<int> > &vv)\n{\n    for(int i=0; i<vv.size(); i++) {\n        printArray(vv[i]);\n    }\n    cout << endl;\n}\n\nvector< vector<int> > createMatrix(int n, int m)\n{\n    vector< vector<int> > vv;\n    int cnt = 1;\n    for(int i=0; i<n; i++){\n        vector<int> v;\n        for(int j=0; j<m; j++){\n            v.push_back(cnt++);\n        }\n        vv.push_back(v);\n    }\n    return vv;\n}\n\nint main(int argc, char** argv)\n{\n    int n=3, m=3;\n    if (argc>2){\n        n = atoi(argv[1]);\n        m = atoi(argv[2]);\n    }\n    vector< vector<int> > matrix = createMatrix(n, m);\n    printMatrix(matrix);\n    vector<int> v = spiralOrder(matrix);\n    printArray(v);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp",
    "content": "// Source : https://leetcode.com/problems/split-array-largest-sum/\n// Author : Hao Chen\n// Date   : 2016-11-13\n\n/*************************************************************************************** \n *\n * Given an array which consists of non-negative integers and an integer m, you can \n * split the array into m non-empty continuous subarrays. Write an algorithm to \n * minimize the largest sum among these m subarrays.\n * \n * Note:\n * Given m satisfies the following constraint: 1 ≤ m ≤  length(nums) ≤ 14,000.\n * \n * Examples: \n * \n * Input:\n * nums = [7,2,5,10,8]\n * m = 2\n * \n * Output:\n * 18\n * \n * Explanation:\n * There are four ways to split nums into two subarrays.\n * The best way is to split it into [7,2,5] and [10,8],\n * where the largest sum among the two subarrays is only 18.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    // Idea\n    //   1) The max of the result is the sum of the whole array.\n    //   2) The min of the result is the max num among the array.\n    //   3) Then, we use Binary Search to find the resullt between the `min` and  the `max`\n    \n    int splitArray(vector<int>& nums, int m) {\n        int min = 0, max = 0;\n        for (int n : nums) {\n            min = std::max(min, n);\n            max += n;\n        }\n        while (min < max) {\n            int mid = min + (max - min) / 2;\n            if (hasSmallerSum(nums, m, mid)) max = mid;\n            else min = mid + 1;\n        }\n        return min;\n    }\n    \n    \n    // Using a specific `sum` to check wheter we can get `smaller sum`\n    // The idea here as below:\n    //   find all of possible `sub array` whose sum greater than `sum`\n    //   1) if the number of `sub array` >  m, whcih means the actual result is greater than `sum`\n    //   2) if the number of `sub array` <= m, whcih means we can have `smaller sum`\n    //\n    bool hasSmallerSum(vector<int>& nums, int m, int sum) {\n        int cnt = 1, curSum = 0;\n        for (int n : nums) {\n            curSum += n;\n            if (curSum > sum) {\n                curSum = n;\n                cnt++;\n                if (cnt > m) return false;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/splittingAStringIntoDescendingConsecutiveValues/SplittingAStringIntoDescendingConsecutiveValues.cpp",
    "content": "// Source : https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/\n// Author : Hao Chen\n// Date   : 2021-05-03\n\n/***************************************************************************************************** \n *\n * You are given a string s that consists of only digits.\n * \n * Check if we can split s into two or more non-empty substrings such that the numerical values of the \n * substrings are in descending order and the difference between numerical values of every two \n * adjacent substrings is equal to 1.\n * \n * \tFor example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical \n * values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is \n * valid.\n * \tAnother example, the string s = \"001\" can be split into [\"0\", \"01\"], [\"00\", \"1\"], or [\"0\", \n * \"0\", \"1\"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and \n * [0,0,1] respectively, all of which are not in descending order.\n * \n * Return true if it is possible to split s​​​​​​ as described above, or false otherwise.\n * \n * A substring is a contiguous sequence of characters in a string.\n * \n * Example 1:\n * \n * Input: s = \"1234\"\n * Output: false\n * Explanation: There is no valid way to split s.\n * \n * Example 2:\n * \n * Input: s = \"050043\"\n * Output: true\n * Explanation: s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\n * The values are in descending order with adjacent values differing by 1.\n * \n * Example 3:\n * \n * Input: s = \"9080701\"\n * Output: false\n * Explanation: There is no valid way to split s.\n * \n * Example 4:\n * \n * Input: s = \"10009998\"\n * Output: true\n * Explanation: s can be split into [\"100\", \"099\", \"98\"] with numerical values [100,99,98].\n * The values are in descending order with adjacent values differing by 1.\n * \n * Constraints:\n * \n * \t1 <= s.length <= 20\n * \ts only consists of digits.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int pos;\npublic:\n    bool getNum(string& s, long target) {\n        \n        long n = 0;\n        while(s[pos] == '0') pos++; \n        while(pos < s.size()){\n            n = (n*10 + s[pos++] - '0') ;\n            if (n == target) return true;\n            if (n > target ) return false; // n is already greater than target\n        }\n        return target == n;\n    }\n    \n    long firstNum(string& s, int len) {\n        long n = 0;\n        while(s[pos] == '0') pos++; \n        for(; pos< s.size() && len > 0; pos++, len--) {\n            n = (n*10 + s[pos] - '0') ;\n        }\n        return n;  \n    }\n    \n    bool splitString(string s) {\n        pos = 0;\n        long num;\n        for (int len=1; len<= s.size()/2+1; len++) {\n            pos = 0;\n            num = firstNum(s, len); \n            if (pos >= s.size()) continue; // only have one number\n            \n            bool result = true;\n            while( pos < s.size() ) {\n                if (getNum(s, --num) == false){\n                    result = false;\n                    break;\n                }\n            }\n            if (result) return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sqrt/sqrt.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/sqrtx/\n// Author : Hao Chen\n// Date   : 2014-08-26\n\n/********************************************************************************** \n* \n* Implement int sqrt(int x).\n* \n* Compute and return the square root of x.\n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\n\nint sqrt(int x) {\n\n    if (x <=0 ) return 0;\n    \n    //the sqrt is not greater than x/2+1\n    int e = x/2+1;\n    int s = 0;\n    // binary search\n    while ( s <= e ) {\n        int mid = s + (e-s)/2;\n        long long sq = (long long)mid*(long long)mid;\n        if (sq == x ) return mid;\n        if (sq < x) {\n            s = mid + 1;\n        }else {\n            e = mid - 1;\n        }\n    }\n    return e; \n        \n}\n\n// http://en.wikipedia.org/wiki/Newton%27s_method\nint sqrt_nt(int x) {\n    if (x == 0) return 0;\n    double last = 0;\n    double res = 1;\n    while (res != last)\n    {\n        last = res;\n        res = (res + x / res) / 2;\n    }\n    return int(res);\n}\n\n\nint main(int argc, char**argv)\n{\n    int n = 2;\n    if( argc > 1 ){\n        n = atoi(argv[1]);\n    }\n    cout << \"sqrt(\" << n << \") = \" << sqrt(n) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/squaresOfASortedArray/SquaresOfASortedArray.cpp",
    "content": "// Source : https://leetcode.com/problems/squares-of-a-sorted-array/\n// Author : Hao Chen\n// Date   : 2019-03-26\n\n/***************************************************************************************************** \n *\n * Given an array of integers A sorted in non-decreasing order, return an array of the squares of each \n * number, also in sorted non-decreasing order.\n * \n * Example 1:\n * \n * Input: [-4,-1,0,3,10]\n * Output: [0,1,9,16,100]\n * \n * Example 2:\n * \n * Input: [-7,-3,2,3,11]\n * Output: [4,9,9,49,121]\n * \n * Note:\n * \n * \t1 <= A.length <= 10000\n * \t-10000 <= A[i] <= 10000\n * \tA is sorted in non-decreasing order.\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    vector<int> sortedSquares(vector<int>& A) {\n        // find the place, negative numbers are right, positive number are right.\n        // two pointer, one goes left, another goes right.\n\n        //using binary search algorithm\n        const int len = A.size();\n        int low = 0, high = len- 1;\n        int mid =0;\n        while (low <= high) {\n            mid = low + (high - low)/2;\n            if (A[mid] >= 0 ) high = mid - 1;\n            if (A[mid] < 0 ) low = mid + 1;\n        }\n\n        //TRICKY: make sure  A[mid] <= 0 or A[mid] is A[0]\n        if (A[mid] > 0 && mid > 0 ) mid--;\n        //cout << mid << \" - \"<< A[mid]<<  endl;\n\n        vector<int> result;\n        low = mid; high = mid+1;\n        while ( low >=0 && high < len ) {\n            if ( abs(A[low]) < abs(A[high]) ) {\n                result.push_back(A[low] * A[low]);\n                low --;\n            }else {\n                result.push_back(A[high] * A[high]);\n                high++;\n            }\n        }\n\n        for (;low >= 0; low--) result.push_back(A[low] * A[low]);\n        for (;high<len; high++) result.push_back(A[high] * A[high] );\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/strStr/strStr.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/implement-strstr/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Implement strStr().\n* \n* Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nchar *strStr1(char *haystack, char *needle);\nchar *strStr2(char *haystack, char *needle);\n\nchar *strStr(char*haystack, char *needle) {\n    if (random()%2){\n        printf(\"---KMP---\\n\");\n        return strStr1(haystack, needle);\n    }\n    printf(\"---brute-force---\\n\");\n    return strStr2(haystack, needle);\n}\n//KMP\nchar *strStr1(char *haystack, char *needle) {\n    if(!haystack || !needle ) {\n        return NULL;\n    }\n    if (!*needle ) {\n        return haystack;\n    }\n\n    char *ph = haystack;\n    char *pn = needle;\n    for( ;*ph && *pn ; ph++, pn++ );\n\n    //len(haystack) < len(needle)\n    if (!*ph && *pn){\n        return NULL;    \n    }\n\n    for(ph=ph-1; *ph; haystack++, ph++) {\n        char *q=needle;\n        char *p=haystack;\n        int n=0;\n        while(*q && *p && *p==*q){\n            p++; q++;\n            if (n==0 && *p == *needle){\n                n = p - haystack;\n            }\n        }\n        if (!*q){\n            return haystack;\n        }\n        haystack += (n>0 ? n-1 : n);\n    }\n    return NULL;\n}\n\n//brute-force\nchar *strStr2(char *haystack, char *needle) {\n\n    if(!haystack || !needle ) {\n        return NULL;\n    }\n    if (!*needle ) {\n        return haystack;\n    }\n\n    char *ph = haystack;\n    char* pn = needle;\n    for( ;*ph && *pn ; ph++, pn++ );\n\n    //len(haystack) < len(needle)\n    if (!*ph && *pn){\n        return NULL;    \n    }\n    ph--;\n\n    for( ; *ph; haystack++, ph++) {\n        char *q=needle;\n        char *p=haystack;\n        while(*q && *p && *p==*q){\n            p++; q++;\n        }\n        if (!*q){\n            return haystack;\n        }\n    }\n\n    return NULL;\n}\n\nint main(int argc, char** argv)\n{\n    srand(time(0));\n    const char* haystack = \"mississippi\";\n    const char* needle = \"issi\";\n    printf(\"%s, %s : %s\\n\", haystack, needle, strStr((char*)haystack, (char*)needle));\n\n    haystack = \"mississippi\";\n    needle = \"issip\";\n    printf(\"%s, %s : %s\\n\", haystack, needle, strStr((char*)haystack, (char*)needle));\n\n\n    haystack = \"babbbbbabb\";\n    needle = \"bbab\";\n    printf(\"%s, %s : %s\\n\", haystack, needle, strStr1((char*)haystack, (char*)needle));\n\n    if (argc>2){\n        haystack = argv[1];\n        needle = argv[2];\n        printf(\"%s, %s : %s\\n\", haystack, needle, strStr((char*)haystack, (char*)needle));\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/stringToIntegerAtoi/stringToIntegerAtoi.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/string-to-integer-atoi/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Implement atoi to convert a string to an integer.\n* \n* Hint: Carefully consider all possible input cases. If you want a challenge, \n*       please do not see below and ask yourself what are the possible input cases.\n* \n* Notes: \n*   It is intended for this problem to be specified vaguely (ie, no given input specs). \n*   You are responsible to gather all the input requirements up front. \n* \n* \n* Requirements for atoi:\n* \n* The function first discards as many whitespace characters as necessary until the first \n* non-whitespace character is found. Then, starting from this character, takes an optional \n* initial plus or minus sign followed by as many numerical digits as possible, and interprets \n* them as a numerical value.\n* \n* The string can contain additional characters after those that form the integral number, \n* which are ignored and have no effect on the behavior of this function.\n* \n* If the first sequence of non-whitespace characters in str is not a valid integral number, \n* or if no such sequence exists because either str is empty or it contains only whitespace \n* characters, no conversion is performed.\n* \n* If no valid conversion could be performed, a zero value is returned. If the correct value \n* is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) \n* is returned.\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n\n#define INT_MIN     (-2147483647 - 1)\n#define INT_MAX      2147483647\n\nint atoi(const char *str) {\n    if (str==NULL || *str=='\\0'){\n        return 0;\n    }\n    \n    int ret=0;\n    \n    for(;isspace(*str); str++);\n    \n    bool neg=false;\n    if (*str=='-' || *str=='+') {\n        neg = (*str=='-') ;\n        str++;\n    }\n    \n    for(; isdigit(*str); str++) {\n        int digit = (*str-'0');\n        if(neg){\n            if( -ret < (INT_MIN + digit)/10 ) {\n                return INT_MIN;\n            }\n        }else{\n            if( ret > (INT_MAX - digit) /10 ) {\n                return INT_MAX;\n            }\n        }\n\n        ret = 10*ret + digit ;\n    }\n    \n    return neg?-ret:ret;\n}\n\n\nint main()\n{\n    printf(\"\\\"%s\\\" = %d\\n\", \"123\", atoi(\"123\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"   123\", atoi(\"    123\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"+123\", atoi(\"+123\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \" -123\", atoi(\" -123\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"123ABC\", atoi(\"123ABC\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \" abc123ABC\", atoi(\" abc123ABC\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"2147483647\", atoi(\"2147483647\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"-2147483648\", atoi(\"-2147483648\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"2147483648\", atoi(\"2147483648\"));\n    printf(\"\\\"%s\\\" = %d\\n\", \"-2147483649\", atoi(\"-2147483649\"));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/stringWithoutAAAOrBBB/StringWithoutAAAOrBBB.cpp",
    "content": "// Source : https://leetcode.com/problems/string-without-aaa-or-bbb/\n// Author : Hao Chen\n// Date   : 2019-01-29\n\n/***************************************************************************************************** \n *\n * Given two integers A and B, return any string S such that:\n * \n * \tS has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters;\n * \tThe substring 'aaa' does not occur in S;\n * \tThe substring 'bbb' does not occur in S.\n * \n * Example 1:\n * \n * Input: A = 1, B = 2\n * Output: \"abb\"\n * Explanation: \"abb\", \"bab\" and \"bba\" are all correct answers.\n * \n * Example 2:\n * \n * Input: A = 4, B = 1\n * Output: \"aabaa\"\n * \n * Note:\n * \n * \t0 <= A <= 100\n * \t0 <= B <= 100\n * \tIt is guaranteed such an S exists for the given A and B.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string strWithout3a3b(int A, int B) {\n\n        string result;\n        while (true){\n\n            // if A == B, then just simpley repeat \"ab\" pattern;\n            if (A == B) {\n                for ( int i=0; i<A; i++ ) {\n                    result += \"ab\";\n                }\n                break;\n            }\n\n            // if A+B less then 3 and A != B, which means A=1,2 && B=0 or A=0 && B=1,2\n            if (A+B <3) {\n                while  ( A-- > 0 ) result += 'a';\n                while  ( B-- > 0 ) result += 'b';\n                break;\n            }\n\n            // if A+B >=3 and A !=B\n\n            // if A > B, then we need consume 'a' more than 'b'\n            // So, only \"aab\" can be used.\n            if ( A > B ) {\n                result += \"aab\";\n                A -= 2;\n                B--;\n                continue;\n            }\n\n            // if A > B, then we need consume 'b' more than 'a'\n            // So, only \"bba\" can be used.\n            if (B > A ){\n                result += \"bba\";\n                B-=2;\n                A--;\n                continue;\n            }\n\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/subsets/subsets.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/subsets-ii/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Given a collection of integers that might contain duplicates, S, return all possible subsets.\n* \n* Note:\n* \n* Elements in a subset must be in non-descending order.\n* The solution set must not contain duplicate subsets.\n* \n* For example,\n* If S = [1,2,2], a solution is:\n* \n* [\n*   [2],\n*   [1],\n*   [1,2,2],\n*   [2,2],\n*   [1,2],\n*   []\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvoid getCombination(vector<int>& v, int n, int k, vector<int>& solution, vector< vector<int> >& result );\nvector<vector<int> > combine(vector<int>& v, int k); \nvector<vector<int> > combine1(vector<int>& v, int k); \nvector<vector<int> > combine2(vector<int>& v, int k);\n\nvector<vector<int> > subsets(vector<int> &S) {\n    vector<vector<int> > result;\n    sort(S.begin(), S.end());\n    for(int i=0; i<=S.size(); i++){\n        vector<vector<int> > r = combine(S, i); \n        result.insert(result.end(), r.begin(), r.end()); \n    } \n    return result;\n}\n\n\nvector<vector<int> > combine(vector<int> &v, int k) {\n    vector<vector<int> > result;\n    vector<int> solution;\n    getCombination(v, v.size(), k, solution, result);\n    return result;\n}\n\nvoid getCombination(vector<int> &v, int n, int k, vector<int>& solution, vector< vector<int> >& result ){\n    if (k==0){\n        //sort to meet LeetCode requirement\n        vector<int> v = solution;\n        sort(v.begin(), v.end());\n        result.push_back(v);\n        return;\n    }\n    for(int i=n; i>0; i--){\n        solution.push_back(v[i-1]);\n        getCombination(v, i-1, k-1, solution, result);\n        solution.pop_back();\n        //skip the duplication\n        while (i>1 && v[i-1]==v[i-2]) i--;\n   }\n}\n\n\nvoid printResult(vector<vector<int> >& result)\n{\n    for(int i=0; i<result.size(); i++){\n        cout << \"{\";\n        for(int j=0; j<result[i].size(); j++){\n            cout << \" \" << result[i][j];\n        }\n        cout << \" }\" <<endl;\n    }\n}\n\nvoid printArray(vector<int>& v){\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \" }\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    srand(time(NULL));\n\n    int n = 3;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector<int> v;\n    for(int i=n; i>0; i--){\n        v.push_back(random()%n+1);\n    }\n    printArray(v);\n    cout << \"--------------------\" <<endl;\n    vector<vector<int> > r = subsets(v);\n    printResult(r);\n    cout << \"====================\" <<endl;\n\n    int a[] = {1, 4, 4, 4, 4,};\n    v.clear();\n    v.insert(v.begin(), a, a+5);\n    printArray(v);\n    cout << \"--------------------\" <<endl;\n    r = subsets(v);\n    printResult(r);\n    cout << \"====================\" <<endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/subsets/subsets.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/subsets/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a set of distinct integers, S, return all possible subsets.\n* \n* Note:\n* \n* Elements in a subset must be in non-descending order.\n* The solution set must not contain duplicate subsets.\n* \n* For example,\n* If S = [1,2,3], a solution is:\n* \n* [\n*   [3],\n*   [1],\n*   [2],\n*   [1,2,3],\n*   [1,3],\n*   [2,3],\n*   [1,2],\n*   []\n* ]\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nvoid getCombination(vector<int>& v, int n, int k, vector<int>& solution, vector< vector<int> >& result );\nvector<vector<int> > combine(vector<int>& v, int k); \nvector<vector<int> > combine1(vector<int>& v, int k); \nvector<vector<int> > combine2(vector<int>& v, int k);\n\nvector<vector<int> > subsets(vector<int> &S) {\n    vector<vector<int> > result;\n    for(int i=0; i<=S.size(); i++){\n        vector<vector<int> > r = combine(S, i); \n        result.insert(result.end(), r.begin(), r.end()); \n    } \n    return result;\n}\n\n\nvector<vector<int> > combine(vector<int>& v, int k) {\n    if (random()%2){\n        cout << \"recusive method!\" << endl;\n        return combine1(v, k);\n    }\n    cout << \"non-recusive method!\" << endl;\n    return combine2(v, k);\n}\n\nvector<vector<int> > combine1(vector<int> &v, int k) {\n    vector<vector<int> > result;\n    vector<int> solution;\n    getCombination(v, v.size(), k, solution, result);\n    return result;\n}\n\nvoid getCombination(vector<int> &v, int n, int k, vector<int>& solution, vector< vector<int> >& result ){\n    if (k==0){\n        //sort to meet LeetCode requirement\n        vector<int> v = solution;\n        sort(v.begin(), v.end());\n        result.push_back(v);\n        return;\n    }\n    for(int i=n; i>0; i--){\n        solution.push_back(v[i-1]);\n        getCombination(v, i-1, k-1, solution, result);\n        solution.pop_back();\n    }\n}\n\nvector<vector<int> > combine2(vector<int> &v, int k) {\n    \n    vector<vector<int> > result;\n    vector<int> d;\n    int n = v.size();\n    for (int i=0; i<n; i++){\n        d.push_back( (i<k) ? 1 : 0 );\n    }\n\n    //1) from the left, find the [1,0] pattern, change it to [0,1]\n    //2) move all of the 1 before the pattern to the most left side\n    //3) check all of 1 move to the right\n    while(1){\n        vector<int> tmp;\n        for(int x=0; x<n; x++){\n            if (d[x]) tmp.push_back(v[x]);\n        }\n        sort(tmp.begin(), tmp.end());\n        result.push_back(tmp);\n        //step 1), find [1,0] pattern\n        int i;\n        bool found = false;\n        int ones =0;\n        for(i=0; i<n-1; i++){\n            \n            if (d[i]==1 && d[i+1]==0){\n                d[i]=0; d[i+1]=1;\n                found = true;\n                //step 2) move all of right 1 to the most left side\n                for (int j=0; j<i; j++){\n                    d[j]=( ones > 0 ) ? 1 : 0;\n                    ones--;\n                }\n                break; \n            } \n            if (d[i]==1) ones++;\n        }\n        if (!found){\n            break;\n        }\n        \n    }\n    return result;\n    \n}\n\n\n\n\nvoid printResult(vector<vector<int> >& result)\n{\n    for(int i=0; i<result.size(); i++){\n        cout << \"{\";\n        for(int j=0; j<result[i].size(); j++){\n            cout << \" \" << result[i][j];\n        }\n        cout << \" }\" <<endl;\n    }\n}\n\nvoid printArray(vector<int>& v){\n    cout << \"{\";\n    for(int i=0; i<v.size(); i++) {\n        cout << \" \" << v[i];\n    }\n    cout << \" }\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    srand(time(NULL));\n\n    int n = 3;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector<int> v;\n    for(int i=n; i>0; i--){\n        v.push_back(i);\n    }\n    printArray(v);\n    vector<vector<int> > r = subsets(v);\n    printResult(r);\n}\n"
  },
  {
    "path": "algorithms/cpp/substringWithConcatenationOfAllWords/substringWithConcatenationOfAllWords.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/\n// Author : Hao Chen\n// Date   : 2014-08-24\n\n/********************************************************************************** \n* \n* You are given a string, S, and a list of words, L, that are all of the same length. \n* Find all starting indices of substring(s) in S that is a concatenation of each word \n* in L exactly once and without any intervening characters.\n* \n* For example, given:\n* S: \"barfoothefoobarman\"\n* L: [\"foo\", \"bar\"]\n* \n* You should return the indices: [0,9].\n* (order does not matter).\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <map>\nusing namespace std;\n\nvector<int> findSubstring(string S, vector<string> &L) {\n\n    vector<int> result;\n    if ( S.size()<=0 || L.size() <=0 ){\n        return result;\n    }\n    \n    int n = S.size(), m = L.size(), l = L[0].size();\n\n    //put all of words into a map    \n    map<string, int> expected;\n    for(int i=0; i<m; i++){\n        if (expected.find(L[i])!=expected.end()){\n            expected[L[i]]++;\n        }else{\n            expected[L[i]]=1;\n        }\n    }\n\n    for (int i=0; i<l; i++){\n        map<string, int> actual;\n        int count = 0; //total count\n        int winLeft = i;\n        for (int j=i; j<=n-l; j+=l){\n            string word = S.substr(j, l);\n            //if not found, then restart from j+1;\n            if (expected.find(word) == expected.end() ) {\n                actual.clear();\n                count=0;\n                winLeft = j + l;\n                continue;\n            }\n            count++;\n            //count the number of \"word\"\n            if (actual.find(word) == actual.end() ) {\n                actual[word] = 1;\n            }else{\n                actual[word]++;\n            }\n            // If there is more appearance of \"word\" than expected\n            if (actual[word] > expected[word]){\n                string tmp;\n                do {\n                    tmp = S.substr( winLeft, l );\n                    count--;\n                    actual[tmp]--;\n                    winLeft += l; \n                } while(tmp!=word);\n            }\n\n            // if total count equals L's size, find one result\n            if ( count == m ){\n                result.push_back(winLeft);\n                string tmp = S.substr( winLeft, l );\n                actual[tmp]--;\n                winLeft += l;\n                count--;\n            }\n            \n        }\n    }\n\n    return result;\n}\n\n\nint main(int argc, char**argv)\n{\n    string s = \"barfoobarfoothefoobarman\";\n    vector<string> l;\n    l.push_back(\"foo\");\n    l.push_back(\"bar\");\n    l.push_back(\"foo\");\n    \n    vector<int> indics = findSubstring(s, l);\n    \n    for(int i=0; i<indics.size(); i++){\n        cout << indics[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/substringsOfSizeThreeWithDistinctCharacters/SubstringsOfSizeThreeWithDistinctCharacters.cpp",
    "content": "// Source : https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/submissions/\n// Author : Hao Chen\n// Date   : 2021-11-12\n\n/***************************************************************************************************** \n *\n * A string is good if there are no repeated characters.\n * \n * Given a string s, return the number of good substrings of length three in s.\n * \n * Note that if there are multiple occurrences of the same substring, every occurrence should be \n * counted.\n * \n * A substring is a contiguous sequence of characters in a string.\n * \n * Example 1:\n * \n * Input: s = \"xyzzaz\"\n * Output: 1\n * Explanation: There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \n * The only good substring of length 3 is \"xyz\".\n * \n * Example 2:\n * \n * Input: s = \"aababcabc\"\n * Output: 4\n * Explanation: There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\n * The good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \ts consists of lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countGoodSubstrings(string s) {\n        char exist[26] = {0};\n        \n        int cnt = 0, c = 0;\n        \n        \n        for (int i = 0; i<s.size(); i++){\n            char ch = s[i] - 'a';\n            \n            if (i > 2) {\n                char ch = s[i-3]-'a';\n                exist[ch]--;\n                if ( exist[ch] == 0 ) c--;\n            }\n            \n            exist[ch]++;\n            if (exist[ch] == 1 ) {\n                c++;\n            }\n            \n            if ( c == 3 ){\n                cnt++;\n            }\n            \n\n        }\n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sudokuSolver/sudokuSolver.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/sudoku-solver/\n// Author : Hao Chen\n// Date   : 2014-09-20\n\n/********************************************************************************** \n* \n* Write a program to solve a Sudoku puzzle by filling the empty cells.\n* \n* Empty cells are indicated by the character '.'.\n* \n* You may assume that there will be only one unique solution.\n* \n* A sudoku puzzle...\n* \n* ...and its solution numbers marked in red.\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\nconst int SodukuSize = 9;\nbool row_mask[SodukuSize][SodukuSize];\nbool col_mask[SodukuSize][SodukuSize];\nbool area_mask[SodukuSize][SodukuSize];\n\nbool initSudokuMask(vector< vector<char> > &board){\n    //reset the memory\n    memset(row_mask, false, sizeof(row_mask));\n    memset(col_mask, false, sizeof(col_mask));\n    memset(area_mask, false, sizeof(area_mask));\n\n    //check each rows and cols\n    for(int r=0; r<board.size(); r++){\n        for (int c=0; c<board[r].size(); c++){\n            if (!isdigit(board[r][c])) {\n                continue;\n            };\n            int idx =  board[r][c] - '0' - 1;\n\n            //check the rows/cols/areas\n            int area = (r/3) * 3 + (c/3);\n            if (row_mask[r][idx] || col_mask[c][idx] || area_mask[area][idx] ){\n                return false;\n            }\n            row_mask[r][idx] = col_mask[c][idx] = area_mask[area][idx] = true;\n        }\n    }\n    return true;\n\n}\n\n\nbool recursiveSudoKu(vector< vector<char> > &board, int row, int col){\n\n    if (row >= SodukuSize) {\n        return true;\n    }\n\n    if (col >= SodukuSize){\n        return recursiveSudoKu(board, row+1, 0);\n    }\n    \n    if (board[row][col] != '.'){\n        return recursiveSudoKu(board, row, col+1);    \n    }\n    //pick a number for empty cell\n    int area;\n    for(int i=0; i<SodukuSize; i++){\n        area = (row/3) * 3 + (col/3);\n        if (row_mask[row][i] || col_mask[col][i] || area_mask[area][i] ){\n            continue;\n        }\n        //set the number and sovle it recursively\n        board[row][col] = i + '1';\n        row_mask[row][i] = col_mask[col][i] = area_mask[area][i] = true;\n        if (recursiveSudoKu(board, row, col+1) == true){\n            return true;\n        }\n        //backtrace\n        board[row][col] = '.';\n        row_mask[row][i] = col_mask[col][i] = area_mask[area][i] = false;\n         \n    }\n    return false;\n}\n\n\nvoid solveSudoku(vector<vector<char> > &board) {\n    if (initSudokuMask(board) == false){\n        return;\n    }\n    recursiveSudoKu(board, 0, 0); \n}\n\n\nint main(int argc, char**argv) {\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/sumOfBeautyOfAllSubstrings/SumOfBeautyOfAllSubstrings.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-beauty-of-all-substrings/\n// Author : Hao Chen\n// Date   : 2021-03-13\n\n/***************************************************************************************************** \n *\n * The beauty of a string is the difference in frequencies between the most frequent and least \n * frequent characters.\n * \n * \tFor example, the beauty of \"abaacc\" is 3 - 1 = 2.\n * \n * Given a string s, return the sum of beauty of all of its substrings.\n * \n * Example 1:\n * \n * Input: s = \"aabcb\"\n * Output: 5\n * Explanation: The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with \n * beauty equal to 1.\n * \n * Example 2:\n * \n * Input: s = \"aabcbaa\"\n * Output: 17\n * \n * Constraints:\n * \n * \t1 <= s.length <= 500\n * \ts consists of only lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    int beauty(string& s, int start, int end) {\n        int stat[26] = {0};\n        for (int i=start; i<=end; i++){\n            stat[s[i]-'a']++;\n        }\n        int max = INT_MIN, min = INT_MAX; \n        for (auto s: stat) {\n            if (s == 0 ) continue;\n            max = s > max ? s : max;\n            min = s < min ? s : min;\n        }\n        return max - min;\n    }\npublic:\n    int beautySum(string s) {\n        return beautySum02(s);\n        return beautySum01(s);\n    }\n    \n    int beautySum01(string& s) {\n        int sum = 0; \n        for (int i=0; i<s.size()-1; i++) {\n            for (int j=i+1; j<s.size(); j++) {\n                sum += beauty(s, i, j);\n            }\n        }\n        return sum;\n    }\n    \n    //same as beautySum01(), but optimazed slightly\n    int beautySum02(string& s) {\n        int sum = 0; \n        for (int i=0; i<s.size()-1; i++) {\n            int stat[26] = {0};\n            for (int j=i; j<s.size(); j++) {\n                stat[s[j]-'a']++;\n                int max = INT_MIN, min = INT_MAX; \n                for (auto& n: stat) {\n                    if (n <= 0 ) continue; \n                    max = n > max ? n : max;\n                    min = n < min ? n : min;\n                }\n                //cout << s.substr(i, j-i+1)  << \" --> \"<< max << \":\" << min << endl;\n                sum += (max - min);\n            }\n        }\n        return sum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfDigitsInBaseK/SumOfDigitsInBaseK.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-digits-in-base-k/\n// Author : Hao Chen\n// Date   : 2021-04-25\n\n/***************************************************************************************************** \n *\n * Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n \n * from base 10 to base k.\n * \n * After converting, each digit should be interpreted as a base 10 number, and the sum should be \n * returned in base 10.\n * \n * Example 1:\n * \n * Input: n = 34, k = 6\n * Output: 9\n * Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\n * \n * Example 2:\n * \n * Input: n = 10, k = 10\n * Output: 1\n * Explanation: n is already in base 10. 1 + 0 = 1.\n * \n * Constraints:\n * \n * \t1 <= n <= 100\n * \t2 <= k <= 10\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int sumBase(int n, int k) {\n        int sum = 0;\n        while(n > 0) {\n            sum += (n % k);\n            n /= k;\n        }\n        return sum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfDigitsOfStringAfterConvert/SumOfDigitsOfStringAfterConvert.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-digits-of-string-after-convert/\n// Author : Hao Chen\n// Date   : 2021-11-12\n\n/***************************************************************************************************** \n *\n * You are given a string s consisting of lowercase English letters, and an integer k.\n * \n * First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., \n * replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with \n * the sum of its digits. Repeat the transform operation k times in total.\n * \n * For example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following \n * operations:\n * \n * \tConvert: \"zbax\" ➝ \"(26)(2)(1)(24)\" ➝ \"262124\" ➝ 262124\n * \tTransform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17\n * \tTransform #2: 17 ➝ 1 + 7 ➝ 8\n * \n * Return the resulting integer after performing the operations described above.\n * \n * Example 1:\n * \n * Input: s = \"iiii\", k = 1\n * Output: 36\n * Explanation: The operations are as follows:\n * - Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999\n * - Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36\n * Thus the resulting integer is 36.\n * \n * Example 2:\n * \n * Input: s = \"leetcode\", k = 2\n * Output: 6\n * Explanation: The operations are as follows:\n * - Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545\n * - Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33\n * - Transform #2: 33 ➝ 3 + 3 ➝ 6\n * Thus the resulting integer is 6.\n * \n * Example 3:\n * \n * Input: s = \"zbax\", k = 2\n * Output: 8\n * \n * Constraints:\n * \n * \t1 <= s.length <= 100\n * \t1 <= k <= 10\n * \ts consists of lowercase English letters.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int sumChar(char c) {\n        int x = c - 'a' + 1;\n        return x < 10 ? x : x / 10 + x % 10;\n    }\n    int sumInt(int x) {\n        int s = 0;\n        while( x > 0 ) {\n            s += x % 10;\n            x /= 10;\n        }\n        return s;\n    }\n    int getLucky(string s, int k) {\n        int result = 0;\n        for (auto c : s) {\n            result += sumChar(c);\n        }\n        for (; k > 1 ; k--) {\n            result = sumInt(result);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfEvenNumbersAfterQueries/SumOfEvenNumbersAfterQueries.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-even-numbers-after-queries/\n// Author : Hao Chen\n// Date   : 2019-02-05\n\n/***************************************************************************************************** \n *\n * We have an array A of integers, and an array queries of queries.\n * \n * For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the \n * answer to the i-th query is the sum of the even values of A.\n * \n * (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the \n * array A.)\n * \n * Return the answer to all queries.  Your answer array should have answer[i] as the answer to the \n * i-th query.\n * \n * Example 1:\n * \n * Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\n * Output: [8,6,2,4]\n * Explanation: \n * At the beginning, the array is [1,2,3,4].\n * After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\n * After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\n * After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\n * After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n * \n * Note:\n * \n * \t1 <= A.length <= 10000\n * \t-10000 <= A[i] <= 10000\n * \t1 <= queries.length <= 10000\n * \t-10000 <= queries[i][0] <= 10000\n * \t0 <= queries[i][1] < A.length\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) {\n        int sum = 0;\n        for(int i=0; i<A.size(); i++) {\n            if (A[i] % 2 == 0) sum += A[i];\n        }\n        vector<int> result;\n        for(auto query : queries) {\n            int i = query[1];\n            int x = A[i] + query[0];\n            \n            if (A[i] % 2 == 0 && x %2 == 0) {\n                sum += ( -A[i] + x ); \n                A[i] = x;\n            } else if (A[i] % 2 != 0 && x %2 == 0) {\n                sum += x;\n                A[i] = x;\n            } else if (A[i] % 2 == 0 && x %2 != 0) {\n                sum -= A[i];\n                A[i] = x;\n            } else if (A[i] % 2 != 0 && x %2 != 0){ \n                A[i] = x;\n            }\n            result.push_back(sum);\n        }\n        \n        if (result.size()<=0) result.push_back(0);\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfFlooredPairs/SumOfFlooredPairs.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-floored-pairs/\n// Author : Hao Chen\n// Date   : 2021-05-22\n\n/***************************************************************************************************** \n *\n * Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 \n * <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7.\n * \n * The floor() function returns the integer part of the division.\n * \n * Example 1:\n * \n * Input: nums = [2,5,9]\n * Output: 10\n * Explanation:\n * floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\n * floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\n * floor(5 / 2) = 2\n * floor(9 / 2) = 4\n * floor(9 / 5) = 1\n * We calculate the floor of the division for every pair of indices in the array then sum them up.\n * \n * Example 2:\n * \n * Input: nums = [7,7,7,7,7,7,7]\n * Output: 49\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 10^5\n * \t1 <= nums[i] <= 10^5\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int sumOfFlooredPairs(vector<int>& nums) {\n        const int MAX_NUM = 100001;\n        int cnt[MAX_NUM] = {0};\n        int maxn = 0;\n        for(auto& n : nums) {\n            cnt[n]++;\n            maxn = max(maxn, n);\n        }\n        \n        vector<vector<int>> stats;\n        for(int i=1; i<MAX_NUM; i++) {\n            if (cnt[i] > 0) {\n                stats.push_back({i, cnt[i]});\n            }\n            cnt[i] += cnt[i-1];\n        }\n        \n        const int MOD = 1e9+7;\n        int result = 0;\n        for(int i=0; i < stats.size(); i++) {\n            int n = stats[i][0];\n            int c = stats[i][1];\n\n            for(int x=2; x <= maxn/n+1; x++) {\n                int pre = (x-1) * n - 1; \n                int cur = min( x * n - 1, MAX_NUM-1);\n                result = (result + (cnt[cur] - cnt[pre]) * long(x-1) * c) % MOD;      \n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-left-leaves/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * Find the sum of all left leaves in a given binary tree.\n * \n * Example:\n * \n *     3\n *    / \\\n *   9  20\n *     /  \\\n *    15   7\n * \n * There are two left leaves in the binary tree, with values 9 and 15 respectively. \n * Return 24.\n ***************************************************************************************/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n\n    \n    void sumOfLeftLeaves_recursion_v1(TreeNode* root, int& result) {\n        if (root == NULL ) {\n            return;\n        }\n        \n        if (root->left && root->left->left == NULL && root->left->right == NULL) {\n            result += root->left->val;\n        }\n        sumOfLeftLeaves_recursion_v1(root->left, result);\n        sumOfLeftLeaves_recursion_v1(root->right, result);\n        \n    }\n    \n    int sumOfLeftLeaves_recursion_v2(TreeNode* root) {\n        if (root == NULL ) {\n            return 0;\n        }\n        int result = 0;\n        if (root->left && root->left->left == NULL && root->left->right == NULL) {\n            result = root->left->val;\n        }\n        result += sumOfLeftLeaves_recursion_v2(root->left) + sumOfLeftLeaves_recursion_v2(root->right);\n        return result;\n    }    \n    \n\n    int sumOfLeftLeaves(TreeNode* root) {\n        srand(time(NULL));\n        if (rand()%2) {\n            int result = 0;\n            sumOfLeftLeaves_recursion_v1(root, result);\n            return result;\n        } else {\n            return sumOfLeftLeaves_recursion_v2(root);\n        }\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-two-integers/description/\n// Author : Hao Chen\n// Date   : 2018-06-25\n\n/*************************************************************************************** \n *\n * Calculate the sum of two integers a and b, but you are not allowed to use the \n * operator + and -.\n * \n * Example:\n * Given a = 1 and b = 2, return 3.\n * \n * \n * Credits:Special thanks to @fujiaozhu for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int getSum(int x, int y) {\n        // Iterate till there is no carry  \n        while (y != 0) {\n            // carry now contains common \n            //set bits of x and y\n            int carry = x & y;  \n\n            // Sum of bits of x and y where at \n            //least one of the bits is not set\n            x = x ^ y; \n\n            // Carry is shifted by one so that adding\n            // it to x gives the required sum\n            y = carry << 1;\n        }\n        return x;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/sumOfUniqueElements/SumOfUniqueElements.cpp",
    "content": "// Source : https://leetcode.com/problems/sum-of-unique-elements/\n// Author : Hao Chen\n// Date   : 2021-02-12\n\n/***************************************************************************************************** \n *\n * You are given an integer array nums. The unique elements of an array are the elements that appear \n * exactly once in the array.\n * \n * Return the sum of all the unique elements of nums.\n * \n * Example 1:\n * \n * Input: nums = [1,2,3,2]\n * Output: 4\n * Explanation: The unique elements are [1,3], and the sum is 4.\n * \n * Example 2:\n * \n * Input: nums = [1,1,1,1,1]\n * Output: 0\n * Explanation: There are no unique elements, and the sum is 0.\n * \n * Example 3:\n * \n * Input: nums = [1,2,3,4,5]\n * Output: 15\n * Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 100\n * \t1 <= nums[i] <= 100\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int sumOfUnique(vector<int>& nums) {\n        return sumOfUnique_special(nums);\n        return sumOfUnique_general(nums);\n    }\n    \n    int sumOfUnique_general(vector<int>& nums) {\n        enum stat {UNIQ, DUP};\n        unordered_map<int, stat> dict;\n        int sum = 0;\n        for (auto i : nums) {\n            if (dict.find(i) == dict.end()){\n                sum += i;\n                dict[i] = UNIQ;\n            } else {\n                if (dict[i] == UNIQ) {\n                    sum -= i;\n                    dict[i] = DUP;\n                }\n            }\n            \n        }\n        return sum;\n    }\n    \n    int sumOfUnique_special(vector<int>& nums) {\n        //because we have constraint: 1 <= nums[i] <= 100\n        //we can use array instead of map \n        enum stat {NO=0,UNIQ=1,DUP=2};\n        stat dict[100]={NO};\n        int sum = 0;\n        for (auto i : nums) {\n            switch(dict[i-1]) {\n                case NO:\n                    sum += i;\n                    dict[i-1] = UNIQ;\n                    break;\n                case UNIQ:\n                    sum -= i;\n                    dict[i-1] = DUP;\n                    break;\n                default:\n                    continue;\n            }\n        }\n        return sum;\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/sumRootToLeafNumber/sumRootToLeafNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/\n// Author : Hao Chen\n// Date   : 2014-06-21\n\n/********************************************************************************** \n* \n* Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.\n* An example is the root-to-leaf path 1->2->3 which represents the number 123.\n* \n* Find the total sum of all root-to-leaf numbers.\n* \n* For example,\n* \n*     1\n*    / \\\n*   2   3\n* \n* The root-to-leaf path 1->2 represents the number 12.\n* The root-to-leaf path 1->3 represents the number 13.\n* \n* Return the sum = 12 + 13 = 25.\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int sumNumbers(TreeNode *root) {\n    \n        if (!root) return 0;\n        \n        int sum = 0;       \n        vector<TreeNode*> v;\n        v.push_back(root);\n        while(v.size()>0){\n            TreeNode* node = v.back();\n            v.pop_back();\n            if (node->left){\n                node->left->val += (10*node->val); \n                v.push_back(node->left);\n            }\n            if (node->right){\n                node->right->val += (10*node->val); \n                v.push_back(node->right);\n            }\n            if(!node->right && !node->left){\n                sum += node->val;\n            }\n        }\n        \n        return sum;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/summaryRanges/SummaryRanges.cpp",
    "content": "// Source : https://leetcode.com/problems/summary-ranges/\n// Author : Hao Chen\n// Date   : 2015-07-03\n\n/********************************************************************************** \n * \n * Given a sorted integer array without duplicates, return the summary of its ranges.\n * \n * For example, given [0,1,2,4,5,7], return [\"0->2\",\"4->5\",\"7\"].\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\n\nclass Solution {\npublic:\n    string makeRange(int start, int end) {\n        ostringstream oss;\n        if (start != end) {\n            oss << start << \"->\" << end;\n        } else {\n            oss << start;\n        }\n        return oss.str();\n    }\n    \n    vector<string> summaryRanges(vector<int>& nums) {\n        vector<string> result;\n        int len = nums.size();\n        if (len == 0) return result;\n        \n        // we have two pointer for range-starter and range-ender\n        int start=nums[0], end=nums[0];\n\n        for (int i=1; i<len; i++) {\n            // if it is continous number, move the end pointer;\n            if (nums[i] == end + 1) {\n                end = nums[i];\n                continue;\n            }\n            \n            //if the number is not continous, push the range into result\n            //and reset the start and end pointer\n            result.push_back(makeRange(start, end));\n            start = end = nums[i];\n        \n        }\n        \n        //for the last range\n        result.push_back(makeRange(start, end)); \n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/superUglyNumber/SuperUglyNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/super-ugly-number/\n// Author : Hao Chen\n// Date   : 2017-01-02\n\n/*************************************************************************************** \n *\n * Write a program to find the nth super ugly number.\n * \n *     Super ugly numbers are positive numbers whose all prime factors are in the given \n * prime list\n *     primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32]\n *  is the sequence of the first 12 super ugly numbers given primes\n *     = [2, 7, 13, 19] of size 4.\n * \n *     Note:\n *     (1) 1 is a super ugly number for any given primes.\n *     (2) The given numbers in primes are in ascending order.\n *     (3) 0 k ≤ 100, 0 n ≤ 106, 0 primes[i] \n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\n// As the solution we have for the ugly number II problem\n//\n//    int nthUglyNumber(int n) {\n//\n//        int i=0, j=0, k=0;\n//        vector<int> ugly(1,1);\n//\n//        while(ugly.size() < n){\n//            int next = min(ugly[i]*2, ugly[j]*3, ugly[k]*5);\n//            if (next == ugly[i]*2) i++;\n//            if (next == ugly[j]*3) j++;\n//            if (next == ugly[k]*5) k++;\n//            ugly.push_back(next);\n//        }\n//        return ugly.back();\n//    }\n//\n// The logic of solution is exacly same for both., except that instead of 3 numbers you have k numbers to consider. \n//\n// \n//\nclass Solution {\n  \npublic:\n    int nthSuperUglyNumber(int n, vector<int>& primes) {\n        vector<int> ugly(1, 1);\n        int len = primes.size();\n        vector<int> pos(len, 0);\n        \n        while( ugly.size() < n ) {\n            int next = INT_MAX;\n            for(int i=0; i<len; i++) {\n                next = min(next, ugly[pos[i]] * primes[i]);\n            }\n            for(int i=0; i<len; i++) {\n                if (next == ugly[pos[i]] * primes[i]) {\n                    pos[i]++;\n                }\n            }\n            ugly.push_back(next);\n        }\n        return ugly.back();\n    }\n    \n\n};\n"
  },
  {
    "path": "algorithms/cpp/surroundedRegions/surroundedRegions.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/surrounded-regions/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.\n* \n* A region is captured by flipping all 'O's into 'X's in that surrounded region.\n* \n* For example,\n* \n* X X X X\n* X O O X\n* X X O X\n* X O X X\n* \n* After running your function, the board should be:\n* \n* X X X X\n* X X X X\n* X X X X\n* X O X X\n* \n*               \n**********************************************************************************/\n\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nvoid print(vector< vector<char> > &board);\n\n\nvoid markOpen(vector< vector<char> > &board, int row, int col, int r, int c) {\n    if (r<0 || c <0 || r>=row || c>=col || board[r][c] != 'O') return;\n    board[r][c]='N'; // 'N' means it's not closed\n    markOpen(board, row, col, r+1, c);\n    markOpen(board, row, col, r-1, c);\n    markOpen(board, row, col, r, c+1);\n    markOpen(board, row, col, r, c-1);\n}\n\nvoid solve_recursively(vector< vector<char> > &board) {\n\n    if (board.size()<=0 || board[0].size()<=0) return;\n\n    int row = board.size();\n    int col = board[0].size();\n    //left & right edge\n    for (int r=0; r<row; r++){\n        if ( board[r][0] == 'O') {\n            markOpen(board, row, col, r, 0); \n        }\n        if ( board[r][col-1] == 'O') {\n            markOpen(board, row, col, r, col-1); \n        }\n    }\n    //top & bottom edge\n    for (int c=1; c<col-1; c++){\n        if ( board[0][c] == 'O') {\n            markOpen(board, row, col, 0, c); \n        }\n        if ( board[row-1][c] == 'O') {\n            markOpen(board, row, col, row-1, c); \n        }\n    }\n    print(board);\n    // change 'N' to 'O', change 'O' to 'X'\n    for (int r=0; r<row; r++) {\n        for (int c=0; c<col; c++) {\n            if (board[r][c] == 'O') {\n                board[r][c]='X';\n            } else if (board[r][c] == 'N') {\n                board[r][c]='O';\n            }\n        }\n    }\n}\n\n\n/*change the recursive method to non_recursive way by using queue*/\n\nstruct position{\n    int row, col;\n    void set(int r, int c) { row = r; col = c; }\n    position(int r, int c): row(r), col(c) {}\n};\n\nvoid solve_non_recursively(vector< vector<char> > &board) {\n\n    if (board.size()<=0 || board[0].size()<=0) return;\n\n    int row = board.size();\n    int col = board[0].size();\n\n    queue<position> q;\n    position p(0,0);\n\n    //left & right edge\n    for (int r=0; r<row; r++){\n        if ( board[r][0] == 'O') {\n            board[r][0] = 'N';\n            p.set(r, 0);\n            q.push(p) ; \n        }\n        if ( board[r][col-1] == 'O') {\n            board[r][col-1] = 'N';\n            p.set(r, col-1);\n            q.push(p) ; \n        }\n    }\n    //top & bottom edge\n    for (int c=1; c<col-1; c++){\n        if ( board[0][c] == 'O') {\n            board[0][c] = 'N';\n            p.set(0, c);\n            q.push(p) ; \n        }\n        if ( board[row-1][c] == 'O') {\n            board[row-1][c] = 'N';\n            p.set(row-1, c);\n            q.push(p) ; \n        }\n    }\n\n    while (!q.empty()){\n        p = q.front();\n        q.pop(); \n        int r = p.row;\n        int c = p.col;\n        if (r < row-1 && board[r+1][c] == 'O') {\n            board[r+1][c] = 'N';\n            p.set(r+1, c);\n            q.push(p);\n        }\n        if (r > 0 && board[r-1][c] == 'O') {\n            board[r-1][c] = 'N';\n            p.set(r-1, c);\n            q.push(p);\n        }\n        if (c < col-1 && board[r][c+1] == 'O') {\n            board[r][c+1] = 'N';\n            p.set(r, c+1);\n            q.push(p);\n        }\n        if (c>0 && board[r][c-1] == 'O') {\n            board[r][c-1] = 'N';\n            p.set(r, c-1);\n            q.push(p);\n        }\n    }\n\n\n    print(board);\n    // change 'N' to 'O', change 'O' to 'X'\n    for (int r=0; r<row; r++) {\n        for (int c=0; c<col; c++) {\n            if (board[r][c] == 'O') {\n                board[r][c]='X';\n            } else if (board[r][c] == 'N') {\n                board[r][c]='O';\n            }\n        }\n    }\n}\n\n\n// refers to <Algorithm> 4th edition.\nclass UnionFind {\n    int  count_;  // number of components\n    int* rank_;   // to limits tree hights\n    int* id_;     // id[i] parent of i\npublic:\n    UnionFind(int n) {\n        count_ = n;\n        rank_ = new int[n];\n        id_ = new int[n];\n        for (int i = 0; i < n; i++) {\n            id_[i] = i;\n            rank_[i] = 0;\n        }\n    }\n\n    ~UnionFind() {\n        delete [] rank_;\n        delete [] id_;\n    }\n\n    int count() { return count_; }\n\n    int find(int p) {\n        while (p != id_[p])    {\n            id_[p] = id_[id_[p]]; // path compression\n            p = id_[p];\n        }\n        return p;\n    }\n\n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n\n    void connect(int p, int q) {\n        int i = find(p);\n        int j = find(q);\n        if (i == j) return;\n        if (rank_[i] < rank_[j]) id_[i] = j;\n        else if (rank_[i] > rank_[j]) id_[j] = i;\n        else { // ==\n            id_[j] = i;\n            rank_[i]++;\n        }\n        count_--;\n    }\n};\n\nclass Solution {\npublic:\n    void solve(vector<vector<char> >& board) {\n        int n = board.size();\n        if (n == 0) return;\n        int m = board[0].size();\n\n        UnionFind uf(n*m+1);\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                if (i == 0 || i == n-1 || j == 0 || j == m-1) { // side case, connect to dummy node\n                    uf.connect(i*m + j, n*m);\n                    continue;\n                }\n                char c = board[i][j]; // inner case, connect to same neighbor\n                if (board[i+1][j] == c) uf.connect((i+1)*m + j, i*m + j);\n                if (board[i-1][j] == c) uf.connect((i-1)*m + j, i*m + j);\n                if (board[i][j+1] == c) uf.connect(i*m + (j+1), i*m + j);\n                if (board[i][j-1] == c) uf.connect(i*m + (j-1), i*m + j);\n            }\n        }\n\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                if (board[i][j] == 'O' && !uf.connected(i*m + j, n*m)) {\n                    board[i][j] = 'X';\n                }\n            }\n        }\n    }\n};\n\n\nvoid solve(vector< vector<char> > &board) {\n    if (rand() % 2) {\n        Solution().solve(board);\n        return;\n    }\n    solve_recursively(board); \n    solve_non_recursively(board); \n}\n\nvoid construct(vector< vector<char> > &board, int row, int col) {\n    srand(time(0));\n    for(int i=0; i<row; i++){\n        vector<char> line;\n        for(int j=0; j<col; j++){\n            if (i==0 || j==0 || i==row-1 || j==col-1) \n                line.push_back(rand()%3 ? 'X' : 'O'); \n            else\n                line.push_back(rand()%2 ? 'X' : 'O'); \n        }\n        board.push_back(line);\n    }\n}\n\nvoid print(vector< vector<char> > &board) {\n    for(int i=0; i<board.size(); i++){\n        for(int j=0; j<board[i].size(); j++){\n            cout << board[i][j] << \" \";\n        }\n        cout << endl;\n    }\n    cout << endl;\n}\n\nint main(int argc, char** argv )\n{\n    int row, col;\n    row = col = 6;\n    if (argc>1){\n        row = atoi(argv[1]);\n    }\n    if (argc>2){\n        col = atoi(argv[2]);\n    }\n\n    vector< vector<char> > data;\n\n    construct(data, row, col);\n    print(data);\n\n    solve(data);\n    print(data);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/swapNodesInPairs/swapNodesInPairs.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/swap-nodes-in-pairs/\n// Author : Hao Chen\n// Date   : 2014-06-22\n\n/********************************************************************************** \n* \n* Given a linked list, swap every two adjacent nodes and return its head.\n* \n* For example,\n* Given 1->2->3->4, you should return the list as 2->1->4->3.\n* \n* Your algorithm should use only constant space. You may not modify the values in the list, \n* only nodes itself can be changed.\n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n    /*\n     * Here we have two ways to solve this problem:\n     * 1) keep the list's nodes no change. only swap the data in the list node.\n     * 2) swap the list node physically.\n     */\n    ListNode *swapPairs(ListNode *head) {\n        if(random()%2){\n            return swapPairs1(head);\n        }\n        return swapPairs2(head);\n    }\n    /*just swap the node's value instead of node*/\n    ListNode *swapPairs1(ListNode *head) {\n        for (ListNode *p = head; p && p->next; p = p->next->next) {\n            int n = p->val;\n            p->val = p->next->val;\n            p->next->val = n;\n        }\n        return head;\n    }\n    /*swap the list nodes physically*/ \n    ListNode *swapPairs2(ListNode *head) {\n        ListNode *h = NULL;\n        //using `*p` to traverse the linked list\n        for (ListNode *p = head; p && p->next; p = p->next) {\n            //`n` is `p`'s next node, and swap `p` and `n` physcially\n            ListNode *n = p->next;\n            p->next = n->next;\n            n->next = p;\n            //using `h` as `p`'s previous node\n            if (h){\n                h->next = n;\n            }\n            h=p;\n            \n            //determin the really 'head' pointer\n            if (head == p){\n                head = n;\n            }\n        }\n        \n        return head;\n    }\n\n    ListNode* swapPairs3(ListNode* head) {\n         // Three pointers point current, previous and next node.\n         ListNode *Curr=head, *Prev=NULL, *Next=NULL;\n\n         while (Curr && Curr->next ) {\n             Next = Curr->next;\n\n             //swap nodes\n             Curr->next = Next->next;\n             Prev == NULL ? head = Prev = Next : Prev->next = Next;\n             Next->next = Curr;\n\n             //set the pointers to next place.\n             Prev = Curr;\n             Curr = Curr->next;\n         }\n         return head;\n     }\n};\n"
  },
  {
    "path": "algorithms/cpp/symmetricTree/symmetricTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/symmetric-tree/\n// Author : Hao Chen\n// Date   : 2014-06-28\n\n/********************************************************************************** \n* \n* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n* \n* For example, this binary tree is symmetric:\n* \n*     1\n*    / \\\n*   2   2\n*  / \\ / \\\n* 3  4 4  3\n* \n* But the following is not:\n* \n*     1\n*    / \\\n*   2   2\n*    \\   \\\n*    3    3\n* \n* Note:\n* Bonus points if you could solve it both recursively and iteratively.\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    Solution(){\n        srand(time(NULL));\n    }\n\n    bool isSymmetric(TreeNode *root) {\n        if (root == NULL ) return true;\n        return isSymmetric(root->left, root->right);\n        \n    }\n    \n    bool isSymmetric(TreeNode *p, TreeNode *q){\n        if (random()%2){\n           return isSymmetric1(p, q);\n        }\n        return isSymmetric2(p, q);\n    }\n    \n    bool isSymmetric1(TreeNode *p, TreeNode *q){\n        if (p==NULL && q==NULL) return true;\n        if (p==NULL || q==NULL) return false;\n        \n        return (p->val == q->val) &&\n                isSymmetric(p->left, q->right) &&\n                isSymmetric(p->right, q->left);\n    }\n    \n    bool isSymmetric2(TreeNode *p, TreeNode *q){\n\n        queue<TreeNode*> q1;\n        queue<TreeNode*> q2;\n        q1.push(p);\n        q2.push(q);\n        while(q1.size()>0 && q2.size()>0){\n            TreeNode* p1 = q1.front();\n            q1.pop();\n            TreeNode* p2 = q2.front();\n            q2.pop();\n            if (p1==NULL && p2==NULL) continue;\n            if (p1==NULL || p2==NULL) return false;\n            \n            if (p1->val != p2->val) return false;\n            \n            q1.push(p1->left);\n            q2.push(p2->right);\n\n            q1.push(p1->right);\n            q2.push(p2->left);\n\n        }\n        return true;\n        \n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/targetSum/targetSum.cpp",
    "content": "// Source : https://leetcode.com/problems/target-sum/\n// Author : Bhavesh Mandhan\n// Date   : 2020-10-21\n\n\n/**********************************************************************************\n * You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. \n * Now you have 2 symbols + and -. For each integer, you should choose one from + and - \n * as its new symbol.\n *\n * Find out how many ways to assign symbols to make sum of integers equal to target S.\n *\n * \tFor example, given array nums is [1, 1, 1, 1, 1], S is 3.\n *\n * \tThere are 5 ways to assign symbols to make the sum of nums be target 3.\n *\n * \t-1+1+1+1+1 = 3\n * \t+1-1+1+1+1 = 3\n * \t+1+1-1+1+1 = 3\n * \t+1+1+1-1+1 = 3\n * \t+1+1+1+1-1 = 3\n\n***********************************************************************************/\n\nclass Solution {\npublic:\n    int findTargetSumWays(vector<int>& nums, int S) {\n        long int i,j,n,tot=0,sum,zero=0;\n        n = nums.size();\n        for(i=0;i<n;i++){\n            tot+=nums[i];\n            if(nums[i]==0){\n                zero++;\n            }\n        }\n        if((S+tot)%2!=0 || S>tot){\n            return 0;\n        }\n        sum = (S+tot)/2;\n        int dp[n+1][sum+1];\n        for(i=1;i<=sum;i++){\n            dp[0][i]= 0;\n        }\n        for(i=0;i<=n;i++){\n            dp[i][0]= 1;\n        }\n        for(i=1;i<=n;i++){\n            for(j=1;j<=sum;j++){\n                if(nums[i-1]==0 || nums[i-1]>j){\n                    dp[i][j] = dp[i-1][j];\n                }\n                else{\n                    dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]];\n                }\n            }\n        }\n        return pow(2,zero)*dp[n][sum];\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/textJustification/textJustification.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/text-justification/\n// Author : Hao Chen\n// Date   : 2014-10-11\n\n/********************************************************************************** \n* \n* Given an array of words and a length L, format the text such that each line has \n* exactly L characters and is fully (left and right) justified.\n*  \n* \n* You should pack your words in a greedy approach; that is, pack as many words as you can in each line. \n* Pad extra spaces ' ' when necessary so that each line has exactly L characters.\n* \n* Extra spaces between words should be distributed as evenly as possible. \n* If the number of spaces on a line do not divide evenly between words, \n* the empty slots on the left will be assigned more spaces than the slots on the right.\n* \n* For the last line of text, it should be left justified and no extra space is inserted between words.\n* \n* For example,\n* words: [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"]\n* L: 16.\n* \n* Return the formatted lines as:\n* \n* [\n*    \"This    is    an\",\n*    \"example  of text\",\n*    \"justification.  \"\n* ]\n* \n* Note: Each word is guaranteed not to exceed L in length.\n* \n* \n* Corner Cases:\n* \n* A line other than the last line might contain only one word. What should you do in this case?\n* In this case, that line should be left-justified.\n* \n*               \n**********************************************************************************/\n\n#include <math.h>\n#include <iostream>\n#include <string>\n#include <vector>\nusing namespace std;\n\n\nvector<string> fullJustify(vector<string> &words, int L) {\n    vector<string> result;\n    \n    int len=0;\n    int start = 0;\n    int end = 0;\n    double space =0;\n    bool lastLine = false;\n    for (int i=0; i<words.size(); i++){\n        len += words[i].size();\n        if (len + i - start > L || i == words.size()-1) {\n            //remove the last one\n            if (len + i - start > L) {  \n                len -= words[i].size();\n                end = i-1;\n                lastLine = false;\n            }else{\n                end = i;\n                lastLine = true;\n            }\n            //calculate the space number\n            space = L - len;\n            int mspace;\n            int extra;\n            if (lastLine){\n                mspace = 1;\n                extra = 0;\n            } else {\n                mspace = floor(space/(end-start));\n                extra = space - mspace * (end-start);\n            }\n\n            string line = words[start];\n            for (int j=start+1; j<=end; j++) {\n                for(int k=0; k<mspace && space>0; k++, space--) {\n                    line += \" \";\n                }   \n                if (j-start-1 < extra){\n                    line += \" \";\n                    space--;\n                } \n                line += words[j];\n            }\n            //add the rest space\n            if (space>0){\n                for(; space>0; space--) {\n                    line += \" \";\n                }\n            }\n            result.push_back(line);\n            start = i;\n            i = end;\n            len = 0;\n        } \n    }\n\n    return result;\n}\n\n\nvoid printVector(vector<string> &words, bool newline=false) {\n    for(int i=0; i<words.size(); i++) {\n        cout << \"\\\"\" << words[i] << \"\\\", \";\n        if (newline) cout << endl; \n    }\n    cout << endl;\n}\n\nvoid test(const char* A[], int len, int L) {\n    vector<string> words(A, A+len);\n\n    printVector(words);\n\n    vector<string> result = fullJustify(words, L);\n    cout << endl;\n    printVector(result, true);\n\n}\n\n#define TEST(a, L) test(a, sizeof(a)/sizeof(const char*), L)\n\nint main(int argc, char** argv)\n{\n    const char* w1[]={\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"};\n    TEST(w1, 16);    \n\n    const char* w2[] = {\"What\",\"must\",\"be\",\"shall\",\"be.\"}; \n    TEST(w2, 12);\n    \n    const char* w3[] = {\"My\",\"momma\",\"always\",\"said,\",\"Life\",\"was\",\"like\",\"a\",\"box\",\"of\",\"chocolates.\",\"You\",\"never\",\"know\",\"what\",\"you're\",\"gonna\",\"get.\"};\n    TEST(w3, 20);\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/theSkylineProblem/TheSkylineProblem.cpp",
    "content": "// Source : https://leetcode.com/problems/the-skyline-problem/\n// Author : Hao Chen\n// Date   : 2015-06-11\n\n/********************************************************************************** \n * \n * A city's skyline is the outer contour of the silhouette formed by all the buildings \n * in that city when viewed from a distance. Now suppose you are given the locations and \n * height of all the buildings as shown on a cityscape photo (Figure A), write a program \n * to output the skyline formed by these buildings collectively (Figure B).\n * \n *  ^                                        ^                                                                   \n *  |                                        |                                                                   \n *  |                                        |                                                                   \n *  |    +-----+                             |    O-----+                                                        \n *  |    |     |                             |    |     |                                                        \n *  |    |     |                             |    |     |                                                        \n *  |    |  +--+------+                      |    |     O------+                                                 \n *  |    |  |         |                      |    |            |                                                 \n *  |  +-+--+----+    |   +------+           |  O-+            |   O------+                                      \n *  |  |         |    |   |      |           |  |              |   |      |                                      \n *  |  |         |    |   |    +-+--+        |  |              |   |      O--+                                   \n *  |  |         |    |   |    |    |        |  |              |   |         |                                   \n *  |  |         |    |   |    |    |        |  |              |   |         |                                   \n *  |  |         |    |   |    |    |        |  |              |   |         |                                   \n *  |  |         |    |   |    |    |        |  |              |   |         |                                   \n *  +--+---------+----+---+----+----+--->    +--+--------------O---+---------O--->                               \n *  \n *   https://leetcode.com/static/images/problemset/skyline1.jpg  \n *   https://leetcode.com/static/images/problemset/skyline2.jpg  \n * \n * The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], \n * where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, \n * and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 , and Ri - Li > 0. \n * You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\n * \n * For instance, the dimensions of all buildings in Figure A are recorded as: \n *  [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .\n * \n * The output is a list of \"key points\" (red dots in Figure B) in the format of \n * [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. \n * A key point is the left endpoint of a horizontal line segment. \n *\n * Note that the last key point, where the rightmost building ends, is merely used to mark \n * the termination of the skyline, and always has zero height. Also, the ground in between \n * any two adjacent buildings should be considered part of the skyline contour.\n * \n * For instance, the skyline in Figure B should be represented as:\n *  [ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].\n * \n * Notes:\n * \n *  - The number of buildings in any input list is guaranteed to be in the range [0, 10000].\n *  - The input list is already sorted in ascending order by the left x position Li. \n *  - The output list must be sorted by the x position. \n *  - There must be no consecutive horizontal lines of equal height in the output skyline. \n *    For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; \n *    the three lines of height 5 should be merged into one in the final output as such: \n *    [...[2 3], [4 5], [12 7], ...]\n * \n * Credits: Special thanks to @stellari for adding this problem, \n *          creating these two awesome images and all test cases.\n *               \n **********************************************************************************/\n\n\n\n/*\n * Sweep line with max-heap\n * ------------------------\n * Notice that \"key points\" are either the left or right edges of the buildings. \n * \n * Therefore, we first obtain both the edges of all the N buildings, and store the 2N edges in a sorted array. \n * Maintain a max-heap of building heights while scanning through the edge array: \n * 1) If the current edge is a left edge, then add the height of its associated building to the max-heap; \n * 2) If the edge is a right one, remove the associated height from the heap. \n * \n * Then we take the top value of the heap (yi) as the maximum height at the current edge position (xi). \n * Now (xi, yi) is a potential key point. \n * \n * If yi is the same as the height of the last key point in the result list, it means that this key point \n * is not a REAL key point, but rather a horizontal continuation of the last point, so it should be discarded; \n * \n * otherwise, we add (xi,yi) to the result list because it is a real key point. \n * \n * Repeat this process until all the edges are checked.\n * \n * It takes O(NlogN) time to sort the edge array. For each of the 2N edges, \n * it takes O(1) time to query the maximum height but O(logN) time to add \n * or remove elements. Overall, this solution takes O(NlogN) time.\n */\nclass Solution {\npublic:\n\n    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {\n        vector< pair<int, int> > edges;\n        \n        //put all of edge into a vector\n        //set left edge as negtive, right edge as positive\n        //so, when we sort the edges, \n        //  1) for same left point, the height would be descending order\n        //  2) for same right point, the height would be ascending order\n        int left, right, height;\n        for(int i=0; i<buildings.size(); i++) {\n            left   = buildings[i][0];\n            right  = buildings[i][1];\n            height = buildings[i][2];\n            edges.push_back(make_pair(left, -height));\n            edges.push_back(make_pair(right, height));\n        }\n        sort(edges.begin(), edges.end());\n\n        // 1) if we meet a left edge, then we add its height into a `set`.\n        //    the `set` whould sort the height automatically.\n        // 2) if we meet a right edge, then we remove its height from the `set`\n        //\n        // So, we could get the current highest height from the `set`, if the \n        // current height is different with preivous height, then we need add\n        // it into the result.\n        vector< pair<int, int> > result;\n        multiset<int> m;\n        m.insert(0);\n        int pre = 0, cur = 0;\n        for (int i=0; i<edges.size(); i++){\n            pair<int,int> &e = edges[i];\n            if (e.second < 0) {\n                m.insert(-e.second);\n            }else{\n                m.erase(m.find(e.second));\n            }\n            cur = *m.rbegin();\n            if (cur != pre) {\n                result.push_back(make_pair(e.first, cur));\n                pre = cur;\n            }\n        }\n        return result;\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/third-maximum-number/\n// Author : Hao Chen\n// Date   : 2016-11-12\n\n/*************************************************************************************** \n *\n * Given a non-empty array of integers, return the third maximum number in this array. \n * If it does not exist, return the maximum number. The time complexity must be in O(n).\n * \n * Example 1:\n * \n * Input: [3, 2, 1]\n * \n * Output: 1\n * \n * Explanation: The third maximum is 1.\n * \n * Example 2:\n * \n * Input: [1, 2]\n * \n * Output: 2\n * \n * Explanation: The third maximum does not exist, so the maximum (2) is returned \n * instead.\n * \n * Example 3:\n * \n * Input: [2, 2, 3, 1]\n * \n * Output: 1\n * \n * Explanation: Note that the third maximum here means the third maximum distinct \n * number.\n * Both numbers with value 2 are both considered as second maximum.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int nMax(vector<int>& nums, int n) {\n        set<int> topN;\n        for(auto num : nums) {\n            topN.insert(num);\n            if (topN.size() > n) topN.erase(topN.begin());\n        }\n        return (topN.size() >= n) ? *(topN.begin()) : *(topN.rbegin());\n    }\n    int thirdMax(vector<int>& nums) {\n        return nMax(nums, 3);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/thousandSeparator/ThousandSeparator.cpp",
    "content": "// Source : https://leetcode.com/problems/thousand-separator/\n// Author : Hao Chen\n// Date   : 2020-10-03\n\n/***************************************************************************************************** \n *\n * Given an integer n, add a dot (\".\") as the thousands separator and return it in string format.\n * \n * Example 1:\n * \n * Input: n = 987\n * Output: \"987\"\n * \n * Example 2:\n * \n * Input: n = 1234\n * Output: \"1.234\"\n * \n * Example 3:\n * \n * Input: n = 123456789\n * Output: \"123.456.789\"\n * \n * Example 4:\n * \n * Input: n = 0\n * Output: \"0\"\n * \n * Constraints:\n * \n * \t0 <= n < 2^31\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    string thousandSeparator(int n) {\n        if (n==0) return \"0\";\n        int cnt=0;\n        string result;\n        while( n > 0 ){\n            int m = n % 10;\n            result.insert(result.begin(),   ('0' + m) );\n            cnt++;\n            n /= 10;\n            if (cnt % 3 == 0 && n > 0) {\n                result = '.' + result;\n            }\n\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/threeConsecutiveOdds/ThreeConsecutiveOdds.cpp",
    "content": "// Source : https://leetcode.com/problems/three-consecutive-odds/\n// Author : Hao Chen\n// Date   : 2020-10-03\n\n/***************************************************************************************************** \n *\n * Given an integer array arr, return true if there are three consecutive odd numbers in the array. \n * Otherwise, return false.\n * \n * Example 1:\n * \n * Input: arr = [2,6,4,1]\n * Output: false\n * Explanation: There are no three consecutive odds.\n * \n * Example 2:\n * \n * Input: arr = [1,2,34,3,4,5,7,23,12]\n * Output: true\n * Explanation: [5,7,23] are three consecutive odds.\n * \n * Constraints:\n * \n * \t1 <= arr.length <= 1000\n * \t1 <= arr[i] <= 1000\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n\n    bool threeConsecutiveOdds(vector<int>& arr) {\n        int cnt = 0;\n        for (auto n : arr) {\n            if ( n % 2 ) cnt++;\n            else cnt = 0;\n            if (cnt >=3) return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/timeBasedKeyValueStore/TimeBasedKeyValueStore.cpp",
    "content": "// Source : https://leetcode.com/problems/time-based-key-value-store/\n// Author : Hao Chen\n// Date   : 2019-01-30\n\n/***************************************************************************************************** \n *\n * Create a timebased key-value store class Timeap, that supports two operations.\n * \n * 1. set(string key, string value, int timestamp)\n * \n * \tStores the key and value, along with the given timestamp.\n * \n * 2. get(string key, int timestamp)\n * \n * \tReturns a value such that set(key, value, timestamp_prev) was called previously, with \n * timestamp_prev <= timestamp.\n * \tIf there are multiple such values, it returns the one with the largest timestamp_prev.\n * \tIf there are no values, it returns the empty string (\"\").\n * \n * Example 1:\n * \n * Input: inputs = [\"Timeap\",\"set\",\"get\",\"get\",\"set\",\"get\",\"get\"], inputs = \n * [[],[\"foo\",\"bar\",1],[\"foo\",1],[\"foo\",3],[\"foo\",\"bar2\",4],[\"foo\",4],[\"foo\",5]]\n * Output: [null,null,\"bar\",\"bar\",null,\"bar2\",\"bar2\"]\n * Explanation:   \n * Timeap kv;   \n * kv.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1   \n * kv.get(\"foo\", 1);  // output \"bar\"   \n * kv.get(\"foo\", 3); // output \"bar\" since there is no value corresponding to foo at timestamp 3 and \n * timestamp 2, then the only value is at timestamp 1 ie \"bar\"   \n * kv.set(\"foo\", \"bar2\", 4);   \n * kv.get(\"foo\", 4); // output \"bar2\"   \n * kv.get(\"foo\", 5); //output \"bar2\"   \n * \n * Example 2:\n * \n * Input: inputs = [\"Timeap\",\"set\",\"set\",\"get\",\"get\",\"get\",\"get\",\"get\"], inputs = \n * [[],[\"love\",\"high\",10],[\"love\",\"low\",20],[\"love\",5],[\"love\",10],[\"love\",15],[\"love\",20],[\"love\",25]]\n * Output: [null,null,null,\"\",\"high\",\"high\",\"low\",\"low\"]\n * \n * Note:\n * \n * \tAll key/value strings are lowercase.\n * \tAll key/value strings have length in the range [1, 100]\n * \tThe timestamps for all Timeap.set operations are strictly increasing.\n * \t1 <= timestamp <= 107\n * \tTimeap.set and Timeap.get functions will be called a total of 120000 times (combined) per \n * test case.\n ******************************************************************************************************/\n\nclass TimeMap {\nprivate:\n    unordered_map<string, std::set<int>> key_time;\n    unordered_map<int, string> time_value;\npublic:\n    /** Initialize your data structure here. */\n    TimeMap() {\n        \n    }\n    \n    void set(string key, string value, int timestamp) {\n        key_time[key].insert(timestamp);\n        time_value[timestamp] = value;\n    }\n    \n    string get(string key, int timestamp) {\n        if ( key_time.find(key) == key_time.end() ) return \"\";\n        auto it = key_time[key].lower_bound(timestamp);\n        if ( *it == timestamp ) return time_value[*it];\n        if ( it != key_time[key].begin() ) {\n            it--;\n            return time_value[*it];\n        }\n        return \"\";\n    }\n};\n\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n"
  },
  {
    "path": "algorithms/cpp/timeNeededToInformAllEmployees/TimeNeededToInformAllEmployees.cpp",
    "content": "// Source : https://leetcode.com/problems/time-needed-to-inform-all-employees/\n// Author : Shreya Vanga\n// Date   : 2020-10-02\n\n/*************************************************************************************** \n *\n * A company has n employees with a unique ID for each employee from 0 to n - 1. \n * The head of the company has is the one with headID.\n *\n * Each employee has one direct manager given in the manager array where manager[i] is \n * the direct manager of the i-th employee, manager[headID] = -1. Also it's guaranteed \n * that the subordination relationships have a tree structure.\n *\n * The head of the company wants to inform all the employees of the company of an urgent \n * piece of news. He will inform his direct subordinates and they will inform their \n * subordinates and so on until all employees know about the urgent news.\n *\n * The i-th employee needs informTime[i] minutes to inform all of his direct subordinates \n * (i.e After informTime[i] minutes, all his direct subordinates can start spreading the news).\n *\n * Return the number of minutes needed to inform all the employees about the urgent news.\n * \n * Example:\n * \n * Given: n = 1, headID = 0, manager = [-1], informTime = [0]\n * Return: 0\n * \n * Given: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1]\n * Return: 21 \n * \n ***************************************************************************************/\n\n\n\n\n\nclass Solution {\npublic:\n    vector<int>visited;\n    long long int dfs(vector<vector<int>>& adj, vector<int>& informTime, int src, int n)\n    {\n        long long int count = 0;\n        for(int i=0;i<adj[src].size();i++)\n        {\n            count = max(count,dfs(adj, informTime, adj[src][i], n));\n        }\n        return (informTime[src]+count);\n    }\n    int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {\n        vector<vector<int>>adj(n);\n        for(int i=0;i<manager.size();i++)\n        {\n            if(manager[i] != -1)\n                adj[manager[i]].push_back(i);\n        }\n        long long int time;\n        visited.resize(n,0);\n        visited[headID] = 1;\n        time= dfs(adj, informTime, headID, n);\n        return time;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp",
    "content": "// Source : https://leetcode.com/problems/top-k-frequent-elements/\n// Author : Calinescu Valentin\n// Date   : 2016-05-02\n\n/*************************************************************************************** \n *\n * Given a non-empty array of integers, return the k most frequent elements.\n * \n * For example,\n * Given [1,1,1,2,2,3] and k = 2, return [1,2].\n * \n * Note: \n * You may assume k is always valid, 1 ≤ k ≤ number of unique elements.\n * Your algorithm's time complexity must be better than O(n log n), where n is the \n * array's size.\n * \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    struct element//structure consisting of every distinct number in the vector,\n    //along with its frequency\n    {\n        int number, frequency;\n        bool operator < (const element arg) const\n        {\n            return frequency < arg.frequency;\n        }\n    };\n    priority_queue <element> sol;//we use a heap so we have all of the elements sorted\n    //by their frequency\n    vector <int> solution;\n    \n    vector<int> topKFrequent(vector<int>& nums, int k) {\n        sort(nums.begin(), nums.end());\n        int i = 1;\n        for(; i < nums.size(); i++)\n        {\n            int freq = 1;\n            while(i < nums.size() && nums[i] == nums[i - 1])\n            {\n                i++;\n                freq++;\n            }\n            element el;\n            el.number = nums[i - 1];\n            el.frequency = freq;\n            sol.push(el);\n        }\n        if(i == nums.size())//if we have 1 distinct element as the last\n        {\n            element el;\n            el.number = nums[nums.size() - 1];\n            el.frequency = 1;\n            sol.push(el);\n        }\n        while(k)//we extract the first k elements from the heap\n        {\n            solution.push_back(sol.top().number);\n            sol.pop();\n            k--;\n        }\n        return solution;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp",
    "content": "// Source : https://leetcode.com/problems/total-hamming-distance/\n// Author : Calinescu Valentin\n// Date   : 2017-01-09\n\n/*************************************************************************************** \n *\n * The Hamming distance between two integers is the number of positions at which the \n * corresponding bits are different.\n * \n * Now your job is to find the total Hamming distance between all pairs of the given \n * numbers.\n * \n * Example:\n * Input: 4, 14, 2\n * \n * Output: 6\n * \n * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\n * showing the four bits relevant in this case). So the answer will be:\n * HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n * \n * Note:\n * Elements of the given array are in the range of 0 to 10^9\n * Length of the array will not exceed 10^4.\n ***************************************************************************************/\n\n/*\n*  Solution 1 - O(N)\n*\n* The total Hamming Distance is equal to the sum of all individual Hamming Distances\n* between every 2 numbers. However, given that this depends on the individual bits of\n* each number, we can see that we only need to compute the number of 1s and 0s for each\n* bit position. For example, we look at the least significant bit. Given that we need to\n* calculate the Hamming Distance for each pair of 2 numbers, we see that the answer is\n* equal to the number of 1s at this position * the number of 0s(which is the total number\n* of numbers - the number of 1s), because for each 1 we need to have a 0 to form a pair.\n* Thus, the solution is the sum of all these distances at every position.\n*/\nclass Solution {\npublic:\n    int totalHammingDistance(vector<int>& nums) {\n        long long solution = 0;\n        int ones[31];\n        for(int i = 0; i < 31; i++)\n            ones[i] = 0;\n        for(vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)\n        {\n            for(int i = 0; (1 << i) <= *it; i++) //i is the position of the bit\n                if((1 << i) & *it)//to see if the bit at i-position is a 1\n                    ones[i]++;\n        }\n        for(int i = 0; i < 31; i++)\n            solution += ones[i] * (nums.size() - ones[i]);\n        return solution;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/trappingRainWater/trappingRainWater.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/trapping-rain-water/\n// Author : Hao Chen\n// Date   : 2014-07-02\n\n/********************************************************************************** \n* \n* Given n non-negative integers representing an elevation map where the width of each bar is 1, \n* compute how much water it is able to trap after raining. \n* \n* For example, \n* Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.\n*   \n*     ^                                             \n*     |                                             \n*   3 |                       +--+                  \n*     |                       |  |                  \n*   2 |          +--+xxxxxxxxx|  +--+xx+--+         \n*     |          |  |xxxxxxxxx|  |  |xx|  |         \n*   1 |   +--+xxx|  +--+xxx+--+  |  +--+  +--+      \n*     |   |  |xxx|  |  |xxx|  |  |  |  |  |  |      \n*   0 +---+--+---+--+--+---+--+--+--+--+--+--+----->\n*       0  1   0  2  1   0  1  3  2  1  2  1        \n* \n* The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, \n* 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n*               \n**********************************************************************************/\n\n#include <stdio.h>\n/*\n * The idea is:\n *    1) find the highest bar.\n *    2) traverse the bar from left the highest bar.\n *       becasue we have the highest bar in right, so, any bar higher than its right bar(s) can contain the water.\n *    3) traverse the bar from right the highest bar.\n *       becasue we have the highest bar in left, so, any bar higher than its left bar(s) can contain the water.\n *\n * The code below is quite clear!\n *\n */\nint trap(int a[], int n) {\n    int result = 0;\n\n    //find the highest value/position\n    int maxHigh = 0;\n    int maxIdx = 0;\n    for(int i=0; i<n; i++){\n        if (a[i] > maxHigh){\n            maxHigh = a[i];\n            maxIdx = i;\n        }\n    }\n\n    //from the left to the highest postion\n    int prevHigh = 0;\n    for(int i=0; i<maxIdx; i++){\n        if(a[i] > prevHigh){\n            prevHigh = a[i];\n        }\n        result += (prevHigh - a[i]);\n    }\n\n    //from the right to the highest postion\n    prevHigh=0;\n    for(int i=n-1; i>maxIdx; i--){\n        if(a[i] > prevHigh){\n            prevHigh = a[i];\n        }\n        result += (prevHigh - a[i]);\n    }\n\n    return result;\n}\n\n#define TEST(a) printf(\"%d\\n\", trap(a, sizeof(a)/sizeof(int)))\nint main()\n{\n    int a[]={2,0,2};\n    TEST(a);\n    int b[]={0,1,0,2,1,0,1,3,2,1,2,1};\n    TEST(b);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/treeOfCoprimes/TreeOfCoprimes.cpp",
    "content": "// Source : https://leetcode.com/problems/tree-of-coprimes/\n// Author : Hao Chen\n// Date   : 2021-04-01\n\n/***************************************************************************************************** \n *\n * There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes \n * numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the \n * root of the tree is node 0.\n * \n * To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] \n * represents the i^th node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj \n * and vj in the tree.\n * \n * Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of \n * x and y.\n * \n * An ancestor of a node i is any other node on the shortest path from node i to the root. A node is \n * not considered an ancestor of itself.\n * \n * Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and \n * nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n * \n * Example 1:\n * \n * Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\n * Output: [-1,0,0,1]\n * Explanation: In the above figure, each node's value is in parentheses.\n * - Node 0 has no coprime ancestors.\n * - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n * - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node \n * 0's\n *   value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n * - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is \n * its\n *   closest valid ancestor.\n * \n * Example 2:\n * \n * Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\n * Output: [-1,0,-1,0,0,0,-1]\n * \n * Constraints:\n * \n * \tnums.length == n\n * \t1 <= nums[i] <= 50\n * \t1 <= n <= 10^5\n * \tedges.length == n - 1\n * \tedges[j].length == 2\n * \t0 <= uj, vj < n\n * \tuj != vj\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    // Euclidean algorithm\n    // https://en.wikipedia.org/wiki/Euclidean_algorithm\n    int gcd(int a, int b) {\n        while (a != b ) { \n            if (a > b ) a -= b;\n            else b -= a;\n        }\n        return a;\n    }\n    void print(vector<int>& v, int len, vector<int>& nums){\n        cout << \"[\";\n        for(int i=0; i< len; i++) {\n            cout << v[i] <<\"(\"<< nums[v[i]]<<\"), \";\n        }\n        cout << v[len] <<\"(\"<<nums[v[len]]<<\")]\"<< endl;\n    }\n    \npublic:\n    vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {\n        unordered_map<int, vector<int>> graph;\n        for(auto& edge : edges) {\n            graph[edge[0]].push_back(edge[1]);\n            graph[edge[1]].push_back(edge[0]);\n        }\n       \n        int n = nums.size();\n        vector<int> result(n, -1);\n        \n        vector<int> path(n, -1);\n        path[0] = 0;\n        \n        // primePos[num] = {position, level};\n        vector<vector<pair<int, int>>> primePos(51, vector<pair<int, int>>());\n        \n        getCoprimesDFS(-1, 0, nums, graph, path, 0, primePos, result);\n    \n        return result;\n    }\n    \n    void getCoprimesDFS(int parent, int root,\n                        vector<int>& nums,\n                        unordered_map<int, vector<int>>& graph,\n                        vector<int>& path, int pathLen,\n                        vector<vector<pair<int, int>>>& primePos,\n                        vector<int>& result) {\n\n        int max_level = -1;\n        // find the previous closest prime \n        for(int n = 0; n < primePos.size(); n++) {\n            auto& pos = primePos[n];\n            //  no position || not co-prime\n            if ( pos.size() <=0  || gcd(nums[root], n) != 1) continue; \n            if (pos.back().second > max_level && pos.back().first != root) {\n                max_level = pos.back().second;\n                result[root] =  pos.back().first;\n            }\n\n        }\n        \n        primePos[nums[root]].push_back({root, pathLen});\n        for (auto& child : graph[root]) {\n            if (child == parent) continue; // don't go back\n            path[pathLen+1] = child; // for debug\n            getCoprimesDFS(root, child, nums, graph, path, pathLen + 1, primePos, result);\n        }\n        primePos[nums[root]].pop_back();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/triangle/triangle.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/triangle/\n// Author : Hao Chen\n// Date   : 2014-06-18\n\n/********************************************************************************** \n* \n* Given a triangle, find the minimum path sum from top to bottom. \n* Each step you may move to adjacent numbers on the row below.\n* \n* For example, given the following triangle\n* \n* [\n*      [2],\n*     [3,4],\n*    [6,5,7],\n*   [4,1,8,3]\n* ]\n* \n* The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\n* \n* Note:\n* Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nclass Solution {\n    \npublic:\n    int minimumTotal(vector<vector<int> > &triangle) {\n        vector< vector<int> > v;\n        \n        for (int i=0; i<triangle.size(); i++){\n            \n            if(i==0){\n                v.push_back(triangle[i]);\n                continue;\n            }\n            \n            vector<int> tmp;\n            \n            \n            for(int j=0; j<triangle[i].size(); j++){\n                int x, y, z;\n                x = y = z = 0x7fff;\n                if ( (j-1) >= 0){\n                    x = v[i-1][j-1];\n                }\n                if (j<v[i-1].size()) {\n                    y = v[i-1][j];\n                }\n                /* won't take the previous adjacent number */\n                //if ( (j+1)<v[i-1].size()) {\n                //    z = v[i-1][j+1];\n                //}\n                tmp.push_back( min(x,y,z) + triangle[i][j] );\n            }\n            \n            v.push_back(tmp);\n            \n        }\n        int min=0x7fff;\n        if (v.size() > 0){\n            vector<int> &vb = v[v.size()-1];\n            for(int i=0; i<vb.size(); i++){\n                if (vb[i] < min ){\n                    min = vb[i];\n                }\n            }\n        }\n           \n        return min;\n    }\nprivate:\n    inline int min(int x, int y, int z){\n        int n = x<y?x:y;\n        return (n<z?n:z);\n    }\n};\n\n\nint main()\n{\n    vector< vector<int> > v;\n    vector<int> i;\n    i.push_back(-1);\n    v.push_back(i);\n    \n    i.clear();\n    i.push_back(2);\n    i.push_back(3);\n    v.push_back(i);\n\n    i.clear();\n    i.push_back(1);\n    i.push_back(-1);\n    i.push_back(-3);\n    v.push_back(i);\n\n    Solution s;\n    cout << s.minimumTotal(v) << endl;;\n    \n    v.clear();\n    i.clear();\n    i.push_back(-1);\n    v.push_back(i);\n    \n    i.clear();\n    i.push_back(3);\n    i.push_back(2);\n    v.push_back(i);\n\n    i.clear();\n    i.push_back(-3);\n    i.push_back(1);\n    i.push_back(-1);\n    v.push_back(i);\n    cout << s.minimumTotal(v) << endl;;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/triplesWithBitwiseANDEqualToZero/TriplesWithBitwiseAndEqualToZero.cpp",
    "content": "// Source : https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/\n// Author : Hao Chen\n// Date   : 2020-07-26\n\n/***************************************************************************************************** \n *\n * Given an array of integers A, find the number of triples of indices (i, j, k) such that:\n * \n * \t0 <= i < A.length\n * \t0 <= j < A.length\n * \t0 <= k < A.length\n * \tA[i] & A[j] & A[k] == 0, where & represents the bitwise-AND operator.\n * \n * Example 1:\n * \n * Input: [2,1,3]\n * Output: 12\n * Explanation: We could choose the following i, j, k triples:\n * (i=0, j=0, k=1) : 2 & 2 & 1\n * (i=0, j=1, k=0) : 2 & 1 & 2\n * (i=0, j=1, k=1) : 2 & 1 & 1\n * (i=0, j=1, k=2) : 2 & 1 & 3\n * (i=0, j=2, k=1) : 2 & 3 & 1\n * (i=1, j=0, k=0) : 1 & 2 & 2\n * (i=1, j=0, k=1) : 1 & 2 & 1\n * (i=1, j=0, k=2) : 1 & 2 & 3\n * (i=1, j=1, k=0) : 1 & 1 & 2\n * (i=1, j=2, k=0) : 1 & 3 & 2\n * (i=2, j=0, k=1) : 3 & 2 & 1\n * (i=2, j=1, k=0) : 3 & 1 & 2\n * \n * Note:\n * \n * \t1 <= A.length <= 1000\n * \t0 <= A[i] < 2^16\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int countTriplets(vector<int>& A) {\n        int n = A.size();\n\n        //using a map to aggregate the duplication\n        unordered_map<int, int> rec;\n        for (int i=0; i<n; i++) {\n            for (int j=0; j<n; j++) {\n                rec[A[i] & A[j]]++;\n            }\n        }\n\n        int result = 0;\n        for (auto &r : rec ) {\n            for (int k=0; k<n; k++) {\n                if ((r.first & A[k]) == 0) result+=r.second;\n            }\n        }\n        return result;\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/truncateSentence/TruncateSentence.cpp",
    "content": "// Source : https://leetcode.com/problems/truncate-sentence/\n// Author : Hao Chen\n// Date   : 2021-04-05\n\n/***************************************************************************************************** \n *\n * A sentence is a list of words that are separated by a single space with no leading or trailing \n * spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).\n * \n * \tFor example, \"Hello World\", \"HELLO\", and \"hello world hello world\" are all sentences.\n * \n * You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it \n * contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.\n * \n * Example 1:\n * \n * Input: s = \"Hello how are you Contestant\", k = 4\n * Output: \"Hello how are you\"\n * Explanation:\n * The words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\n * The first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\n * Hence, you should return \"Hello how are you\".\n * \n * Example 2:\n * \n * Input: s = \"What is the solution to this problem\", k = 4\n * Output: \"What is the solution\"\n * Explanation:\n * The words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\n * The first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\n * Hence, you should return \"What is the solution\".\n * \n * Example 3:\n * \n * Input: s = \"chopper is not a tanuki\", k = 5\n * Output: \"chopper is not a tanuki\"\n * \n * Constraints:\n * \n * \t1 <= s.length <= 500\n * \tk is in the range [1, the number of words in s].\n * \ts consist of only lowercase and uppercase English letters and spaces.\n * \tThe words in s are separated by a single space.\n * \tThere are no leading or trailing spaces.\n ******************************************************************************************************/\n\nclass Solution {\nprivate:\n    bool isAlpha(const char& ch) {\n        return (ch >='a' && ch <='z') || (ch >= 'A' && ch <='Z') ;\n    }\npublic:\n    string truncateSentence(string s, int k) {\n        s += ' '; //for edge case\n        bool wordStart = false;\n        int i=0;\n        for (; i< s.size(); i++) {\n            if (!wordStart && isAlpha(s[i])) {\n                wordStart = true;\n            }else if (wordStart && !isAlpha(s[i])) {\n                if (--k <= 0) break;\n                wordStart = false;\n            }\n        }\n        return s.substr(0, i);\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/tupleWithSameProduct/TupleWithSameProduct.cpp",
    "content": "// Source : https://leetcode.com/problems/tuple-with-same-product/\n// Author : Hao Chen\n// Date   : 2021-04-27\n\n/***************************************************************************************************** \n *\n * Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such \n * that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.\n * \n * Example 1:\n * \n * Input: nums = [2,3,4,6]\n * Output: 8\n * Explanation: There are 8 valid tuples:\n * (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n * (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n * \n * Example 2:\n * \n * Input: nums = [1,2,4,5,10]\n * Output: 16\n * Explanation: There are 16 valids tuples:\n * (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n * (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n * (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)\n * (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n * \n * Example 3:\n * \n * Input: nums = [2,3,4,6,8,12]\n * Output: 40\n * \n * Example 4:\n * \n * Input: nums = [2,3,5,7]\n * Output: 0\n * \n * Constraints:\n * \n * \t1 <= nums.length <= 1000\n * \t1 <= nums[i] <= 10^4\n * \tAll elements in nums are distinct.\n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int tupleSameProduct(vector<int>& nums) {\n        unordered_map<int, int> stat;\n        for(int i = 0; i < nums.size(); i++) {\n            for ( int j = i+1; j < nums.size(); j++) {\n                stat[nums[i]*nums[j]]++;\n            }\n        }\n        \n        int result = 0;\n        for ( auto [n, cnt] : stat) {\n            if (cnt > 1) result += cnt*2 * (cnt-1)*2;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/twoArraysEqualByReversingSubArrays/MakeTwoArraysEqualByReversingSubArrays.cpp",
    "content": "// Source : https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/\n// Author : Hao Chen\n// Date   : 2020-10-02\n\n/***************************************************************************************************** \n *\n * Given two integer arrays of equal length target and arr.\n * \n * In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make \n * any number of steps.\n * \n * Return True if you can make arr equal to target, or False otherwise.\n * \n * Example 1:\n * \n * Input: target = [1,2,3,4], arr = [2,4,1,3]\n * Output: true\n * Explanation: You can follow the next steps to convert arr to target:\n * 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n * 2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n * 3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\n * There are multiple ways to convert arr to target, this is not the only way to do so.\n * \n * Example 2:\n * \n * Input: target = [7], arr = [7]\n * Output: true\n * Explanation: arr is equal to target without any reverses.\n * \n * Example 3:\n * \n * Input: target = [1,12], arr = [12,1]\n * Output: true\n * \n * Example 4:\n * \n * Input: target = [3,7,9], arr = [3,7,11]\n * Output: false\n * Explanation: arr doesn't have value 9 and it can never be converted to target.\n * \n * Example 5:\n * \n * Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]\n * Output: true\n * \n * Constraints:\n * \n * \ttarget.length == arr.length\n * \t1 <= target.length <= 1000\n * \t1 <= target[i] <= 1000\n * \t1 <= arr[i] <= 1000\n ******************************************************************************************************/\nclass Solution {\npublic:\n    // This problem could transfer to check two array has exactly same numbers\n    bool canBeEqual(vector<int>& target, vector<int>& arr) {\n       \n       \n        int len1 = target.size();\n        int len2 = arr.size();\n        if (len1 != len2) return false;\n        if (len1 == 0) return true;\n        \n        unordered_map<int, int> stat;\n        for (int i=0; i<len1; i++) {\n            stat[target[i]]++;\n            stat[arr[i]]--;\n        }\n        \n        for (auto& s:stat) {\n            if (s.second !=0 ) return false;\n        }\n        return true;\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/twoCityScheduling/TwoCityScheduling.cpp",
    "content": "// Source : https://leetcode.com/problems/two-city-scheduling/\n// Author : Hao Chen\n// Date   : 2019-04-21\n\n/***************************************************************************************************** \n *\n * There are 2N people a company is planning to interview. The cost of flying the i-th person to city \n * A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].\n * \n * Return the minimum cost to fly every person to a city such that exactly N people arrive in each \n * city.\n * \n * Example 1:\n * \n * Input: [[10,20],[30,200],[400,50],[30,20]]\n * Output: 110\n * Explanation: \n * The first person goes to city A for a cost of 10.\n * The second person goes to city A for a cost of 30.\n * The third person goes to city B for a cost of 50.\n * The fourth person goes to city B for a cost of 20.\n * \n * The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n * \n * Note:\n * \n * \t1 <= costs.length <= 100\n * \tIt is guaranteed that costs.length is even.\n * \t1 <= costs[i][0], costs[i][1] <= 1000\n ******************************************************************************************************/\n\n\nclass Solution {\nprivate:\n    static int diff(vector<int>& x) {\n        return x[1] - x[0];\n    }\n    static bool cmpfunc(vector<int>& lhs, vector<int>& rhs) {\n        return diff(lhs) > diff(rhs);\n    }\n\npublic:\n    // Just simply sort the array by comparing the different cost go to A city and B city\n    // then the bigger difference would be in left and right side, and the smaller difference would be in the middle\n    // We could simply let the first half go to A city, and the second half go to B city.\n    int twoCitySchedCost(vector<vector<int>>& costs) {\n        sort(costs.begin(), costs.end(), cmpfunc);\n        int result = 0;\n        int len = costs.size();\n        for (int i=0; i<len/2; i++) {\n            result += (costs[i][0] + costs[len-i-1][1]);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/twoSum/twoSum.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/\n// Author : Hao Chen\n// Date   : 2014-12-25\n\n/********************************************************************************** \n* \n* Given an array of integers that is already sorted in ascending order, \n* find two numbers such that they add up to a specific target number.\n* \n* The function twoSum should return indices of the two numbers such that they add up to the target, \n* where index1 must be less than index2. Please note that your returned answers (both index1 and index2) \n* are not zero-based.\n* \n* You may assume that each input would have exactly one solution.\n* \n* Input: numbers={2, 7, 11, 15}, target=9\n* Output: index1=1, index2=2 \n* \n**********************************************************************************/\n\n\n\nclass Solution {\npublic:\n    vector<int> twoSum(vector<int> &numbers, int target) {\n        vector<int> result;\n        int low=0, high = numbers.size()-1;\n        while (low < high){\n            if (numbers[low] + numbers[high] == target){\n                result.push_back(low+1);\n                result.push_back(high+1);\n                return result;\n            }else{\n                numbers[low] + numbers[high] > target ? high-- : low++;\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/twoSum/twoSum.III.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/\n// Author : Hao Chen\n// Date   : 2014-12-29\n\n/********************************************************************************** \n* \n* Design and implement a TwoSum class. It should support the following operations: add and find.\n* \n* add - Add the number to an internal data structure.\n* find - Find if there exists any pair of numbers which sum is equal to the value.\n* \n* For example,\n*\n*   add(1); add(3); add(5);\n*   find(4) -> true\n*   find(7) -> false\n* \n**********************************************************************************/\n\nclass TwoSum {\n    private:\n        unordered_map<int, int> nums;\n    public:\n\n        //O(1) add\n        void add(int number) {\n            nums[number]++;\n        }\n\n        //O(n) find\n        bool find(int value) {\n            int one, two;\n            for(auto it = nums.begin(); it != nums.end(); it++){\n                one = it->first;\n                two = value - one;\n                if ( (one == two && it->second > 1) ||\n                        (one != two && nums.find(two) != nums.end() ) ){\n                    return true;\n                }\n            }\n            return false;\n        }\n};\n"
  },
  {
    "path": "algorithms/cpp/twoSum/twoSum.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/two-sum/\n// Author : Hao Chen\n// Date   : 2014-06-17\n\n/********************************************************************************** \n* \n* Given an array of integers, find two numbers such that they add up to a specific target number.\n* \n* The function twoSum should return indices of the two numbers such that they add up to the target, \n* where index1 must be less than index2. Please note that your returned answers (both index1 and index2) \n* are not zero-based.\n* \n* You may assume that each input would have exactly one solution.\n* \n* Input: numbers={2, 7, 11, 15}, target=9\n* Output: index1=1, index2=2\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    /*\n     *   The easy solution is O(n^2) run-time complexity.\n     *   ```\n     *       foreach(item1 in array) {\n     *           foreach(item2 in array){\n     *               if (item1 + item2 == target) {\n     *                   return result\n     *               }\n     *           }\n     *   ```\n     *   \n     *   We can see the nested loop just for searching, \n     *   So, we can use a hashmap to reduce the searching time complexity from O(n) to O(1)\n     *   (the map's `key` is the number, the `value` is the position)\n     *   \n     *   But be careful, if there are duplication numbers in array, \n     *   how the map store the positions for all of same numbers?\n     *\n     */\n\n\n    //\n    // The implementation as below is bit tricky. but not difficult to understand\n    //\n    //  1) Traverse the array one by one\n    //  2) just put the `target - num[i]`(not `num[i]`) into the map\n    //     so, when we checking the next num[i], if we found it existed in the map,\n    //     it means we found the second one.\n    //      \n    vector<int> twoSum(vector<int> &numbers, int target) {\n        unordered_map<int, int> m;\n        vector<int> result;\n        for(int i=0; i<numbers.size(); i++){\n            // not found the second one\n            if (m.find(numbers[i])==m.end() ) { \n                // store the first one position into the second one's key\n                m[target - numbers[i]] = i; \n            }else { \n                // found the second one\n                result.push_back(m[numbers[i]]+1);\n                result.push_back(i+1);\n                break;\n            }\n        }\n        return result;\n    }\n\n    // we also can store nums[i] into map, and find target - nums[i]\n    vector<int> twoSum(vector<int>& nums, int target) {\n        unordered_map<int, int> m;\n        vector<int> result;\n        for (int i=0; i<nums.size(); i++) {\n            if ( m.find(target - nums[i]) == m.end() ) {\n                m[nums[i]] = i;\n            }else{\n                result.push_back(m[target - nums[i]]);\n                result.push_back(i);\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/uglyNumber/UglyNumber.II.cpp",
    "content": "// Source : https://leetcode.com/problems/ugly-number-ii/\n// Author : Hao Chen\n// Date   : 2015-10-21\n\n/*************************************************************************************** \n *\n * Write a program to find the n-th ugly number.\n * \n * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For \n * example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.\n * \n * Note that 1 is typically treated as an ugly number.\n * \n *   The naive approach is to call isUgly for every number until you reach the nth one. \n * Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.\n *\n *   An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.\n *\n *   The key is how to maintain the order of the ugly numbers. Try a similar approach \n * of merging from three sorted lists: L1, L2, and L3.\n *\n *   Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 \n * * 5).\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\nclass Solution {\npublic:\n\n    int min(int a, int b) {\n        return a < b ? a:b;\n    }\n    \n    int min(int a, int b, int c) {\n        return min( min(a, b),  c);\n    }\n\n    //  \n    // The idea is we generate the ugly number instead of checking every number.\n    //\n    // To generate the next ugly number, we can use the existed ugly numbers to multipy 2,3,5,\n    // and get the minimal one.\n    //\n    //     Let's start from the first ugly number - [1]\n    //\n    //        [1]  next = min( 1*2=2, 1*3=3, 1*5=5) = 2\n    //\n    //     Now we have [1,2], we can see, only the second one need be multipied by 2\n    //     but both 3 and 5 still need be multipied by first one. So:\n    // \n    //        [1,2]  next = min(2*2=4, 1*3=3, 1*5=5) = 3\n    //\n    //     Now we have [1,2,3], we can see the second one need be mulityped by 2 and 3,\n    //     but the 5 still needs be multipied by first one. So:\n    //\n    //        [1,2,3]  next = min (2*2, 2*3, 1*5) = 4\n    //\n    //     and so on...\n    //\n    // So, we can see we need to maintain three indics in ugly number list, \n    // each one represents the place need be mulipied by 2,3,5.\n    //\n    // And we increase the index who's multiplication is the minimal. \n    //\n    \n    int nthUglyNumber01(int n) {\n            \n        int i=0, j=0, k=0;\n        vector<int> v(1,1);\n        \n        while(v.size() < n){\n            int next = min(v[i]*2, v[j]*3, v[k]*5);\n            if (next == v[i]*2) i++;\n            if (next == v[j]*3) j++;\n            if (next == v[k]*5) k++;\n            v.push_back(next);\n        }\n        return v.back();\n    }\n    \n    // This version just uses the static variable to cache \n    // the 3 indics and the ugly number list\n    int nthUglyNumber02(int n) {\n            \n        static int i=0, j=0, k=0;\n        static vector<int> v(1,1);\n    \n        if (v.size()>=n) return v[n-1];\n        \n        while(v.size() < n){\n            int next = min(v[i]*2, v[j]*3, v[k]*5);\n            if (next == v[i]*2) i++;\n            if (next == v[j]*3) j++;\n            if (next == v[k]*5) k++;\n            v.push_back(next);\n        }\n        return v.back();\n    }\n    \n    int nthUglyNumber(int n) {\n        return nthUglyNumber02(n); // 4ms-8ms\n        return nthUglyNumber01(n); // 28ms\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/uglyNumber/UglyNumber.cpp",
    "content": "// Source : https://leetcode.com/problems/ugly-number/\n// Author : Hao Chen\n// Date   : 2015-10-21\n\n/*************************************************************************************** \n *\n * Write a program to check whether a given number is an ugly number.\n * \n * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For \n * example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.\n * \n * Note that 1 is typically treated as an ugly number.\n * \n * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating \n * all test cases.\n *               \n ***************************************************************************************/\n\nclass Solution {\npublic:\n    //greeting algorithm\n    bool isUgly(int num) {\n        if ( num == 0 ) return false;\n        if ( num == 1 ) return true;\n        //becasue the 2,3,5 are prime numbers, so, we just simply remove each factors \n        //by keeping dividing them one by one \n        while ( num % 2 == 0 ) num /= 2;\n        while ( num % 3 == 0 ) num /= 3;\n        while ( num % 5 == 0 ) num /= 5;\n        \n        return num == 1;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/unique-binary-search-trees-ii/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.\n* \n* For example,\n* Given n = 3, your program should return all 5 unique BST's shown below.\n* \n*    1         3     3      2      1\n*     \\       /     /      / \\      \\\n*      3     2     1      1   3      2\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <vector>\nusing namespace std;\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nvector<TreeNode*> generateTrees(int low, int high);\n\nvector<TreeNode*> generateTrees(int n) {\n\n    vector<TreeNode*> v;\n    v = generateTrees(1, n);\n    return v;\n}\n\nvector<TreeNode*> generateTrees(int low, int high){\n    vector<TreeNode*> v;\n    if (low > high || low<=0 || high<=0){\n        v.push_back(NULL);\n        return v;\n    }\n    if (low==high){\n        TreeNode* node = new TreeNode(low);\n        v.push_back(node); \n        return v;\n    }\n    for (int i=low; i <= high; i++){\n        vector<TreeNode*> vleft = generateTrees(low, i-1);\n        vector<TreeNode*> vright = generateTrees(i+1, high);\n        for (int l=0; l<vleft.size(); l++){\n            for (int r=0; r<vright.size(); r++){\n                TreeNode *root = new TreeNode(i);\n                root->left = vleft[l];\n                root->right = vright[r];\n                v.push_back(root);\n            }\n        }\n    }\n    return v;\n}\n\nvoid printTree(TreeNode *root){\n    if (root == NULL){\n        printf(\"# \");\n        return;\n    }\n    printf(\"%d \", root->val );\n\n    printTree(root->left);\n    printTree(root->right);\n}\n\n\nint main(int argc, char** argv) \n{\n    int n=2;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    vector<TreeNode*> v = generateTrees(n);\n    for(int i=0; i<v.size(); i++){\n        printTree(v[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/unique-binary-search-trees/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Given n, how many structurally unique BST's (binary search trees) that store values 1...n?\n* \n* For example,\n* Given n = 3, there are a total of 5 unique BST's.\n* \n*    1         3     3      2      1\n*     \\       /     /      / \\      \\\n*      3     2     1      1   3      2\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint numTrees1(int n) ;\nint numTrees2(int n) ;\n\nint numTrees(int n) {\n    return numTrees1(n);\n}\n\nint numTrees1(int n) {\n    int *cnt = (int*)malloc((n+1)*sizeof(int));\n    memset(cnt, 0, (n+1)*sizeof(int));\n    cnt[0] = 1;\n    cnt[1] = 1;\n    \n    for (int i=2; i<=n; i++){\n        for(int j=0; j<i; j++){\n           cnt[i] += cnt[j]*cnt[i-j-1];\n        }\n    }\n    int sum = cnt[n];\n    free(cnt);\n    return sum;\n}\n\n\n\nint numTrees2(int n) {\n    if (n<=0) return 0;\n    if (n == 1 ) return 1;\n    int sum=0;\n    for (int i=1; i<=n; i++){\n        if (i==1||i==n){\n            sum += numTrees(n-1);\n        }else{\n            sum += (numTrees(i-1) * numTrees(n-i));\n        }\n    }\n    return sum;\n}\n\n\nint main(int argc, char** argv) \n{\n    int n=2;\n    if (argc>1){\n        n = atoi(argv[1]);\n    }\n    printf(\"%d=%d\\n\", n, numTrees(n));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/uniqueEmailAddresses/UniqueEmailAddresses.cpp",
    "content": "// Source : https://leetcode.com/problems/unique-email-addresses/\n// Author : Hao Chen\n// Date   : 2020-07-26\n\n/***************************************************************************************************** \n *\n * Every email consists of a local name and a domain name, separated by the @ sign.\n * \n * For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.\n * \n * Besides lowercase letters, these emails may contain '.'s or '+'s.\n * \n * If you add periods ('.') between some characters in the local name part of an email address, mail \n * sent there will be forwarded to the same address without dots in the local name.  For example, \n * \"alice.z@leetcode.com\" and \"alicez@leetcode.com\" forward to the same email address.  (Note that \n * this rule does not apply for domain names.)\n * \n * If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. \n * This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to \n * my@email.com.  (Again, this rule does not apply for domain names.)\n * \n * It is possible to use both of these rules at the same time.\n * \n * Given a list of emails, we send one email to each address in the list.  How many different \n * addresses actually receive mails? \n * \n * Example 1:\n * \n * Input: \n * [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"\n * ]\n * Output: 2\n * Explanation: \"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails\n * \n * Note:\n * \n * \t1 <= emails[i].length <= 100\n * \t1 <= emails.length <= 100\n * \tEach emails[i] contains exactly one '@' character.\n * \tAll local and domain names are non-empty.\n * \tLocal names do not start with a '+' character.\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int numUniqueEmails(vector<string>& emails) {\n        unordered_map<string, int> dict;\n        for (auto& email : emails) {\n            string addr;\n\n            for(int i=0; i<email.size(); i++) {\n                if (email[i] == '.' ) continue;\n\n                if (email[i] == '+') {\n                    while( email[++i] != '@');\n                }\n                if (email[i] =='@') {\n                    addr += email.substr(i);\n                    break;\n                }\n                addr += email[i];\n            }\n\n            dict[addr]++;\n        }\n        return dict.size();\n    }\n\n};\n"
  },
  {
    "path": "algorithms/cpp/uniqueMorseCodeWords/UniqueMorseCodeWords.cpp",
    "content": "// Source : https://leetcode.com/problems/unique-morse-code-words/description/\n// Author : Hao Chen\n// Date   : 2018-06-29\n\n/*************************************************************************************** \n *\n * International orse Code defines a standard encoding where each letter is mapped to \n * a series of dots and dashes, as follows: \"a\" maps to \".-\", \"b\" maps to \"-...\", \"c\" \n * maps to \"-.-.\", and so on.\n * \n * For convenience, the full table for the 26 letters of the English alphabet is given \n * below:\n * \n * \n * [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\n * \"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n * \n * Now, given a list of words, each word can be written as a concatenation of the orse \n * code of each letter. For example, \"cab\" can be written as \"-.-.-....-\", (which is \n * the concatenation \"-.-.\" + \"-...\" + \".-\"). We'll call such a concatenation, the \n * transformation of a word.\n * \n * Return the number of different transformations among all words we have.\n * \n * \n * Example:\n * Input: words = [\"gin\", \"zen\", \"gig\", \"msg\"]\n * Output: 2\n * Explanation: \n * The transformation of each word is:\n * \"gin\" -> \"--...-.\"\n * \"zen\" -> \"--...-.\"\n * \"gig\" -> \"--...--.\"\n * \"msg\" -> \"--...--.\"\n * \n * There are 2 different transformations, \"--...-.\" and \"--...--.\".\n * \n * \n *  \n * \n * Note:\n * \n * \n * \tThe length of words will be at most 100.\n * \tEach words[i] will have length in range [1, 12].\n *     words[i] will only consist of lowercase letters.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n    int uniqueMorseRepresentations(vector<string>& words) {\n        \n        string MorseTable[26] = {\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\n                                 \"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\n                                 \"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\n                                 \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n        unordered_map<string, bool> transformations;\n        for (auto word : words) {\n            string morse;\n            for (auto ch : word) {\n                morse += MorseTable[ ch - 'a' ];\n            }\n            transformations[morse]=true;\n        }\n        return transformations.size();\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp",
    "content": "// Source : https://leetcode.com/problems/unique-number-of-occurrences/\n// Author : Manu Gond\n// Date   : 2019-10-06\n\n/***************************************************************************************************** \n*\tGiven an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.\n*\t\n*\t \n*\n*\tExample 1:\n*\t\n*\tInput: arr = [1,2,2,1,1,3]\n*\tOutput: true\n*\tExplanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n*\tExample 2:\n*\t\n*\tInput: arr = [1,2]\n*\tOutput: false\n*\tExample 3:\n*\t\n*\tInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\n*\tOutput: true\n*\t \n*\t\n*\tConstraints:\n*\t\n*\t1 <= arr.length <= 1000\n*\t-1000 <= arr[i] <= 1000\n ******************************************************************************************************/\n class Solution {\npublic:\n    bool uniqueOccurrences(vector<int>& arr) {\n        map<int,int>myMap;\n        for(int i=0;i<arr.size();i++){\n            myMap[arr[i]]++;\n        }\n        int temp=0;\n        vector<int>v;\n        for (auto i : myMap) {\n            v.push_back(i.second);\n        }\n        sort(v.begin(),v.end());\n        for(int i=0;i<v.size();i++){\n            if(v[i]==temp)\n                return false;\n            else\n                temp=v[i];\n        }\n        return true;\n             \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/uniquePaths/UniquePaths.III.cpp",
    "content": "// Source : https://leetcode.com/problems/unique-paths-iii/\n// Author : Hao Chen\n// Date   : 2019-02-03\n\n/***************************************************************************************************** \n *\n * On a 2-dimensional grid, there are 4 types of squares:\n * \n * \t1 represents the starting square.  There is exactly one starting square.\n * \t2 represents the ending square.  There is exactly one ending square.\n * \t0 represents empty squares we can walk over.\n * \t-1 represents obstacles that we cannot walk over.\n * \n * Return the number of 4-directional walks from the starting square to the ending square, that walk \n * over every non-obstacle square exactly once.\n * \n * Example 1:\n * \n * Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n * Output: 2\n * Explanation: We have the following two paths: \n * 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n * 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n * \n * Example 2:\n * \n * Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n * Output: 4\n * Explanation: We have the following four paths: \n * 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n * 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n * 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n * 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n * \n * Example 3:\n * \n * Input: [[0,1],[2,0]]\n * Output: 0\n * Explanation: \n * There is no path that walks over every empty square exactly once.\n * Note that the starting and ending square can be anywhere in the grid.\n * \n * Note:\n * \n * \t1 <= grid.length * grid[0].length <= 20\n * \n ******************************************************************************************************/\nclass Solution {\npublic:\n    int uniquePathsIII(vector<vector<int>>& grid) {\n        \n        int path = 0;\n        int startX, startY;\n\tif (!findStartPoint( grid, startX, startY)) return 0;\n        uniquePathsHelper(grid, startX, startY, path);\n        return path;\n    }\n    \n    bool findStartPoint(vector<vector<int>> &grid, int& x, int& y) {\n         for(int i=0; i<grid.size(); i++) {\n            for(int j=0; j<grid[0].size(); j++) {\n                if (grid[i][j] == 1) {\n                    x = i; y =j;\n                    return true;\n                }\n            }\n         }\n        return false;\n    }\n    bool check(vector<vector<int>> &grid ) {\n        for(int i=0; i<grid.size(); i++) {\n            for(int j=0; j<grid[0].size(); j++) {\n                if (grid[i][j]  == 0 ) return false;\n            }\n        }\n        return true;\n    }\n    \n    \n    void uniquePathsHelper(vector<vector<int>> &grid, int x, int y, int& path ) {\n        \n        if (x < 0 || y < 0 || x>= grid.size() || y>=grid[0].size()) return;\n        \n        if ( grid[x][y] < 0)  return;\n \n        if ( grid[x][y] == 2) {  \n            if (check(grid)) path++;\n            return;\n        }\n        \n        //back tracing - mark -2 means already passed.\n        grid[x][y] = -2;\n        uniquePathsHelper(grid, x, y-1, path); // up\n        uniquePathsHelper(grid, x, y+1, path); // down\n        uniquePathsHelper(grid, x+1, y, path); // right\n        uniquePathsHelper(grid, x-1, y, path); // left\n        grid[x][y] = 0;\n    \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/uniquePaths/uniquePaths.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/unique-paths-ii/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n* \n* Follow up for \"Unique Paths\":\n* \n* Now consider if some obstacles are added to the grids. How many unique paths would there be?\n* \n* An obstacle and empty space is marked as 1 and 0 respectively in the grid.\n* \n* For example,\n* There is one obstacle in the middle of a 3x3 grid as illustrated below.\n* \n* [\n*   [0,0,0],\n*   [0,1,0],\n*   [0,0,0]\n* ]\n* \n* The total number of unique paths is 2.\n* \n* Note: m and n will be at most 100.\n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n//As same as DP solution with \"Unique Path I\", just need to consider the obstacles.\nint uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n    vector<vector<unsigned int>>  v (row, vector<unsigned int>(col, 0));\n    unsigned int max=0;\n    for (int i=0; i<obstacleGrid.size(); i++){\n        for (int j=0; j<obstacleGrid[0].size(); j++){\n            if(obstacleGrid[i][j] == 1){\n                max = v[i][j] = 0;\n            } else {\n                if (i>0 && j>0) {\n                    max= v[i][j] = v[i-1][j] + v[i][j-1];\n                }else if(i>0){\n                    max = v[i][j] = v[i-1][j];\n                }else if(j>0){\n                    max = v[i][j] = v[i][j-1];\n                }else{\n                    max = v[i][j] = 1 ;\n                }\n            }\n        }\n    }\n    return max;\n}\n\n// the previous implemetation has too many if-else\n// the following dynamic programming is much more easy to read\nint uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n    int row = obstacleGrid.size();\n    int col = obstacleGrid[0].size();\n\n    vector< vector <unsigned int> >  dp (row, vector<unsigned int>(col, 0));\n\n    dp[0][0] =  obstacleGrid[0][0]  ?  0 : 1;\n    for (int r=1; r<row; r++) {\n        dp[r][0] = obstacleGrid[r][0]  ?  0 : dp[r-1][0];\n    }\n    for (int c=1; c<col; c++) {\n        dp[0][c] = obstacleGrid[0][c]  ?  0 : dp[0][c-1];\n    }\n\n    for (int r=1; r<row; r++) {\n        for (int c=1; c<col; c++) {\n            dp[r][c]  = obstacleGrid[r][c] == 1 ? 0 : dp[r][c-1] + dp[r-1][c];\n        }\n    }\n\n    return dp[row-1][col-1];\n}\n\n\n"
  },
  {
    "path": "algorithms/cpp/uniquePaths/uniquePaths.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/unique-paths/\n// Author : Hao Chen\n// Date   : 2014-06-25\n\n/********************************************************************************** \n * \n * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).\n * \n * The robot can only move either down or right at any point in time. The robot is trying to reach \n * the bottom-right corner of the grid (marked 'Finish' in the diagram below).\n *    \n *    \n *    start                                                  \n *    +---------+----+----+----+----+----+                   \n *    |----|    |    |    |    |    |    |                   \n *    |----|    |    |    |    |    |    |                   \n *    +----------------------------------+                   \n *    |    |    |    |    |    |    |    |                   \n *    |    |    |    |    |    |    |    |                   \n *    +----------------------------------+                   \n *    |    |    |    |    |    |    |----|                   \n *    |    |    |    |    |    |    |----|                   \n *    +----+----+----+----+----+---------+                   \n *                                   finish                  \n *    \n * \n * How many possible unique paths are there?\n * \n * Above is a 3 x 7 grid. How many possible unique paths are there?\n * \n * Note: m and n will be at most 100.\n *               \n **********************************************************************************/\n\n#ifdef CSTYLE\n\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid printMatrix(int*a, int m, int n)\n{\n    for (int i=0; i<m; i++){\n        for (int j=0; j<n; j++){\n            printf(\"%4d \", a[i*n+j]);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"\\n\");\n}\n\n/*\n * Dynamic Programming\n *\n * We have a dp[i][j] represents  how many paths from [0][0] to hear. So, we have the following DP formuler:\n *\n *    dp[i][j] =  1  if i==0 || j==0        //the first row/column only have 1 uniqe path.\n *             =  dp[i-1][j] + dp[i][j-1]   //the path can be from my top cell and left cell.\n */\n\n// using C style array\nint uniquePaths(int m, int n) {\n    int* matrix = new int[m*n];\n    printMatrix(matrix, m, n);\n    for (int i=0; i<m; i++){\n        for (int j=0; j<n; j++){\n            if(i==0 || j==0){\n                matrix[i*n+j]=1;\n            }else{\n                matrix[i*n+j] = matrix[(i-1)*n+j] + matrix[i*n+j-1];\n            }\n        }\n    } \n    printMatrix(matrix, m, n);\n    int u = matrix[m*n-1];\n    delete[] matrix;\n    return u;\n}\n\n#else\n\n#include <vector>\nusing namespace std;\n\n// using C++ STL vector , the code is much easy to read\nint uniquePaths(int m, int n) {\n    vector< vector <int> >  dp (n, vector<int>(m, 1));\n    for (int row=1; row<n; row++) {\n        for (int col=1; col<m; col++) {\n            dp[row][col] = dp[row-1][col] + dp[row][col-1];\n        }\n    }\n    return dp[n-1][m-1];\n}\n\n#endif\n\nint main(int argc, char** argv)\n{\n    int m=3, n=7;\n    if( argc>2){\n        m = atoi(argv[1]);\n        n = atoi(argv[2]);\n    }\n\n    printf(\"uniquePaths=%d\\n\", uniquePaths(m,n));\n    return  0;\n}\n"
  },
  {
    "path": "algorithms/cpp/validNumber/validNumber.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/valid-number/\n// Author : Hao Chen\n// Date   : 2014-08-26\n\n/********************************************************************************** \n* \n* Validate if a given string is numeric.\n* \n* Some examples:\n* \"0\" => true\n* \"   0.1  \" => true\n* \"abc\" => false\n* \"1 a\" => false\n* \"2e10\" => true\n* \n* Note: It is intended for the problem statement to be ambiguous. \n*       You should gather all requirements up front before implementing one.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\nusing namespace std;\n\n\nbool isdigit(const char c){\n    return (c>='0' && c<='9');\n}\nbool isspace(const char c) {\n    return (c==' ' || c =='\\t' || c=='\\n' || c=='\\r' || c=='\\f' || c=='\\v');\n}\n\nbool isNumber(const char *s) {\n    bool point = false;\n    bool hasE = false;\n    \n    //trim the space\n    while(isspace(*s)) s++;\n    //check empty \n    if (*s == '\\0' ) return false;\n    //check sign\n    if (*s=='+' || *s=='-') s++;\n\n    const char *head  = s;\n    for(; *s!='\\0'; s++){\n        // if meet point\n        if ( *s == '.' ){\n            if ( hasE == true || point == true){\n                return false;\n            }\n            if ( s == head && !isdigit(*(s+1))  ){\n                return false;\n            }\n            point = true; \n            continue; \n        }\n        //if meet \"e\"\n        if ( *s == 'e' ){\n            if ( hasE == true || s == head) {\n                return false;\n            }\n            s++;\n            if ( *s=='+' || *s=='-' )  s++;\n            if ( !isdigit(*s) ) return false;\n      \n            hasE = true; \n            continue; \n        }\n        //if meet space, check the rest chars are space or not\n        if (isspace(*s)){\n            for (; *s != '\\0'; s++){\n                if (!isspace(*s)) return false;\n            }\n            return true;\n        }\n        if ( !isdigit(*s) ) {\n            return false;\n        }\n       \n    }\n    \n    return true; \n}\n\n\n#define TEST(s) cout << \"\\\"\" << s << \"\\\"\" << \" : \" << isNumber(s) << endl\nint main(int argc, char** argv)\n{\n    const char* s=\"123\";\n    if(argc>1){\n        s = argv[1];\n    }\n    TEST(s);\n\n    TEST(\"1.044\");\n    TEST(\" 1.044 \");\n    TEST(\"1.a\");\n    TEST(\"abc\");\n    TEST(\"e\");\n    TEST(\"1e\");\n    TEST(\"1e2\");\n    TEST(\"\");\n    TEST(\" \");\n    TEST(\"1.\");\n    TEST(\".2\");\n    TEST(\" . \");\n    TEST(\".\");\n    TEST(\"1.2.3\");\n    TEST(\"1e2e3\");\n    TEST(\"1..\");\n    TEST(\"+1.\");\n    TEST(\" -1.\");\n    TEST(\"6e6.5\");\n    TEST(\"005047e+6\");\n    \n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/validPalindrome/validPalindrome.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/valid-palindrome/\n// Author : Hao Chen\n// Date   : 2014-06-26\n\n/********************************************************************************** \n* \n* Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n* \n* For example,\n* \"A man, a plan, a canal: Panama\" is a palindrome.\n* \"race a car\" is not a palindrome.\n* \n* Note:\n* Have you consider that the string might be empty? This is a good question to ask during an interview.\n* \n* For the purpose of this problem, we define empty string as valid palindrome.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    bool isPalindrome(string s) {\n        s = removeNoise(s);\n        for(int i=0; i<s.size()/2; i++){\n            if (s[i]!= s[s.size()-i-1]){\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    string removeNoise(string& s){\n        string d;\n        for(int i=0; i<s.size(); i++){\n            if(::isalpha(s[i]) || ::isdigit(s[i])){\n                d.push_back(::tolower(s[i]));\n            }\n        }\n        return d;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/validParentheses/validParentheses.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/valid-parentheses/\n// Author : Hao Chen\n// Date   : 2014-06-30\n\n/********************************************************************************** \n* \n* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', \n* determine if the input string is valid.\n* \n* The brackets must close in the correct order, \"()\" and \"()[]{}\" are all valid \n* but \"(]\" and \"([)]\" are not.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\n#include <stack>\nusing namespace std;\n\nbool isValid(string s) {\n    stack<char> st;\n    for(auto ch : s) {\n        if (ch=='{' || ch =='[' || ch=='(' ) {\n            st.push(ch);\n        }else if (ch=='}' || ch ==']' || ch == ')' ){\n            if (st.empty()) return false;\n            char sch = st.top();\n            if ( (sch=='{' && ch =='}') || (sch=='[' && ch==']') || (sch=='(' && ch==')' ) ){\n                st.pop();\n            }else {\n                return false;\n            }\n        }else{\n            return false;\n        }\n    }\n    return st.empty();\n}\n\nint main(int argc, char**argv)\n{\n    string s = \"{{}{[]()}}\";\n    if (argc>1){\n        s = argv[1];\n    }\n    cout << \"str = \\\"\" << (s) << \"\\\"\" << endl;\n    cout << isValid(s) << endl;\n}\n"
  },
  {
    "path": "algorithms/cpp/validPerfectSquare/ValidPerfectSquare.cpp",
    "content": "// Source : https://leetcode.com/problems/valid-perfect-square/description/\n// Author : Hao Chen\n// Date   : 2018-06-26\n\n/*************************************************************************************** \n *\n * Given a positive integer num, write a function which returns True if num is a \n * perfect square else False.\n * \n * \n * Note: Do not use any built-in library function such as sqrt.\n * \n * \n * Example 1:\n * \n * Input: 16\n * Returns: True\n * \n * \n * \n * Example 2:\n * \n * Input: 14\n * Returns: False\n * \n * \n * \n * Credits:Special thanks to @elmirap for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\nclass Solution {\npublic:\n    // time limited error for  the MAX_INT.\n    bool isPerfectSquare1(int num) {\n        //binary searching...\n        int left = 0, right = num;\n        \n        while (left <= right) {\n            //cout << left << \",\" << right << endl;\n            int mid = left + (right - left)/2;\n            int n = mid * mid;\n            if ( n == num) return true;\n            if ( n < num ) left = mid + 1;\n            else right = mid - 1;\n        }\n        \n        return false; \n        \n    }\n    \n    // the stupid way is best & fast.\n    bool isPerfectSquare2(int num) {\n        for (int i=1; i <= num/i ; i++ ) {\n            if ( i*i == num) return true;\n        }\n        \n        return false;\n    }\n    \n    \n    bool isPerfectSquare(int num) {\n        return isPerfectSquare2(num);\n        return isPerfectSquare1(num);\n    }\n    \n};\n"
  },
  {
    "path": "algorithms/cpp/validSudoku/validSudoku.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/valid-sudoku/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.\n* \n* The Sudoku board could be partially filled, where empty cells are filled with the character '.'.\n* \n* A partially filled sudoku which is valid.\n* \n* Note:\n* > A valid Sudoku board (partially filled) is not necessarily solvable. \n*   Only the filled cells need to be validated.\n* \n*               \n**********************************************************************************/\n\nclass Solution {\npublic:\n    bool isValidSudoku(vector<vector<char> > &board) {\n        const int cnt = 9;\n        bool row_mask[cnt][cnt] = {false};\n        bool col_mask[cnt][cnt] = {false};\n        bool area_mask[cnt][cnt] = {false};\n        //check each rows and cols\n        for(int r=0; r<board.size(); r++){\n            for (int c=0; c<board[r].size(); c++){\n                if (!isdigit(board[r][c])) continue;\n                int idx =  board[r][c] - '0' - 1;\n                \n                //check the rows\n                if (row_mask[r][idx] == true){\n                    return false;\n                }\n                row_mask[r][idx] = true;\n                \n                //check the cols\n                if (col_mask[c][idx] == true) {\n                    return false;\n                }\n                col_mask[c][idx] = true;\n                \n                //check the areas\n                int area = (r/3) * 3 + (c/3);\n                if (area_mask[area][idx] == true) {\n                    return false;\n                }\n                area_mask[area][idx] = true;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/validateBinarySearchTree/validateBinarySearchTree.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/validate-binary-search-tree/\n// Author : Hao Chen\n// Date   : 2014-07-05\n\n/********************************************************************************** \n* \n* Given a binary tree, determine if it is a valid binary search tree (BST).\n* \n* Assume a BST is defined as follows:\n* \n* The left subtree of a node contains only nodes with keys less than the node's key.\n* The right subtree of a node contains only nodes with keys greater than the node's key.\n* Both the left and right subtrees must also be binary search trees.\n* \n* confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n* \n* OJ's Binary Tree Serialization:\n* \n* The serialization of a binary tree follows a level order traversal, where '#' signifies \n* a path terminator where no node exists below.\n* \n* Here's an example:\n* \n*    1\n*   / \\\n*  2   3\n*     /\n*    4\n*     \\\n*      5\n* \n* The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\". \n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nbool isValidBST(TreeNode *root) {\n\n    //travel the tree by inner-order\n    vector<TreeNode*> stack;\n    TreeNode* node = root;\n    vector<int> v;\n    while (stack.size()>0 || node!=NULL) {\n        if (node!=NULL){\n            stack.push_back(node);\n            node = node->left;\n        }else{\n            node = stack.back();\n            stack.pop_back();\n            v.push_back(node->val);\n            node = node->right;\n        }\n    }\n\n    //check the vector wehther sorted or not\n    for(int i=0; v.size()>0 && i<v.size()-1; i++){\n        if (v[i] >= v[i+1]) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\n\nTreeNode* createTree(int a[], int n)\n{\n    if (n<=0) return NULL;\n\n    TreeNode **tree = new TreeNode*[n];\n\n    for(int i=0; i<n; i++) {\n        if (a[i]==0 ){\n            tree[i] = NULL;\n            continue;\n        }\n        tree[i] = new TreeNode(a[i]);\n    }\n    int pos=1;\n    for(int i=0; i<n && pos<n; i++) {\n        if (tree[i]){\n            tree[i]->left = tree[pos++];\n            if (pos<n){\n                tree[i]->right = tree[pos++];\n            }\n        }\n    }\n    return tree[0];\n}\n\n\nint main()\n{\n    cout << isValidBST(NULL) << endl;\n\n    int a[]={1,1};\n    cout << isValidBST(createTree(a, sizeof(a)/sizeof(int))) << endl;\n    \n    int b[]={4,2,6,1,7,5,7};\n    cout << isValidBST(createTree(b, sizeof(b)/sizeof(int))) << endl;\n\n    int c[]={4,2,6,1,3,5,7};\n    cout << isValidBST(createTree(c, sizeof(c)/sizeof(int))) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/verifyPreorderSerializationOfABinaryTree/VerifyPreorderSerializationOfABinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/\n// Author : Hao Chen\n// Date   : 2017-01-06\n\n/*************************************************************************************** \n *\n * One way to serialize a binary tree is to use pre-order traversal. When we encounter \n * a non-null node, we record the node's value. If it is a null node, we record using a \n * sentinel value such as #.\n * \n *      _9_\n *     /   \\\n *    3     2\n *   / \\   / \\\n *  4   1  #  6\n * / \\ / \\   / \\\n * # # # #   # #\n * \n * For example, the above binary tree can be serialized to the string \n * \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where # represents a null node.\n * \n * Given a string of comma separated values, verify whether it is a correct preorder \n * traversal serialization of a binary tree. Find an algorithm without reconstructing \n * the tree.\n * \n * Each comma separated value in the string must be either an integer or a character \n * '#' representing null pointer.\n * \n * You may assume that the input format is always valid, for example it could never \n * contain two consecutive commas such as \"1,,3\".\n * \n * Example 1:\n * \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\n * Return true\n * Example 2:\n * \"1,#\"\n * Return false\n * Example 3:\n * \"9,#,#,1\"\n * Return false\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\npublic:\n\n    // we know the following facts:\n    //   1) if we met a non-null node, then this node will generate two child node.\n    //   2) if we met a null node, then this node will generate zero child node.\n    //\n    // so the idea is, \n    //   1) we can have a counter to calculate how many node we are going to expect \n    //   2) once we have the expected node, then we can decrease the counter.\n    //   3) finally, we will check the counter is zero or not.\n    //\n    // the algorithm as below:\n    //   1) when we meet a non-null node, just simply do `counter++`. because:\n    //      1.1) we will expect 2 more node after, then we do `counter += 2`. \n    //      1.2) but the current node also meet the expection of parent node , so, it need remove 1 in counter.\n    //           finally, the `counter = counbter + 2 -1`\n    //   2) when we meet a null node, just simply do `counter--`.\n    \n    bool isValidSerialization(string preorder) {\n        vector<string> list;\n        split(preorder, ',', list);\n        //we initailize the counter as 1, \n        //because we expect at lease 1 node in the tree.\n        int node_expected = 1;\n        for (auto node : list) {\n            if (node_expected == 0) return false;\n            node == \"#\" ? node_expected-- : node_expected++;\n        }\n        return node_expected == 0;\n    }\n    \n    void split(const string &s, char delim, vector<string> &elems) {\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            elems.push_back(item);\n        }\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/verticalOrderTraversalOfABinaryTree/VerticalOrderTraversalOfABinaryTree.cpp",
    "content": "// Source : https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/\n// Author : Hao Chen\n// Date   : 2019-02-05\n\n/***************************************************************************************************** \n *\n * Given a binary tree, return the vertical order traversal of its nodes values.\n * \n * For each node at position (X, Y), its left and right children respectively will be at positions \n * (X-1, Y-1) and (X+1, Y-1).\n * \n * Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches \n * some nodes, we report the values of the nodes in order from top to bottom (decreasing Y \n * coordinates).\n * \n * If two nodes have the same position, then the value of the node that is reported first is the value \n * that is smaller.\n * \n * Return an list of non-empty reports in order of X coordinate.  Every report will have a list of \n * values of nodes.\n * \n * Example 1:\n *    \n *    \n *          +--+\n *     +----+3 +----+\n *     |    +--+    |\n *     |            |\n *    +--+        +--+\n *    |9 |    +---+20+---+\n *    +--+    |   +--+   |\n *            |          |\n *          +--+       +--+\n *          |15|       |7 |\n *          +--+       +--+\n *    \n * \n * Input: [3,9,20,null,null,15,7]\n * Output: [[9],[3,15],[20],[7]]\n * Explanation: \n * Without loss of generality, we can assume the root node is at position (0, 0):\n * Then, the node with value 9 occurs at position (-1, -1);\n * The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);\n * The node with value 20 occurs at position (1, -1);\n * The node with value 7 occurs at position (2, -2).\n * \n * Example 2:\n * \n *    \n *              +-+\n *              |1|\n *         +-----------+\n *         |           |\n *        +++         +++\n *        |2|         |3|\n *     +--------+  +--------+\n *     |        |  |        |\n *    +++      ++--++      +++\n *    |4|      |5||6|      |7|\n *    +-+      +----+      +-+\n *    \n *    \n * Input: [1,2,3,4,5,6,7]\n * Output: [[4],[2],[1,5,6],[3],[7]]\n * Explanation: \n * The node with value 5 and the node with value 6 have the same position according to the given \n * scheme.\n * However, in the report \"[1,5,6]\", the node value of 5 comes first since 5 is smaller than 6.\n * \n * Note:\n * \n * \tThe tree will have between 1 and 1000 nodes.\n * \tEach node's value will be between 0 and 1000.\n * \n ******************************************************************************************************/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Item {\npublic:\n    Item(int _x, int _y, int _val):x(_x), y(_y),val(_val) {}\n    int x, y;\n    int val;\n};\n\nclass ItemCmp {\npublic:\n    bool operator () (const Item &lhs, const Item &rhs) const {\n        return lhs.y != rhs.y ? lhs.y > rhs.y : lhs.val < rhs.val;\n    }\n};\n\nint getValue(const Item& i) {\n    return i.val;\n}\n\nclass Solution {\npublic:\n    vector<vector<int>> verticalTraversal(TreeNode* root) {\n        set<int> rows;\n        unordered_map<int, set<Item, ItemCmp>> m;\n\n        verticalTraversalHelper(root, 0, 0, rows, m);\n\n        vector<vector<int>> result;\n        for(auto r : rows) {\n            vector<int> v;\n            transform(m[r].begin(), m[r].end(), back_inserter(v), getValue);\n            result.push_back(v);\n        }\n        return result;\n    }\n    void verticalTraversalHelper(TreeNode* root, int x, int y,\n                                 set<int>& rows,\n                                 unordered_map<int, set<Item, ItemCmp>>& m) {\n\n        if ( !root ) return;\n\n        rows.insert(x);\n        m[x].insert(Item(x, y, root->val));\n        verticalTraversalHelper(root->left, x-1, y-1, rows, m); //left\n        verticalTraversalHelper(root->right, x+1, y-1, rows, m); //right\n\n\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/videoStitching/VideoStitching.cpp",
    "content": "// Source : https://leetcode.com/problems/video-stitching/\n// Author : Hao Chen\n// Date   : 2019-10-01\n\n/***************************************************************************************************** \n *\n * You are given a series of video clips from a sporting event that lasted T seconds.  These video \n * clips can be overlapping with each other and have varied lengths.\n * \n * Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time \n * clips[i][1].  We can cut these clips into segments freely: for example, a clip [0, 7] can be cut \n * into segments [0, 1] + [1, 3] + [3, 7].\n * \n * Return the minimum number of clips needed so that we can cut the clips into segments that cover the \n * entire sporting event ([0, T]).  If the task is impossible, return -1.\n * \n * Example 1:\n * \n * Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10\n * Output: 3\n * Explanation: \n * We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\n * Then, we can reconstruct the sporting event as follows:\n * We cut [1,9] into segments [1,2] + [2,8] + [8,9].\n * Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\n * \n * Example 2:\n * \n * Input: clips = [[0,1],[1,2]], T = 5\n * Output: -1\n * Explanation: \n * We can't cover [0,5] with only [0,1] and [0,2].\n * \n * Example 3:\n * \n * Input: clips = \n * [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], \n * T = 9\n * Output: 3\n * Explanation: \n * We can take clips [0,4], [4,7], and [6,9].\n * \n * Example 4:\n * \n * Input: clips = [[0,4],[2,8]], T = 5\n * Output: 2\n * Explanation: \n * Notice you can have extra video after the event ends.\n * \n * Note:\n * \n * \t1 <= clips.length <= 100\n * \t0 <= clips[i][0], clips[i][1] <= 100\n * \t0 <= T <= 100\n * \n ******************************************************************************************************/\n\nclass Solution {\npublic:\n    int videoStitching(vector<vector<int>>& clips, int T) {\n\n        //sort the clips\n        std::sort(clips.begin(), clips.end(), [](vector<int>& x, vector<int>& y) {\n            return x[0] < y[0] || (x[0] == y[0] && x[1] < y[1]);\n        });\n\n        //print(clips);\n\n        // dynamic programming\n        // dp[i] is the minmal clips from [o,i]\n\n        vector<int> dp(T+1, -1);\n        for (auto c : clips) {\n            //edge case: out of the range\n            if (c[0] > T) continue;\n\n            // if clip is started from 0, then just simple initalize to 1\n            if (c[0] == 0) {\n                for (int i=c[0]; i<=min(T,c[1]); i++) dp[i] = 1;\n                continue;\n            }\n\n            //if clip is not started from 0, seprate the range to two parts\n            //the first part is the greater than 0, then second part is -1\n            // 1) for the first part, need figure the minimal number\n            // 2) for the second part, just simple add 1 with minimal number of first part.\n\n            if (dp[c[0]] == -1 ) continue;\n\n            int m = dp[c[0]];\n\n            for (int i = c[0] + 1; i<= min(T, c[1]); i++) {\n                if ( dp[i] > 0 ) m = min(m, dp[i]);\n                else dp[i] = m + 1;\n            }\n        }\n\n        //print(dp);\n        return dp[T];\n    }\n\n\n\n    //used for debug\n    void print(vector<vector<int>>& clips) {\n        for (auto c : clips) {\n            cout << \"[\" << c[0] <<\",\"<< c[1] << \"]\"<< \" \";\n        }\n        cout << endl;\n    }\n\n    void print(vector<int>& v) {\n        for (auto i : v) {\n            cout << i << \", \";\n        }\n        cout << endl;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/waysToSplitArrayIntoThreeSubarrays/WaysToSplitArrayIntoThreeSubarrays.cpp",
    "content": "// Source : https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/\n// Author : Hao Chen\n// Date   : 2021-05-11\n\n/***************************************************************************************************** \n *\n * A split of an integer array is good if:\n * \n * \tThe array is split into three non-empty contiguous subarrays - named left, mid, right \n * respectively from left to right.\n * \tThe sum of the elements in left is less than or equal to the sum of the elements in mid, \n * and the sum of the elements in mid is less than or equal to the sum of the elements in right.\n * \n * Given nums, an array of non-negative integers, return the number of good ways to split nums. As the \n * number may be too large, return it modulo 10^9 + 7.\n * \n * Example 1:\n * \n * Input: nums = [1,1,1]\n * Output: 1\n * Explanation: The only good way to split nums is [1] [1] [1].\n * \n * Example 2:\n * \n * Input: nums = [1,2,2,2,5,0]\n * Output: 3\n * Explanation: There are three good ways of splitting nums:\n * [1] [2] [2,2,5,0]\n * [1] [2,2] [2,5,0]\n * [1,2] [2,2] [5,0]\n * \n * Example 3:\n * \n * Input: nums = [3,2,1]\n * Output: 0\n * Explanation: There is no good way to split nums.\n * \n * Constraints:\n * \n * \t3 <= nums.length <= 10^5\n * \t0 <= nums[i] <= 10^4\n ******************************************************************************************************/\n\nconst int MOD = (int) (1e9 + 7);\n\nclass Solution {\npublic:\n    int waysToSplit(vector<int>& nums) {\n        int len = nums.size();\n        vector<int> presum(len, 0);\n        presum[0] = nums[0];\n        for(int i=1; i<nums.size(); i++){\n            presum[i] = presum[i-1] + nums[i];\n        }\n        \n        return waysToSplit_BS(presum);  // Binary Search\n        //return waysToSplit_TLE(presum); // Time Limit Error\n    }\n    \n    int binary_search(vector<int>& presum, int left, int i, bool searchLeft ) {\n        int len = presum.size();\n        int l = i, r = len-1;\n        int res = -1;\n        while(l <= r) {\n            int m = l + (r - l) / 2;\n            // if search Left, let middle item belong to left\n            // if search Right, let middle item belong to right\n            int x = searchLeft? 0 : 1; \n            int right = presum[len-1] - presum[m-x];\n            int mid = presum[m-x] - presum[i-1];\n            \n            if (left <= mid && mid <= right) {\n                res = m;\n                if (searchLeft) r = m - 1;\n                else l = m + 1;\n            }else if (left > mid) {\n                l = m + 1;\n            }else {\n                r = m -1;\n            }\n\n        }\n        return res;\n    }\n    int waysToSplit_BS(vector<int>& presum) {\n        int len = presum.size();\n        long cnt = 0;\n        for(int i=0; i<len-2; i++){\n            if (presum[i] > (presum[len-1] - presum[i]) / 2) break;\n            //find the most right position\n            long l = binary_search(presum, presum[i], i+1, true);\n            //find the most right position\n            long r = binary_search(presum, presum[i], i+1, false);\n            if (l == -1 || r == -1 ) continue;\n            cnt += (r-l);\n            //cout << i << \" - [\" << l << \",\" << r << \"]\" << endl;\n        } \n        //cout << endl;\n        return cnt % MOD;\n    }\n    \n    int waysToSplit_TLE(vector<int>& presum) {\n        int len = presum.size();\n        int cnt = 0;\n        int left, mid, right;\n        for(int i=0; i<len-2; i++){\n            left = presum[i];\n            for (int j=i+1; j<len-1; j++) {\n                mid = presum[j] - presum[i];\n                right = presum[len-1] - presum[j];\n                if (left <= mid && mid <= right) {\n                    cnt++;\n                }\n            }\n        } \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/wiggleSort/WiggleSort.II.cpp",
    "content": "// Source : https://leetcode.com/problems/wiggle-sort-ii/\n// Author : Hao Chen\n// Date   : 2017-01-02\n\n/*************************************************************************************** \n *\n * Given an unsorted array nums, reorder it such that\n *     nums[0]  nums[2] .\n * \n *     Example:\n *     (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. \n *     (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].\n * \n *     Note:\n *     You may assume all input has valid answer.\n * \n *     Follow Up:\n *     Can you do it in O(n) time and/or in-place with O(1) extra space?\n * \n * Credits:Special thanks to @dietpepsi for adding this problem and creating all test \n * cases.\n ***************************************************************************************/\n\nclass Solution {\n\npublic:\n    //\n    // Solution - O(N*logN)\n    // --------------------\n    // 1) Sorting the array with descending order\n    //\n    // 2) Split the sorted array into two parts,\n    //    and insert the 2nd half array into the 1st half array\n    //\n    //    For example: [ 9 8 7 6 5  4 3 2 1 0  ]\n    //\n    //  \n    //        1st Large half:    . 9 . 8 . 7 . 6 . 5\n    //        2nd Small half:    4 . 3 . 2 . 1 . 0 .\n    //        ---------------------------------------\n    //                Result:    4 9 3 8 2 7 1 6 0 5\n    //\n    // Be careful if the length of array is odd number, \n    // Such as: [5 4 3 2 1], \n    // The 2nd half is [3 2 1] instead of [2 1]\n    // \n\n    void wiggleSort01(vector<int>& nums) {\n        sort(nums.begin(), nums.end(), [](int x, int y) { return x > y; });\n        int half = (nums.size() / 2);\n        \n        for (int i=0; i<half; i++) {\n            int v = nums[half+i];\n            nums.erase(nums.begin() + half + i );\n            nums.insert(nums.begin() + (2*i), v);\n        }\n        cout << endl;\n    }\n    \n    //\n    // After checked the discussion of Leetcode, I found there is a really brilliant idea\n    // which used a tricky idea - virtual index.\n    // \n    // Please refer to the following link to see the full details:\n    // https://discuss.leetcode.com/topic/32929/o-n-o-1-after-median-virtual-indexing\n    \n    void wiggleSort02(vector<int>& nums) {\n        int n = nums.size();\n        \n        // Find a median.\n        auto midptr = nums.begin() + n / 2;\n        nth_element(nums.begin(), midptr, nums.end());\n        int mid = *midptr;\n        \n        // Index-rewiring.\n        #define A(i) nums[(1+2*(i)) % (n|1)]\n    \n        // 3-way-partition-to-wiggly in O(n) time with O(1) space.\n        int i = 0, j = 0, k = n - 1;\n        while (j <= k) {\n            if (A(j) > mid)\n                swap(A(i++), A(j++));\n            else if (A(j) < mid)\n                swap(A(j), A(k--));\n            else\n                j++;\n        }\n    }\n    void wiggleSort(vector<int>& nums) {\n        return wiggleSort02(nums); //~140ms\n        return wiggleSort01(nums); //~230ms\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp",
    "content": "// Source : https://leetcode.com/problems/wiggle-subsequence/\n// Author : Calinescu Valentin\n// Date   : 2016-08-08\n\n/*************************************************************************************** \n *\n * A sequence of numbers is called a wiggle sequence if the differences between\n * successive numbers strictly alternate between positive and negative. The first\n * difference (if one exists) may be either positive or negative. A sequence with fewer\n * than two elements is trivially a wiggle sequence.\n * \n * For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3)\n * are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are\n * not wiggle sequences, the first because its first two differences are positive and\n * the second because its last difference is zero.\n * \n * Given a sequence of integers, return the length of the longest subsequence that is a\n * wiggle sequence. A subsequence is obtained by deleting some number of elements\n * (eventually, also zero) from the original sequence, leaving the remaining elements in\n * their original order.\n * \n * Examples:\n * Input: [1,7,4,9,2,5]\n * Output: 6\n * The entire sequence is a wiggle sequence.\n * \n * Input: [1,17,5,10,13,15,10,5,16,8]\n * Output: 7\n * There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].\n * \n * Input: [1,2,3,4,5,6,7,8,9]\n * Output: 2\n * \n * Follow up:\n * Can you do it in O(n) time?\n * \n ***************************************************************************************/\n \n /* Solution\n  * --------\n  * 1) O(N)\n  * \n  * We notice that adding a new number to an existing subsequence means finding one that\n  * is smaller or bigger than the previous number, according to the difference between the\n  * previous number and the number before that as we always need to alternate between increasing\n  * and decreasing subsequences. If we encounter increasing or decreasing sequences of 2 or \n  * more consecutive numbers we can treat the entire subsequence as a number, because that way \n  * we can always be sure we don't miss any solution, as finding a number smaller than any \n  * number of an increasing subsequence is guaranteed to be smaller than the biggest number \n  * in the subsequence. Thus, we can only check the difference between consecutive numbers.\n  * \n  * Follow up:\n  * \n  * The time complexity is already O(N).\n  */\nclass Solution {\npublic:\n    int wiggleMaxLength(vector<int>& nums) {\n        int solution = 0;//if we have an empty vector the solution is 0\n        if(nums.size())\n        {\n            solution = 1;\n            int bigger = 0;//0 is the starting point to be followed by either an increasing or decreasing sequence\n            for(int i = 1; i < nums.size(); i++)\n            {\n                if(nums[i] == nums[i - 1])\n                    continue;//we can ignore duplicates as they can always be omitted\n                else if(nums[i] > nums[i - 1])\n                {\n                    if(bigger == 0 || bigger == 2)\n                    {\n                        bigger = 1;//1 means we now have an increasing sequence\n                        solution++;\n                    }\n                }\n                else //if(nums[i] < nums[i - 1])\n                {\n                    if(bigger == 0 || bigger == 1)\n                    {\n                        bigger = 2;//2 means we now have a decreasing sequence\n                        solution++;\n                    }\n                }\n            }\n        }\n        return solution;\n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/wildcardMatching/wildcardMatching.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/wildcard-matching/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n* \n* Implement wildcard pattern matching with support for '?' and '*'.\n* \n* '?' Matches any single character.\n* '*' Matches any sequence of characters (including the empty sequence).\n* \n* The matching should cover the entire input string (not partial).\n* \n* The function prototype should be:\n* bool isMatch(const char *s, const char *p)\n* \n* Some examples:\n* isMatch(\"aa\",\"a\") → false\n* isMatch(\"aa\",\"aa\") → true\n* isMatch(\"aaa\",\"aa\") → false\n* isMatch(\"aa\", \"*\") → true\n* isMatch(\"aa\", \"a*\") → true\n* isMatch(\"ab\", \"?*\") → true\n* isMatch(\"aab\", \"c*a*b\") → false\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <string>\nusing namespace std;\n\n\nbool isMatch(const char *s, const char *p) {\n\n    const char *last_s = NULL; \n    const char *last_p = NULL;\n    while( *s != '\\0' ){\n        if (*p=='*'){\n            //skip the \"*\", and mark a flag\n            p++;\n            //edge case\n            if (*p=='\\0') return true;\n            //use last_s and last_p to store where the \"*\" match starts.\n            last_s = s;\n            last_p = p;\n        }else if (*p=='?' || *s == *p){\n            s++; p++;\n        }else if (last_s != NULL){ // check \"last_s\" to know whether meet \"*\" before\n            // if meet \"*\" previously, and the *s != *p\n            // reset the p, using '*' to match this situation\n            p = last_p;\n            s = ++last_s; \n        }else{\n            // *p is not wildcard char, \n            // doesn't match *s, \n            // there are no '*' wildcard matched before\n            return false;\n        }\n    }\n    //edge case: \"s\" is done, but \"p\" still have chars.\n    while (*p == '*') p++;\n    return *p == '\\0';\n}\n\n\nint main(int argc, char** argv)\n{\n    const char *s = \"aab\";\n    const char *p = \"a*a*b\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    s = \"abbb\";\n    p = \"a*b\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    s = \"abb\";\n    p = \"a*bb\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    s = \"abddbbb\";\n    p = \"a*d*b\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    s = \"abdb\";\n    p = \"a**\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    s = \"a\";\n    p = \"a**\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    /* thanks @jakwings (GitHub) find this problem */\n    s = \"*aa\"; // <-- it is not a pattern, it just a string where '*' is not a wildcard\n    p = \"*a\";\n    cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n\n    if (argc>2){\n        s = argv[1];\n        p = argv[2];\n        cout << s << \", \" << p << \" : \" << isMatch(s, p) << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/wordBreak/wordBreak.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/word-break-ii/\n// Author : Hao Chen\n// Date   : 2014-07-03\n\n/********************************************************************************** \n* \n* Given a string s and a dictionary of words dict, add spaces in s to construct a sentence \n* where each word is a valid dictionary word.\n* \n* Return all such possible sentences.\n* \n* For example, given\n* s = \"catsanddog\",\n* dict = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\"].\n* \n* A solution is [\"cats and dog\", \"cat sand dog\"].\n* \n*               \n**********************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\nusing namespace std;\n\n// ---------------\n//  Recursive Way\n// ---------------\n// The recursive method is quite straight forward.\n//\n//    1) if a substring from 0 to i is a word, then take the rest substring to evaluate. \n//    2) during the recursion, keep tracking the result\n//\n//  For example:\n//\n//    s = \"catsanddog\",\n//    dict = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\"].\n//\n//       \n//                            +---> sand / dog ---> dog           \n//                            |                   \n//         +-------> cat / sanddog                 \n//         |                                      \n//       catsanddog                               \n//          |                                     \n//          +------> cats / anddog                  \n//                            |                    \n//                            +----> and / dog ---> dog           \n//       \n//\n// However, the recursive could produce a lot duplicated calculation, we need use a cache to avoid.\n//\n\n//To avoid time limit error, need to add cache\nvector<string> wordBreak(string s, set<string> &dict, map<string, vector<string> >& cache) {\n\n    if (cache.find(s)!=cache.end()){\n        return cache[s];\n    }\n\n    vector<string> result;\n\n    for(int i=0; i<s.size(); i++){\n        string w = s.substr(0,i+1);\n        if (dict.find(w)!=dict.end()) {\n           if (i==s.size()-1){\n                result.push_back(w);\n                break;\n           }\n\n            vector<string> ret = wordBreak(s.substr(i+1, s.size()-i-1), dict, cache);\n            for(int j=0; j<ret.size(); j++){\n                result.push_back( w + \" \" + ret[j] );\n            }\n        }\n    }\n    cache[s] = result;\n    return result;\n    \n}\n\n\n//Time limit error\nvoid wordBreak(string s, set<string> &dict, string str, vector<string>& result) {\n\n    string org_str = str;\n\n    for(int i=0; i<s.size(); i++){\n        string w = s.substr(0,i+1);\n\n        // if the current substring is a word\n        if (dict.find(w)!=dict.end()) {\n            str = org_str;\n            if (str.size()>0){\n                str +=\" \";\n            }\n            str = str + w;\n\n            // foud the solution, add it into the result\n            if (i==s.size()-1){\n                result.push_back(str);\n                return;\n            }\n\n            //recursively to solve the rest subarray\n            wordBreak(s.substr(i+1, s.size()-i-1), dict, str, result);\n        }\n    }\n}\n//---------------------\n// Dynamic Programming\n//---------------------\n//\n//  Define substring[i, j] is the sub string from i to j.\n//\n//       (substring[i,j] == word) :   result[i] = substring[i,j] + {result[j]}\n//\n//      So, it's better to evaluate it backword. \n//\n//  For example:\n//\n//    s = \"catsanddog\",\n//    dict = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\"].\n//  \n//       0  c  \"cat\"  -- word[0,2] + {result[3]}  ==> \"cat sand dog\"\n//             \"cats\" -- word[0,3] + {result[4]}  ==> \"cats and dog\" \n//       1  a  \"\"\n//       2  t  \"\"\n//       3  s  \"sand\" --  word[3,6] + {result[7]} ==> \"sand dog\"\n//       4  a  \"and\"  --  word[4,6] + {result[7]} ==> \"and dog\"\n//       5  n  \"\"\n//       6  d  \"\"\n//       7  d  \"dog\"\n//       8  o  \"\"\n//       9  g  \"\"\n\nvector<string> wordBreak_dp(string s, set<string> &dict) {\n    vector< vector<string> > result(s.size());\n\n    for(int i=s.size()-1; i>=0; i--) {\n        vector<string> v;\n        result[i] = v;\n        for(int j=i+1; j<=s.size(); j++) {\n            string word = s.substr(i, j-i);\n            if (dict.find(word) != dict.end()){\n                if (j==s.size()){\n                    result[i].push_back(word);\n                }else{\n                    for(int k=0; k<result[j].size(); k++){\n                        result[i].push_back(word + \" \" + result[j][k]);\n                    }\n                }\n            }\n        } \n    }\n\n    return result[0];\n}\n\n\nvector<string> wordBreak(string s, set<string> &dict) {\n\n    vector<string> result;\n\n    switch (random()%3) \n    {\n        case 0: \n            {\n            cout << \"---------Recursive Solution--------\" << endl;\n            string str;\n            wordBreak(s, dict, str, result);\n            }\n            break;\n\n        case 1:\n            {\n            cout << \"----Memorized Recursive Solution----\" << endl;\n            map<string, vector<string> > cache;\n            result = wordBreak(s, dict,  cache);\n            }\n            break;\n\n        case 2:\n            cout << \"----Dynamic Programming Solution----\" << endl;\n            result =  wordBreak_dp(s, dict);\n            break;\n    }\n    return result;\n}\n\nvoid printVector(vector<string>& v)\n{\n    for(int i=0; i<v.size(); i++){\n        cout << v[i] <<endl;\n    }\n}\n\nint main()\n{\n    srand(time(NULL));\n\n    string d[]={\"cat\", \"cats\", \"and\", \"sand\", \"dog\"};\n    set<string> dict(d, d+5);\n    string s = \"catsanddog\";\n    vector<string> v = wordBreak(s, dict);\n    printVector(v);     \n    \n    string d0[]={\"apple\",\"app\",\"le\",\"pie\"};\n    dict.clear();\n    dict.insert(d0, d0+4);\n    s = \"applepie\";\n    v = wordBreak(s, dict);\n    printVector(v);     \n    \n    string d1[]={\"aaaa\",\"aa\",\"a\"};\n    dict.clear();\n    dict.insert(d1, d1+3);\n    s = \"aaaaaaa\";\n    v = wordBreak(s, dict);\n    printVector(v);     \n\n    string d5[]={\"a\",\"aa\",\"aaa\",\"aaaa\",\"aaaaa\",\"aaaaaa\",\"aaaaaaa\",\"aaaaaaaa\",\"aaaaaaaaa\",\"aaaaaaaaaa\"};\n    dict.clear();\n    dict.insert(d5, d5+10);\n    s=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab\";\n    v = wordBreak(s, dict);\n    printVector(v);     \n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/wordBreak/wordBreak.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/word-break/\n// Author : Hao Chen\n// Date   : 2014-07-01\n\n/********************************************************************************** \n* \n* Given a string s and a dictionary of words dict, determine if s can be segmented \n* into a space-separated sequence of one or more dictionary words.\n* \n* For example, given\n* s = \"leetcode\",\n* dict = [\"leet\", \"code\"].\n* \n* Return true because \"leetcode\" can be segmented as \"leet code\".\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <set>\nusing namespace std;\n\nbool wordBreak(string s, set<string> &dict) {\n\n    //using an array to mark subarray from 0 to i can be broken or not\n    vector<bool> v(s.size(),false);\n\n    for(int i=0; i<s.size(); i++){\n        //check the substring from 0 to i is int dict or not\n        string w = s.substr(0,i+1);\n        v[i] = (dict.find(w)!=dict.end());\n\n        //if it is, then use greedy algorithm\n        if (v[i]) continue;\n\n        //if it is not, then break it to check\n        for(int j=0; j<i; j++){\n            //if the substring from 0 to j can be borken, then check the substring from j to i\n            if (v[j]==true){\n                w = s.substr(j+1, i-j);\n                v[i] = (dict.find(w)!=dict.end());\n                if (v[i]) break;\n            }\n        }\n    }\n    return v.size() ? v[v.size()-1] : false;\n}\n\n\nint main()\n{\n    string s; \n    set<string> dict;\n\n    s = \"a\";\n    dict.insert(\"a\");\n    cout << wordBreak(s, dict) << endl;\n    \n    dict.clear();\n    s = \"dogs\";\n    string d[]={\"dog\",\"s\",\"gs\"};\n    dict.insert(d, d+3);\n    cout << wordBreak(s, dict) << endl;\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/wordLadder/wordLadder.II.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/word-ladder-ii/\n// Author : Hao Chen\n// Date   : 2014-10-13\n\n/********************************************************************************** \n* \n* Given two words (start and end), and a dictionary, find all shortest transformation \n* sequence(s) from start to end, such that:\n* \n* Only one letter can be changed at a time\n* Each intermediate word must exist in the dictionary\n* \n* For example,\n* \n* Given:\n* start = \"hit\"\n* end = \"cog\"\n* dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n* \n* Return\n* \n*   [\n*     [\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],\n*     [\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]\n*   ]\n* \n* Note:\n* \n* All words have the same length.\n* All words contain only lowercase alphabetic characters.\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <queue>\n#include <unordered_set>\nusing namespace std;\n\n// Solution\n//\n//      1) Using BSF algorithm build a tree like below\n//      2) Using DSF to parse the tree to the transformation path.\n//\n// For example:\n//\n//     start = \"hit\"\n//     end = \"cog\"\n//     dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"dit\",\"hig\", \"dig\"]\n//\n//                      +-----+\n//        +-------------+ hit +--------------+\n//        |             +--+--+              |\n//        |                |                 |\n//     +--v--+          +--v--+           +--v--+\n//     | dit |    +-----+ hot +---+       | hig |\n//     +--+--+    |     +-----+   |       +--+--+\n//        |       |               |          |\n//        |    +--v--+         +--v--+    +--v--+\n//        +----> dot |         | lot |    | dig |\n//             +--+--+         +--+--+    +--+--+\n//                |               |          |\n//             +--v--+         +--v--+       |\n//        +----> dog |         | log |       |\n//        |    +--+--+         +--+--+       |\n//        |       |               |          |\n//        |       |    +--v--+    |          |\n//        |       +--->| cog |<-- +          |\n//        |            +-----+               |\n//        |                                  |\n//        |                                  |\n//        +----------------------------------+\n\nmap< string, unordered_set<string> >& \nbuildTree(string& start, string& end, unordered_set<string> &dict) {\n\n    static map< string, unordered_set<string> > parents;\n    parents.clear();\n\n    unordered_set<string> level[3];\n    unordered_set<string> *previousLevel = &level[0];\n    unordered_set<string> *currentLevel = &level[1];\n    unordered_set<string> *newLevel = &level[2];\n    unordered_set<string> *p =NULL;\n    currentLevel->insert(start);\n\n    bool reachEnd = false;\n\n    while( !reachEnd ) {\n        newLevel->clear();\n        for(auto it=currentLevel->begin(); it!=currentLevel->end(); it++) {    \n            for (int i=0; i<it->size(); i++) {\n                string newWord = *it;\n                for(char c='a'; c<='z'; c++){\n                    newWord[i] = c;\n                    if (newWord == end){\n                        reachEnd = true;\n                        parents[*it].insert(end);\n                        continue;\n                    }\n                    if ( dict.count(newWord)==0 || currentLevel->count(newWord)>0 || previousLevel->count(newWord)>0 ) {\n                        continue;\n                    }\n                    newLevel->insert(newWord);\n                    //parents[newWord].insert(*it);\n                    parents[*it].insert(newWord);\n                }\n            }\n        } \n        if (newLevel->empty()) break;\n\n        p = previousLevel; \n        previousLevel = currentLevel;\n        currentLevel = newLevel;\n        newLevel = p;\n    }\n\n\n    if ( !reachEnd ) {\n        parents.clear();\n    } \n    return parents;\n}\n\nvoid generatePath( string start, string end,\n        map< string, unordered_set<string> > &parents, \n        vector<string> path,\n        vector< vector<string> > &paths) {\n\n    if (parents.find(start) == parents.end()){\n        if (start == end){\n            paths.push_back(path);\n        }\n        return;\n    }\n\n    for(auto it=parents[start].begin(); it!=parents[start].end(); it++){\n        path.push_back(*it);\n        generatePath(*it, end, parents, path, paths);\n        path.pop_back();\n    }\n\n}\n\nvector< vector<string> > \nfindLadders(string start, string end, unordered_set<string> &dict) {\n\n    vector< vector<string> > ladders;\n    vector<string> ladder;\n    ladder.push_back(start);\n    if (start == end){\n        ladder.push_back(end);\n        ladders.push_back(ladder);\n        return ladders;\n    }\n\n    map< string, unordered_set<string> >& parents = buildTree(start, end, dict);\n\n    if  (parents.size()<=0) {\n        return ladders;\n    }\n\n    generatePath(start, end, parents, ladder, ladders);\n\n    return ladders;\n}\n\nvoid printLadders(vector< vector<string> > &ladders){\n    int i, j;\n    for (i=0; i<ladders.size(); i++){\n        for (j=0; j<ladders[i].size()-1; j++){\n            cout << ladders[i][j] << \" -> \";\n        }\n        cout << ladders[i][j] << endl; \n    }\n}\n\nint main(int argc, char** argv)\n{\n    string start = \"hit\";\n    string end = \"cog\";\n    //unordered_set<string> dict ({\"hot\",\"dot\",\"dog\",\"lot\",\"log\"});\n    unordered_set<string> dict ({\"bot\",\"cig\", \"cog\", \"dit\", \"dut\", \"hot\", \"hit\" ,\"dot\",\"dog\",\"lot\",\"log\"});\n\n    vector< vector<string> > ladders;\n    ladders = findLadders(start, end, dict);\n    printLadders(ladders);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/wordLadder/wordLadder.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/word-ladder/\n// Author : Hao Chen\n// Date   : 2014-10-12\n\n/********************************************************************************** \n* \n* Given two words (start and end), and a dictionary, find the length of shortest \n* transformation sequence from start to end, such that:\n* \n* Only one letter can be changed at a time\n* Each intermediate word must exist in the dictionary\n* \n* For example,\n* \n* Given:\n* start = \"hit\"\n* end = \"cog\"\n* dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n* \n* As one shortest transformation is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\",\n* return its length 5.\n* \n* Note:\n* \n* Return 0 if there is no such transformation sequence.\n* All words have the same length.\n* All words contain only lowercase alphabetic characters.\n* \n*               \n**********************************************************************************/\n\n// --------------------------- \n//  BFS non-recursive method\n// ---------------------------\n//\n//    Using BFS instead of DFS is becasue the solution need the shortest transformation path.\n//  \n//    So, we can change every char in the word one by one, until find all possible transformation.\n//\n//    Keep this iteration, we will find the shorest path.\n//\n// For example:\n//   \n//     start = \"hit\"\n//     end = \"cog\"\n//     dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"dit\",\"hig\", \"dig\", \"cog\"]\n//\n//                      +-----+                  \n//        +-------------+ hit +--------------+   \n//        |             +--+--+              |   \n//        |                |                 |   \n//     +--v--+          +--v--+           +--v--+\n//     | dit |    +-----+ hot +---+       | hig |\n//     +--+--+    |     +-----+   |       +--+--+\n//        |       |               |          |   \n//        |    +--v--+         +--v--+    +--v--+\n//        +----> dot |         | lot |    | dig |\n//             +--+--+         +--+--+    +--+--+\n//                |               |          |   \n//             +--v--+         +--v--+       |   \n//        +----> dog |         | log |       |   \n//        |    +--+--+         +--+--+       |   \n//        |       |               |          |   \n//        |       |    +--v--+    |          |   \n//        |       +--->| cog |<-- +          |   \n//        |            +-----+               |   \n//        |                                  |   \n//        |                                  |   \n//        +----------------------------------+   \n//     \n//     1) queue <==  \"hit\"\n//     2) queue <==  \"dit\", \"hot\", \"hig\"\n//     3) queue <==  \"dot\", \"lot\", \"dig\"\n//     4) queue <==  \"dog\", \"log\" \n// \nclass Solution {\npublic:\n    int ladderLength(string start, string end, unordered_set<string> &dict) {\n        \n        // Using a map for two purposes: \n        //   1) store the distince so far.\n        //   2) remove the duplication \n        map<string, int> dis;\n        dis[start] = 1;\n        \n        queue<string> q;\n        q.push(start);\n        \n        while(!q.empty()){\n\n            string word = q.front(); \n            q.pop();\n            \n            if (word == end) {\n                break;\n            }\n            \n            for (int i=0; i<word.size(); i++){\n                string temp = word;\n                for(char c='a'; c<='z'; c++){\n                    temp[i] = c;\n                    if (dict.count(temp)>0 && dis.count(temp)==0){\n                        dis[temp] = dis[word] + 1;\n                        q.push(temp);\n                    }\n                }\n            }\n        }\n        return (dis.count(end)==0) ? 0 : dis[end];\n        \n    }\n};\n"
  },
  {
    "path": "algorithms/cpp/wordPattern/WordPattern.cpp",
    "content": "// Source : https://leetcode.com/problems/word-pattern/\n// Author : Hao Chen\n// Date   : 2015-10-22\n\n/*************************************************************************************** \n *\n * Given a pattern and a string str, find if str follows the same pattern.\n *  Here follow means a full match, such that there is a bijection between a letter in \n * pattern and a non-empty word in str.\n * \n * Examples:\n * \n * pattern = \"abba\", str = \"dog cat cat dog\" should return true.\n * pattern = \"abba\", str = \"dog cat cat fish\" should return false.\n * pattern = \"aaaa\", str = \"dog cat cat dog\" should return false.\n * pattern = \"abba\", str = \"dog dog dog dog\" should return false.\n * \n * Notes:\n * You may assume pattern contains only lowercase letters, and str contains lowercase \n * letters separated by a single space.\n * \n * Credits:Special thanks to @minglotus6 for adding this problem and creating all test \n * cases.\n *               \n ***************************************************************************************/\n\nclass Solution {\n\nprivate::\n\n    vector<string> split(string str, char delimiter) {\n        vector<string> internal;\n        stringstream ss(str); // Turn the string into a stream.\n        string tok;\n        \n        while(getline(ss, tok, delimiter)) {\n            internal.push_back(tok);\n        }\n        \n        return internal;\n    }\n\npublic:\n    \n    bool wordPattern(string pattern, string str) {\n        unordered_map<char, string> dict_pattern;\n        unordered_map<string, char> dict_string;\n        \n        int len = pattern.size();\n        vector<string> strs = split(str, ' ');\n        \n        if (len != strs.size()) return false;\n        \n        for(int i=0; i<len; i++) {\n            char& ch = pattern[i];\n            string& s = strs[i];\n            \n            if ( dict_pattern.find(ch) == dict_pattern.end() ) {\n                dict_pattern[ch] = s;\n            }\n            \n            if ( dict_string.find(s) == dict_string.end() ) {\n                dict_string[s] = ch;\n            }\n            \n            if ( dict_pattern[ch] != s || dict_string[s] != ch ) {\n                return false;\n            }\n            \n        }\n        return true;\n    }\n};\n\n"
  },
  {
    "path": "algorithms/cpp/wordSearch/wordSearch.II.cpp",
    "content": "// Source : https://leetcode.com/problems/word-search-ii/\n// Author : Hao Chen\n// Date   : 2015-06-10\n\n/********************************************************************************** \n * \n * Given a 2D board and a list of words from the dictionary, find all words in the board.\n * \n * Each word must be constructed from letters of sequentially adjacent cell, where \"adjacent\" \n * cells are those horizontally or vertically neighboring. The same letter cell may not be used \n * more than once in a word.\n * \n * For example,\n *   Given words = [\"oath\",\"pea\",\"eat\",\"rain\"] and board = \n *   \n *   [\n *     ['o','a','a','n'],\n *     ['e','t','a','e'],\n *     ['i','h','k','r'],\n *     ['i','f','l','v']\n *   ]\n *   \n * Return [\"eat\",\"oath\"].\n * \n * Note:\n * You may assume that all inputs are consist of lowercase letters a-z.\n * \n * click to show hint.\n * \n * You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?\n * \n * If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. \n * What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? \n * How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: \n * Implement Trie (Prefix Tree) first.\n *               \n **********************************************************************************/\n\nconst int MAX_CHARS = 26;\n\nclass TrieNode {\n    public:\n        TrieNode(string s):isWord(false), word(s) {\n            memset(children, 0, sizeof(children));\n        }\n        TrieNode* & operator [] (char ch) {\n            return children[(ch - 'a') % MAX_CHARS];\n        }\n        TrieNode* & operator [] (int idx) {\n            return children[idx % MAX_CHARS];\n        }\n\n    public:\n        string word;\n        bool isWord;\n    private:\n        TrieNode* children[MAX_CHARS];\n};\n\nclass TrieTree {\n    public:\n        TrieTree():root(new TrieNode(\"\")) { }\n        ~TrieTree() { freeTree(root); }\n        TrieNode* getRoot() {\n            return root;\n        }\n        void addWord(string& s){\n            TrieNode *node = root;\n            string t;\n            for (int i=0; i<s.size(); i++){\n                t += s[i];\n                if ( (*node)[s[i]] == NULL ){\n                    (*node)[s[i]] = new TrieNode(t);\n                }\n                node = (*node)[s[i]];\n            }\n            node->isWord = true;\n        }\n    private:\n        void freeTree(TrieNode* node){\n            for(int i=0; i<MAX_CHARS; i++){\n                if ((*node)[i]!=NULL){\n                    freeTree((*node)[i]);\n                }\n            }\n            delete node;\n        }\n        TrieNode *root;\n\n};\n\nclass Solution {\npublic:\n    void findWords(vector<vector<char>>& board, TrieNode* root, int row, int col, vector<string>& result){\n        if (row < 0 || col < 0 || \n                row >= board.size() || \n                col >= board[row].size() ||\n                board[row][col] == '\\0' ) {\n            return;\n        }\n        \n        char ch = board[row][col];\n        root = (*root)[ch];\n        \n        if (root==NULL) return;\n        \n        if (root->isWord){\n            result.push_back(root->word);\n            root->isWord = false;\n        }\n        \n        \n        board[row][col] = '\\0';\n        \n        findWords(board, root, row, col - 1, result);\n        findWords(board, root, row, col + 1, result);\n        findWords(board, root, row + 1, col, result);\n        findWords(board, root, row - 1, col, result);\n        \n        board[row][col] = ch;\n        \n    }\n\npublic:\n    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {\n        TrieTree t;\n        for (int i = 0; i<words.size(); i++){\n            t.addWord(words[i]);\n        }\n        \n        vector<string> result;\n        for (int i = 0; i<board.size(); i++) {\n            for (int j = 0; j < board[i].size(); j++) { \n                findWords(board, t.getRoot(), i, j, result);\n            }\n        }\n        return result;            \n    }\n\n};\n\n"
  },
  {
    "path": "algorithms/cpp/wordSearch/wordSearch.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/word-search/\n// Author : Hao Chen\n// Date   : 2014-07-19\n\n/********************************************************************************** \n * \n * Given a 2D board and a word, find if the word exists in the grid.\n * \n * The word can be constructed from letters of sequentially adjacent cell, \n * where \"adjacent\" cells are those horizontally or vertically neighboring. \n * The same letter cell may not be used more than once.\n * \n * For example,\n * Given board = \n * \n * [\n *   [\"ABCE\"],\n *   [\"SFCS\"],\n *   [\"ADEE\"]\n * ]\n * \n * word = \"ABCCED\", -> returns true,\n * word = \"SEE\", -> returns true,\n * word = \"ABCB\", -> returns false.\n * \n *               \n **********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nbool exist(vector<vector<char> > &board, string& word, int idx, int row, int col) {\n    if ( row<0 || row>=board.size() ||\n            col<0 || col>=board[0].size() ||\n            board[row][col] != word[idx]) {\n        return false;\n    }\n\n\n    if (idx+1 == word.size()) return true;\n\n    //replace to a special char to avoid duplication.\n    board[row][col] = '\\0';\n\n    if ( exist(board, word, idx+1, row+1, col ) ||\n            exist(board, word, idx+1, row-1, col ) ||\n            exist(board, word, idx+1, row, col+1 ) ||\n            exist(board, word, idx+1, row, col-1 ) ) {\n        return true;\n    }\n\n    //restore the char\n    board[row][col] = word[idx];\n\n    return false;\n}\n\nbool exist(vector<vector<char> > &board, string word) {\n    if (board.size()<=0 || word.size()<=0) return false;\n    int row = board.size();\n    int col = board[0].size();\n\n    for(int i=0; i<board.size(); i++) {\n        for(int j=0; j<board[i].size(); j++){\n            if ( board[i][j]==word[0]  ){\n                if( exist(board, word, 0, i, j) ){\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nvector< vector<char> > buildBoard(char b[][5], int r, int c) {\n    vector< vector<char> > board;\n    for (int i=0; i<r; i++){\n        vector<char> v(b[i], b[i]+c);\n        cout << b[i] << endl;\n        board.push_back(v);\n    }\n    cout << \"----------\" << endl;    \n    return board;\n}\n\nint main(int argc, char** argv)\n{\n    string s;\n    char b[3][5] ={ \"ABCE\", \"SFCS\", \"ADEE\" };\n    vector< vector<char> > board = buildBoard(b, 3, 4);\n\n    s = \"SEE\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n    s = \"ABCCED\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n    s = \"ABCB\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n\n    if (argc>1){\n        s = argv[1];\n        cout << s << \":\" << exist(board, s) << endl; \n    }\n\n    cout << endl << \"----------\" << endl;    \n    char b1[3][5] ={ \"CAA\", \"AAA\", \"BCD\" };\n    board = buildBoard(b1, 3, 3);\n\n    s = \"AAB\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n\n    cout << endl << \"----------\" << endl;    \n    char b2[3][5] ={ \"ABCE\", \"SFES\", \"ADEE\" };\n    board = buildBoard(b2, 3, 4);\n\n    s = \"ABCESEEEFS\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n    cout << endl << \"----------\" << endl;    \n    char b3[3][5] ={ \"aaaa\", \"aaaa\", \"aaaa\" };\n    board = buildBoard(b3, 3, 4);\n\n    s = \"aaaaaaaaaaaaa\";\n    cout << s << \":\" << exist(board, s) << endl; \n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/cpp/zigZagConversion/zigZagConversion.cpp",
    "content": "// Source : https://oj.leetcode.com/problems/zigzag-conversion/\n// Author : Hao Chen\n// Date   : 2014-07-17\n\n/********************************************************************************** \n* \n* The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: \n* (you may want to display this pattern in a fixed font for better legibility)\n* \n* P   A   H   N\n* A P L S I I G\n* Y   I   R\n* \n* And then read line by line: \"PAHNAPLSIIGYIR\"\n* \n* Write the code that will take a string and make this conversion given a number of rows:\n* \n* string convert(string text, int nRows);\n* \n* convert(\"PAYPALISHIRING\", 3) should return \"PAHNAPLSIIGYIR\".\n* \n*               \n**********************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nstring convert(string s, int nRows) {\n    //The cases no need to do anything\n    if (nRows<=1 || nRows>=s.size()) return s;\n     \n    vector<string> r(nRows);\n    int row = 0;\n    int step = 1;\n    for(int i=0; i<s.size(); i ++) {\n        if (row == nRows-1) step = -1;\n        if (row == 0) step = 1;\n        //cout << row <<endl;\n        r[row] += s[i];\n        row += step;\n    }\n    \n    string result;\n    for (int i=0; i<nRows; i++){\n        result += r[i];\n    }\n    return result;\n}\n\nint main(int argc, char**argv){\n\n    string s;\n    int r;\n\n    s = \"PAYPALISHIRING\";\n    r = 3;\n    cout << s << \" : \" << convert(s, 3) << endl;\n\n}\n"
  },
  {
    "path": "algorithms/golang/twoSum/twoSum.go",
    "content": "package twoSum\n\nfunc twoSum(nums []int, target int) []int {\n\tnumMap := make(map[int]int)\n\tfor index, num := range nums {\n\t\tif i, ok := numMap[target-num]; ok {\n\t\t\treturn []int{i, index}\n\t\t}\n\t\tnumMap[num] = index\n\t}\n\treturn nil\n}"
  },
  {
    "path": "algorithms/java/algorithms-java.iml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n  <component name=\"NewModuleRootManager\" inherit-compiler-output=\"true\">\n    <exclude-output />\n    <content url=\"file://$MODULE_DIR$\">\n      <sourceFolder url=\"file://$MODULE_DIR$/src\" isTestSource=\"false\" />\n    </content>\n    <orderEntry type=\"inheritedJdk\" />\n    <orderEntry type=\"sourceFolder\" forTests=\"false\" />\n    <orderEntry type=\"module-library\">\n      <library>\n        <CLASSES>\n          <root url=\"jar://$MODULE_DIR$/junit-4.7.jar!/\" />\n        </CLASSES>\n        <JAVADOC />\n        <SOURCES />\n      </library>\n    </orderEntry>\n  </component>\n</module>"
  },
  {
    "path": "algorithms/java/src/LargestNumberAfterMutatingSubstring/largestNumberAfterMutatingSubstring.java",
    "content": "/***************************************************************************************************** \n *\n * You are given a string num, which represents a large integer. You are also given a 0-indexed \n * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d \n * maps to digit change[d].\n * \n * You may choose to mutate a single substring of num. To mutate a substring, replace each digit \n * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\n * \n * Return a string representing the largest possible integer after mutating (or choosing not to) a \n * single substring of num.\n * \n * A substring is a contiguous sequence of characters within the string.\n * \n * Example 1:\n * \n * Input: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\n * Output: \"832\"\n * Explanation: Replace the substring \"1\":\n * - 1 maps to change[1] = 8.\n * Thus, \"132\" becomes \"832\".\n * \"832\" is the largest number that can be created, so return it.\n * \n * Example 2:\n * \n * Input: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\n * Output: \"934\"\n * Explanation: Replace the substring \"021\":\n * - 0 maps to change[0] = 9.\n * - 2 maps to change[2] = 3.\n * - 1 maps to change[1] = 4.\n * Thus, \"021\" becomes \"934\".\n * \"934\" is the largest number that can be created, so return it.\n * \n * Example 3:\n * \n * Input: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\n * Output: \"5\"\n * Explanation: \"5\" is already the largest number that can be created, so return it.\n * \n * Constraints:\n * \n * \t1 <= num.length <= 10^5\n * \tnum consists of only digits 0-9.\n * \tchange.length == 10\n * \t0 <= change[d] <= 9\n ******************************************************************************************************/\n\nclass Solution {\n    public String maximumNumber(String num, int[] change) {\n        \n        //make flag for checking replacement\n        boolean shouldReplace = false;\n        \n        //work through substring\n        for(int i = 0; i < num.length(); i++){\n            \n            //subtract zero to get correct ascii conversion\n            char a = num.charAt(i);\n            char curr = (char)(a - '0');\n            \n            if(curr < change[curr]){\n                \n                char c = (char)(change[curr] + '0');\n                \n                num = num.replace(num.charAt(i), c);\n                \n                shouldReplace = true;\n                \n            }else if((curr > change[curr]) && (shouldReplace)){\n                \n                break;\n                \n            } \n        }\n        \n        return num;\n    }\n}\n\n\n"
  },
  {
    "path": "algorithms/java/src/MaxSubArray/MaxSubarray.java",
    "content": "// Source : https://leetcode.com/problems/maximum-subarray/\r\n// Author : Ikshit Agrawal\r\n// Date   : 2020-10-04\r\n/*\r\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\r\nExample 1:\r\n\t\tInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\r\n\t\tOutput: 6\r\n\t\tExplanation: [4,-1,2,1] has the largest sum = 6.\r\n\r\nExample 2:\r\n\t\tInput: nums = [1]\r\n\t\tOutput: 1\r\n*/\r\nclass Solution {\r\n    public int maxSubArray(int[] nums) {\r\n     int max1=nums[0],cur=0;\r\n        for(int i :nums)\r\n        {\r\n            if(cur<0)\r\n                cur=0;\r\n            cur+=i;\r\n            max1=Math.max(max1,cur);\r\n        }\r\n        return max1;\r\n    }\r\n}\r\n"
  },
  {
    "path": "algorithms/java/src/RotateImage/rotateImage.java",
    "content": "/*\n\nYou are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n\nYou have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.\n\n Example 1:\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[7,4,1],[8,5,2],[9,6,3]]\n\nExample 2:\nInput: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n\nConstraints:\n\nn == matrix.length == matrix[i].length\n1 <= n <= 20\n-1000 <= matrix[i][j] <= 1000\n\n*/\n\n\n//when looking for a pattern, we notice that there numbers in groups of four that change positions with one another\n//approach: find the positions of those four and swamp them with their right neighbor to make the 90 degree turn\n\nclass Solution {\n    public void rotate(int[][] matrix) {\n        \n        int n = matrix.length; //given\n        \n        //adding one and dividing with int division accounts for both odd and even length of n\n        for (int i = 0; i < ((n + 1) / 2); i ++) {\n            \n            for (int j = 0; j < (n / 2); j++) {\n                \n                //Starts with far edges and works its way back to the left\n                //hold first of group, use to replace in final swap\n                int temp = matrix[n - j - 1][i]; \n                \n                //keep replacing with group member on next side of the square\n                matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; \n                matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];\n                matrix[j][n - i - 1] = matrix[i][j];\n                \n                //finally replace last spot with first spot held in temp\n                matrix[i][j] = temp;\n                \n                //move to next group with index incrementation\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/balancedBinaryTree/TreeNode.java",
    "content": "package balancedBinaryTree;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n    public int val;\n    public TreeNode left, right;\n    public TreeNode(int val) {\n        this.val = val;\n        this.left = this.right = null;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/balancedBinaryTree/balancedBinaryTree.java",
    "content": "// Source : https://oj.leetcode.com/problems/balanced-binary-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/balanced-binary-tree/\n// Author : Lei Cao\n// Date   : 2015-10-07\n\n/**********************************************************************************\n *\n * Given a binary tree, determine if it is height-balanced.\n *\n * For this problem, a height-balanced binary tree is defined as a binary tree in which\n * the depth of the two subtrees of every node never differ by more than 1.\n * Example\n * Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}\n * The binary tree A is a height-balanced binary tree, but B is not.\n **********************************************************************************/\n\npackage balancedBinaryTree;\n\n/**\n * Created by leicao on 7/10/15.\n */\npublic class balancedBinaryTree {\n    /**\n     * @param root: The root of binary tree.\n     * @return: True if this Binary tree is Balanced, or false.\n     */\n    public boolean isBalanced(TreeNode root) {\n        // write your code here\n        return helper(root, 0).isBalanced;\n    }\n\n    // This is not needed. Can just check the depth\n    private class Result {\n        boolean isBalanced;\n        int height;\n        Result(boolean isBalanced, int height) {\n            this.isBalanced = isBalanced;\n            this.height = height;\n        }\n    }\n    private Result helper(TreeNode root, int depth) {\n        if (root == null) {\n            return new Result(true, depth);\n        }\n        Result left = helper(root.left, depth + 1);\n        Result right = helper(root.right, depth + 1);\n\n        if (!left.isBalanced || !right.isBalanced) {\n            return new Result(false, 0);\n        }\n\n        if (Math.abs(left.height - right.height) > 1) {\n            return new Result(false, 0);\n        }\n        return new Result(true, Math.max(left.height, right.height));\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/balancedBinaryTree/balancedBinaryTreeTest.java",
    "content": "package balancedBinaryTree;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n/**\n * Created by leicao on 7/10/15.\n */\npublic class balancedBinaryTreeTest {\n\n    @Test\n    public void testIsBalanced() throws Exception {\n        ArrayList<TreeNode> inputes = new ArrayList<TreeNode>();\n        boolean[] results = {false, false};\n        TreeNode n0 = new TreeNode(0);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        TreeNode n3 = new TreeNode(3);\n\n        n0.left = n1;\n        n1.left = n2;\n        n2.left = n3;\n\n        TreeNode nn0 = new TreeNode(0);\n        TreeNode nn1 = new TreeNode(1);\n        TreeNode nn2 = new TreeNode(2);\n        TreeNode nn3 = new TreeNode(3);\n        nn0.right = nn1;\n        nn1.left = nn2;\n        nn2.left = nn3;\n\n        inputes.add(n0);\n        inputes.add(nn0);\n\n        for (int i = 0; i < results.length; i++) {\n            balancedBinaryTree b = new balancedBinaryTree();\n            assertEquals(results[i], b.isBalanced(inputes.get(i)));\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/binarySearchTreeIterator/TreeNode.java",
    "content": "package binarySearchTreeIterator;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n    public int val;\n    public TreeNode left, right;\n    public TreeNode(int val) {\n        this.val = val;\n        this.left = this.right = null;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIterator.java",
    "content": "// Source : https://oj.leetcode.com/problems/balanced-binary-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/binary-search-tree-iterator/\n// Author : Lei Cao\n// Date   : 2015-10-07\n\n/********************************************************************************** \n * \n * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.\n * \n * Calling next() will return the next smallest number in the BST.\n * \n * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. \n * \n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *               \n **********************************************************************************/\n\npackage binarySearchTreeIterator;\n\nimport java.util.Stack;\n\n/**\n * Definition of TreeNode:\n * public class TreeNode {\n *     public int val;\n *     public TreeNode left, right;\n *     public TreeNode(int val) {\n *         this.val = val;\n *         this.left = this.right = null;\n *     }\n * }\n * Example of iterate a tree:\n * Solution iterator = new Solution(root);\n * while (iterator.hasNext()) {\n *    TreeNode node = iterator.next();\n *    do something for node\n * }\n */\npublic class binarySearchTreeIterator {\n    private TreeNode currentNode = null;\n    private Stack<TreeNode> stack = new Stack<TreeNode>();\n    //@param root: The root of binary tree.\n    public binarySearchTreeIterator(TreeNode root) {\n        if (root != null) {\n            currentNode = root;\n        }\n    }\n\n    //@return: True if there has next node, or false\n    public boolean hasNext() {\n        // write your code here\n        return currentNode != null || !stack.isEmpty();\n    }\n\n    //@return: return next node\n    public TreeNode next() {\n        // write your code here\n        while (currentNode != null) {\n            stack.push(currentNode);\n            currentNode = currentNode.left;\n        }\n\n        currentNode = stack.pop();\n        TreeNode node = currentNode;\n        currentNode = currentNode.right;\n\n        return node;\n    }\n}\n\n"
  },
  {
    "path": "algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIteratorTest.java",
    "content": "package binarySearchTreeIterator;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 11/10/15.\n */\npublic class binarySearchTreeIteratorTest {\n    @Test\n    public void testIterator() throws Exception {\n        ArrayList<TreeNode> inputs = new ArrayList<TreeNode>();\n        TreeNode t0 = new TreeNode(10);\n        TreeNode t1 = new TreeNode(1);\n        TreeNode t2 = new TreeNode(11);\n        TreeNode t3 = new TreeNode(6);\n        TreeNode t4 = new TreeNode(12);\n        t0.left = t1;\n        t0.right = t2;\n        t1.right = t3;\n        t2.right = t4;\n\n        inputs.add(t0);\n\n        int[][] results = {\n                {1,6,10,11,12}\n        };\n\n        for (int i = 0; i < results.length; i++) {\n            binarySearchTreeIterator it = new binarySearchTreeIterator(inputs.get(i));\n            int j = 0;\n            while (it.hasNext()) {\n                TreeNode r = it.next();\n                assertEquals(results[i][j], r.val);\n                j++;\n            }\n        }\n\n    }\n\n}"
  },
  {
    "path": "algorithms/java/src/binaryTreeBFSTraversal/TreeNode.java",
    "content": "package binaryTreeBFSTraversal;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeBFSTraversal/binaryTreeBFSTraversal.java",
    "content": "package binaryTreeBFSTraversal;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class binaryTreeBFSTraversal {\n    public List<Integer> bfsTraversal(TreeNode root) {\n        List<Integer>  results = new ArrayList<Integer>();\n        if (root == null) {\n            return results;\n        }\n\n        Queue<TreeNode> q = new LinkedList<TreeNode>();\n\n        q.offer(root);\n        while (q.size() != 0) {\n            TreeNode n = q.remove();\n            results.add(n.val);\n            if (n.left != null) {\n                q.offer(n.left);\n            }\n            if (n.right != null) {\n                q.offer(n.right);\n            }\n        }\n\n        return results;\n\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeBFSTraversal/binaryTreeBFSTraversalTest.java",
    "content": "package binaryTreeBFSTraversal;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * Created by leicao on 6/10/15.\n */\npublic class binaryTreeBFSTraversalTest {\n\n    /**\n     *          0\n     *        /   \\\n     *      1      2\n     *     / \\      \\\n     *   3    4      6\n     *      /\n     *      5\n     */\n    @Test\n    public void testPreorderTraversal() throws Exception {\n        TreeNode t0 = new TreeNode(0);\n\n        TreeNode n0 = new TreeNode(0);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        TreeNode n3 = new TreeNode(3);\n        TreeNode n4 = new TreeNode(4);\n        TreeNode n5 = new TreeNode(5);\n        TreeNode n6 = new TreeNode(6);\n\n        n0.left = n1;\n        n0.right = n2;\n        n1.left = n3;\n        n1.right = n4;\n        n4.left = n5;\n        n2.right = n6;\n\n\n        ArrayList<TreeNode> inputes = new ArrayList<>();\n        inputes.add(t0);\n        inputes.add(n0);\n\n        List<List<Integer>> results = new ArrayList<List<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(0);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(0);\n                add(1);\n                add(2);\n                add(3);\n                add(4);\n                add(6);\n                add(5);\n            }});\n        }};\n\n        binaryTreeBFSTraversal b = new binaryTreeBFSTraversal();\n        for (int i = 0; i < results.size(); i++) {\n            List<Integer> r = b.bfsTraversal(inputes.get(i));\n            assertEquals(results.get(i), r);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/binaryTreeLevelOrderTraversal/TreeNode.java",
    "content": "package binaryTreeLevelOrderTraversal;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.java",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-level-order-traversal/\n// Inspired by : http://www.jiuzhang.com/solutions/binary-tree-level-order-traversal/\n// Author : Lei Cao\n// Date   : 2015-10-08\n\n/**********************************************************************************\n *\n * Given a binary tree, return the level order traversal of its nodes' values.\n * (ie, from left to right, level by level).\n *\n * For example:\n * Given binary tree {3,9,20,#,#,15,7},\n *\n *     3\n *    / \\\n *   9  20\n *     /  \\\n *    15   7\n *\n * return its level order traversal as:\n *\n * [\n *   [3],\n *   [9,20],\n *   [15,7]\n * ]\n *\n * confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n *\n * OJ's Binary Tree Serialization:\n *\n * The serialization of a binary tree follows a level order traversal, where '#' signifies\n * a path terminator where no node exists below.\n *\n * Here's an example:\n *\n *    1\n *   / \\\n *  2   3\n *     /\n *    4\n *     \\\n *      5\n *\n * The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\".\n *\n *\n **********************************************************************************/\n\npackage binaryTreeLevelOrderTraversal;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\npublic class binaryTreeLevelOrderTraversal {\n    /**\n     * @param root: The root of binary tree.\n     * @return: Level order a list of lists of integer\n     */\n    public List<List<Integer>> levelOrder(TreeNode root) {\n        List<List<Integer>> results = new ArrayList<>();\n        if (root == null) {\n            return results;\n        }\n\n        ArrayList<Integer> values = new ArrayList<Integer>();\n        Queue<TreeNode> q = new LinkedList<>();\n\n        q.offer(root);\n        q.offer(null);\n\n        while (q.size() > 0) {\n            TreeNode node = q.poll();\n            // null node used as a separator of every level\n            if (node == null) {\n                results.add(new ArrayList<>(values));\n                values.clear();\n                if (q.size() == 0) {\n                    break;\n                }\n                q.offer(null);\n                continue;\n            }\n            values.add(node.val);\n            if (node.left != null) {\n                q.offer(node.left);\n            }\n            if (node.right != null) {\n                q.offer(node.right);\n            }\n        }\n\n        return results;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversalTest.java",
    "content": "package binaryTreeLevelOrderTraversal;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 8/10/15.\n */\npublic class binaryTreeLevelOrderTraversalTest {\n\n    @Test\n    public void testLevelOrder() throws Exception {\n        ArrayList<TreeNode> inputs = new ArrayList<TreeNode>();\n\n        TreeNode t0 = new TreeNode(-15);\n        TreeNode t1 = new TreeNode(5);\n        TreeNode t2 = new TreeNode(6);\n        TreeNode t3 = new TreeNode(-8);\n        TreeNode t4 = new TreeNode(1);\n        TreeNode t5 = new TreeNode(3);\n        TreeNode t6 = new TreeNode(9);\n        TreeNode t7 = new TreeNode(2);\n        TreeNode t8 = new TreeNode(6);\n\n        t0.left = t1;\n        t0.right = t2;\n\n        t1.left = t3;\n        t1.right = t4;\n\n        t2.left = t5;\n        t2.right = t6;\n\n        t3.left = t7;\n        t3.right = t8;\n\n        inputs.add(t0);\n\n        ArrayList<ArrayList<ArrayList<Integer>>> results = new ArrayList<ArrayList<ArrayList<Integer>>>(){{\n            add(new ArrayList<ArrayList<Integer>>(){{\n                add(new ArrayList<Integer>(){{\n                   add(-15);\n                }});\n                add(new ArrayList<Integer>(){{\n                    add(5);\n                    add(6);\n                }});\n                add(new ArrayList<Integer>(){{\n                    add(-8);\n                    add(1);\n                    add(3);\n                    add(9);\n                }});\n                add(new ArrayList<Integer>(){{\n                    add(2);\n                    add(6);\n                }});\n            }});\n        }};\n\n        for (int i = 0; i < results.size(); i++) {\n            binaryTreeLevelOrderTraversal b = new binaryTreeLevelOrderTraversal();\n            List<List<Integer>> r = b.levelOrder(inputs.get(i));\n            System.out.println(r.size());\n            for (int j = 0; j < r.size(); j++) {\n                System.out.println(Arrays.toString(r.toArray()));\n            }\n            assertTrue(r.containsAll(results.get(i)) && r.size() == results.get(i).size());\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/binaryTreeMaximumPathSum/TreeNode.java",
    "content": "package binaryTreeMaximumPathSum;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeMaximumPathSum/binaryTreeMaximumPathSum.java",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/\n// Inspired by : http://www.jiuzhang.com/solutions/binary-tree-maximum-path-sum/\n// Author : Lei Cao\n// Date   : 2015-10-08\n\n/**********************************************************************************\n *\n * Given a binary tree, find the maximum path sum.\n *\n * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.\n * The path does not need to go through the root.\n *\n *\n *\n * For example:\n * Given the below binary tree,\n *\n *        1\n *       / \\\n *      2   3\n *\n * Return 6.\n *\n *\n **********************************************************************************/\n\npackage binaryTreeMaximumPathSum;\n\nimport java.util.Arrays;\nimport java.util.Collections;\n\n/**\n * Definition of TreeNode:\n * public class TreeNode {\n *     public int val;\n *     public TreeNode left, right;\n *     public TreeNode(int val) {\n *         this.val = val;\n *         this.left = this.right = null;\n *     }\n * }\n */\npublic class binaryTreeMaximumPathSum {\n    /**\n     * @param root: The root of binary tree.\n     * @return: An integer.\n     */\n    public int maxPathSum(TreeNode root) {\n        Result r = helper(root);\n        return r.sumToLeaf;\n    }\n\n    private class Result {\n        int sumToRoot = 0;\n        int sumToLeaf = 0;\n        Result(int sumToRoot, int sumToLeaf) {\n            this.sumToRoot = sumToRoot;\n            this.sumToLeaf = sumToLeaf;\n        }\n    }\n\n    // [9,6,-3,null,null,-6,2,null,null,2,null,-6,-6,-6]\n    private Result helper(TreeNode root) {\n        if (root == null) {\n            return new Result(0, Integer.MIN_VALUE);\n        }\n\n        if (root.left == null && root.right == null) {\n            return new Result(root.val, root.val);\n        }\n\n        Result left = helper(root.left);\n        Result right = helper(root.right);\n\n        // @todo refactor the logic below\n        int sumToRoot = root.val;\n        int sumsOfSTR = Math.max(left.sumToRoot, right.sumToRoot);\n        if (sumsOfSTR > 0) {\n            sumToRoot = root.val + sumsOfSTR;\n        }\n\n\n        int sumOfTree = root.val + left.sumToRoot + right.sumToRoot;\n        int sumToLeft = root.val + left.sumToRoot;\n        int sumToRight = root.val + right.sumToRoot;\n\n        int max1 = Math.max(root.val, sumOfTree);\n        int max2 = Math.max(sumToLeft, sumToRight);\n        int max3 = Math.max(left.sumToLeaf, right.sumToLeaf);\n        int max4 = Math.max(max1, max2);\n        int max = Math.max(max3, max4);\n\n        return new Result(sumToRoot, max);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreeMaximumPathSum/binaryTreeMaximumPathSumTest.java",
    "content": "package binaryTreeMaximumPathSum;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 8/10/15.\n */\npublic class binaryTreeMaximumPathSumTest {\n\n    @Test\n    public void testMaxPathSum() throws Exception {\n        ArrayList<TreeNode> inputs = new ArrayList<TreeNode>();\n\n        TreeNode t0 = new TreeNode(-15);\n        TreeNode t1 = new TreeNode(5);\n        TreeNode t2 = new TreeNode(6);\n        TreeNode t3 = new TreeNode(-8);\n        TreeNode t4 = new TreeNode(1);\n        TreeNode t5 = new TreeNode(3);\n        TreeNode t6 = new TreeNode(9);\n        TreeNode t7 = new TreeNode(2);\n        TreeNode t8 = new TreeNode(6);\n        TreeNode t9 = new TreeNode(0);\n        TreeNode t10 = new TreeNode(4);\n        TreeNode t11 = new TreeNode(-1);\n        TreeNode t12 = new TreeNode(10);\n\n        t0.left = t1;\n        t0.right = t2;\n\n        t1.left = t3;\n        t1.right = t4;\n\n        t2.left = t5;\n        t2.right = t6;\n\n        t3.left = t7;\n        t3.right = t8;\n\n        t6.right = t9;\n\n        t9.left = t10;\n        t9.right = t11;\n\n        t11.left = t12;\n\n\n        TreeNode n1 = new TreeNode(9);\n        TreeNode n2 = new TreeNode(6);\n        TreeNode n3 = new TreeNode(-3);\n        TreeNode n4 = new TreeNode(-6);\n        TreeNode n5 = new TreeNode(2);\n        TreeNode n6 = new TreeNode(2);\n        TreeNode n7 = new TreeNode(-6);\n        TreeNode n8 = new TreeNode(-6);\n        TreeNode n9 = new TreeNode(-6);\n\n        n1.left = n2;\n        n1.right = n3;\n\n        n3.left = n4;\n        n3.right = n5;\n\n        n5.left = n6;\n\n        n6.left = n7;\n        n6.right = n8;\n\n        n7.left = n9;\n\n\n\n//        inputs.add(t0);\n        inputs.add(n1);\n        int[] results = {\n//                27,\n                16\n        };\n\n        for (int i = 0; i < results.length; i++) {\n            binaryTreeMaximumPathSum b = new binaryTreeMaximumPathSum();\n            int r = b.maxPathSum(inputs.get(i));\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/binaryTreePreorderTraversal/TreeNode.java",
    "content": "package binaryTreePreorderTraversal;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.java",
    "content": "// Source : https://oj.leetcode.com/problems/binary-tree-preorder-traversal/\n// Inspired by : http://www.jiuzhang.com/solutions/binary-tree-preorder-traversal/\n// Author : Lei Cao\n// Date   : 2015-10-05\n\n/**********************************************************************************\n *\n * Given a binary tree, return the preorder traversal of its nodes' values.\n *\n * For example:\n * Given binary tree {1,#,2,3},\n *\n *    1\n *     \\\n *      2\n *     /\n *    3\n *\n * return [1,2,3].\n *\n * Note: Recursive solution is trivial, could you do it iteratively?\n *\n **********************************************************************************/\n\npackage binaryTreePreorderTraversal;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class binaryTreePreorderTraversal {\n\n    //Version 1: Traverse\n    public List<Integer> preorderTraversal(TreeNode root) {\n        List<Integer>  results = new ArrayList<Integer>();\n        traversal(results, root);\n        return results;\n\n    }\n\n    private void traversal(List<Integer> results, TreeNode root) {\n        if (results == null || root == null) {\n            return;\n        }\n        results.add(root.val);\n        traversal(results, root.left);\n        traversal(results, root.right);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversalTest.java",
    "content": "package binaryTreePreorderTraversal;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 6/10/15.\n */\npublic class binaryTreePreorderTraversalTest {\n\n    /**\n     *          0\n     *        /   \\\n     *      1      2\n     *     / \\      \\\n     *   3    4      6\n     *      /\n     *      5\n     */\n    @Test\n    public void testPreorderTraversal() throws Exception {\n        TreeNode t0 = new TreeNode(0);\n\n        TreeNode n0 = new TreeNode(0);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        TreeNode n3 = new TreeNode(3);\n        TreeNode n4 = new TreeNode(4);\n        TreeNode n5 = new TreeNode(5);\n        TreeNode n6 = new TreeNode(6);\n\n        n0.left = n1;\n        n0.right = n2;\n        n1.left = n3;\n        n1.right = n4;\n        n4.left = n5;\n        n2.right = n6;\n\n\n        ArrayList<TreeNode> inputes = new ArrayList<TreeNode>();\n        inputes.add(t0);\n        inputes.add(n0);\n\n        List<List<Integer>> results = new ArrayList<List<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                   add(0);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(0);\n                add(1);\n                add(3);\n                add(4);\n                add(5);\n                add(2);\n                add(6);\n            }});\n        }};\n\n        binaryTreePreorderTraversal b = new binaryTreePreorderTraversal();\n        for (int i = 0; i < results.size(); i++) {\n            List<Integer> r = b.preorderTraversal(inputes.get(i));\n            assertEquals(results.get(i), r);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/containerwithmostwater.java",
    "content": "// Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).\n// n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).\n// Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.\n\n// Notice that you may not slant the container.\n\n// Solution: Start with walls at either end. If the current area is greater than the max area, update it.\n// At each step, move the shorter wall one step towards the longer wall and recalculate. O(n) complexity. \n\nclass Solution {\n    public int maxArea(int[] height) {\n        List<Integer> list = new ArrayList<Integer>();\n        int start = 0, end = height.length - 1, multiplier = height.length - 1;\n        int maxarea = Integer.MIN_VALUE;\n\n        while (multiplier != 0) {\n       \n            maxarea = Integer.max(maxarea, Integer.min(height[start], height[end]) * multiplier--);\n            if (height[start] > height[end]) {\n                end--;\n            } else {\n                start++;\n            }\n        }\n        return maxarea;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/countAndSay/CountAndSay.java",
    "content": "// Source : https://leetcode.com/problems/count-and-say/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * The count-and-say sequence is the sequence of integers with the first five terms as following:\n * \n *  1.     1\n *  2.     11\n *  3.     21\n *  4.     1211\n *  5.     111221\n * 1 is read off as \"one 1\" or 11.\n * 11 is read off as \"two 1s\" or 21.\n * 21 is read off as \"one 2, then one 1\" or 1211.\n * Given an integer n, generate the nth term of the count-and-say sequence.\n * \n * Note: Each term of the sequence of integers will be represented as a string.\n * \n * Example 1:\n * \n *  Input: 1\n *  Output: \"1\"\n * \n * Example 2:\n * \n *  Input: 4\n *  Output: \"1211\"\n * \n **********************************************************************************/\npackage countAndSay;\n\npublic class CountAndSay {\n\n\tpublic String nextString(String str) {\n\t\tStringBuilder next = new StringBuilder();\n\t\tint len = str.length();\n\t\tint i = 0;\n\t\twhile (i < len) {\n\t\t\tint j = i;\n\t\t\tint count = 0;\n\t\t\tchar currentNumber = str.charAt(i);\n\t\t\twhile (j < len && str.charAt(j) == currentNumber) {\n\t\t\t\tj++;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tnext.append(count).append(currentNumber);\n\t\t\ti = j;\n\t\t}\n\t\treturn next.toString();\n\t}\n\tpublic String countAndSay(int n) {\n\t\tif (n <= 1) {\n\t\t\treturn \"1\";\n\t\t} else {\n\t\t\tString p = \"1\";\n\t\t\tfor (int i = 2; i <= n; i++) {\n\t\t\t\tString next = nextString(p);\n\t\t\t\tp = next;\n\t\t\t}\n\t\t\treturn p;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/java/src/countAndSay/TestCountAndSay.java",
    "content": "package countAndSay;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 38. Count and Say\n */\npublic class TestCountAndSay {\n\t@Test\n\tpublic void test() {\n\t\tCountAndSay solution = new CountAndSay();\n\t\tString next5 = solution.countAndSay(5);\n\t\tAssert.assertTrue(next5.equals(\"111221\"));\n\t\tString next6 = solution.countAndSay(6);\n\t\tAssert.assertTrue(next6.equals(\"312211\"));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/climbStairs/climbStairs.java",
    "content": "// Source : https://oj.leetcode.com/problems/climbing-stairs/\n// Inspired by : http://www.jiuzhang.com/solutions/climbing-stairs/\n// Author : Lei Cao\n// Date   : 2015-10-12\n\n/**********************************************************************************\n *\n * You are climbing a stair case. It takes n steps to reach to the top.\n *\n * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n *\n *\n **********************************************************************************/\n\npackage dynamicProgramming.climbStairs;\n\npublic class climbStairs {\n    /**\n     * @param n: An integer\n     * @return: An integer\n     */\n    public int climbStairs(int n) {\n        int[] matrix = new int[n];\n        if (n < 3) {\n            return n;\n        }\n        matrix[0] = 1;\n        matrix[1] = 2;\n        // write your code here\n        for (int i = 2; i < matrix.length; i++) {\n            matrix[i] = matrix[i-1] + matrix[i-2];\n        }\n        return matrix[n-1];\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/climbStairs/climbStairsTest.java",
    "content": "package dynamicProgramming.climbStairs;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 12/10/15.\n */\npublic class climbStairsTest {\n\n    @Test\n    public void testClimbStairs() throws Exception {\n        int[] inputs = {1,2,3,4};\n\n        int[] results = {1,2,3,5};\n\n        for (int i = 0; i < results.length; i++) {\n            climbStairs c = new climbStairs();\n            int r = c.climbStairs(inputs[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/minimumPathSum/minimumPathSum.java",
    "content": "// Source : https://oj.leetcode.com/problems/minimum-path-sum/\n// Inspired by : http://www.jiuzhang.com/solutions/minimum-path-sum/\n// Author : Lei Cao\n// Date   : 2015-10-12\n\n/**********************************************************************************\n *\n * Given a m x n grid filled with non-negative numbers, find a path from top left to\n * bottom right which minimizes the sum of all numbers along its path.\n *\n * Note: You can only move either down or right at any point in time.\n *\n **********************************************************************************/\n\npackage dynamicProgramming.minimumPathSum;\n\npublic class minimumPathSum {\n    /**\n     * @param grid: a list of lists of integers.\n     * @return: An integer, minimizes the sum of all numbers along its path\n     */\n    public int minPathSum(int[][] grid) {\n        if (grid.length == 0 || grid[0].length == 0) {\n            return 0;\n        }\n        int m = grid.length;\n        int n = grid[0].length;\n        int[][] matrix = new int[m][n];\n\n        matrix[0][0] = grid[0][0];\n        for (int i = 1; i < m; i++) {\n            matrix[i][0] = grid[i][0] + matrix[i-1][0];\n        }\n\n        for (int i = 1; i < n; i++) {\n            matrix[0][i] = grid[0][i] + matrix[0][i-1];\n        }\n\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                matrix[i][j] = grid[i][j] + Math.min(matrix[i-1][j], matrix[i][j-1]);\n            }\n        }\n\n        return matrix[m-1][n-1];\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/minimumPathSum/minimumPathSumTest.java",
    "content": "package dynamicProgramming.minimumPathSum;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 12/10/15.\n */\npublic class minimumPathSumTest {\n\n    @Test\n    public void testMinPathSum() throws Exception {\n        int[][][] inputs = {\n            {\n                {1,2},\n                {1,2},\n            }\n        };\n\n        int [] results = {4};\n\n        for (int i = 0; i < results.length; i++) {\n            minimumPathSum m = new minimumPathSum();\n            int r = m.minPathSum(inputs[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/triangle/triangle.java",
    "content": "// Source : https://oj.leetcode.com/problems/triangle/\n// Inspired by : http://www.jiuzhang.com/solutions/triangle/\n// Author : Lei Cao\n// Date   : 2015-10-12\n\n/**********************************************************************************\n *\n * Given a triangle, find the minimum path sum from top to bottom.\n * Each step you may move to adjacent numbers on the row below.\n *\n * For example, given the following triangle\n *\n * [\n *      [2],\n *     [3,4],\n *    [6,5,7],\n *   [4,1,8,3]\n * ]\n *\n * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\n *\n * Note:\n * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.\n *\n *\n **********************************************************************************/\n\npackage dynamicProgramming.triangle;\n\nimport java.util.List;\n\n/**\n * Created by leicao on 12/10/15.\n */\npublic class triangle {\n    /**\n     * @param triangle: a list of lists of integers.\n     * @return: An integer, minimum path sum.\n     */\n    public int minimumTotal1(List<List<Integer>> triangle) {\n        if (triangle == null) {\n            return 0;\n        }\n        int rows = triangle.size();\n        int[][] matrix = new int[rows][rows];\n        matrix[0][0] = triangle.get(0).get(0);\n        for (int i = 1; i < rows; i++) {\n            matrix[i][0] = triangle.get(i).get(0) + matrix[i-1][0];\n        }\n\n        for (int i = 1; i < rows; i++) {\n            matrix[i][i] = triangle.get(i).get(i) + matrix[i - 1][i - 1];\n        }\n\n        for (int i = 1; i < rows; i++) {\n            for (int j = 1; j < i; j++) {\n                matrix[i][j] = Math.min(matrix[i-1][j-1], matrix[i-1][j]) + triangle.get(i).get(j);\n            }\n        }\n        int minimum = matrix[rows - 1][0];\n        for (int i = 1; i < rows; i++) {\n            if (matrix[rows - 1][i] < minimum) {\n                minimum = matrix[rows - 1][i];\n            }\n        }\n        return minimum;\n    }\n\n    public int minimumTotal2(int[][] triangle) {\n        if (triangle == null) {\n            return 0;\n        }\n        int rows = triangle.length;\n        int[][] matrix = new int[rows][rows];\n        matrix[0][0] = triangle[0][0];\n        for (int i = 1; i < rows; i++) {\n            matrix[i][0] = triangle[i][0] + matrix[i-1][0];\n        }\n\n        for (int i = 1; i < rows; i++) {\n            matrix[i][i] = triangle[i][i] + matrix[i - 1][i - 1];\n        }\n\n        for (int i = 1; i < rows; i++) {\n            for (int j = 1; j < i; j++) {\n                matrix[i][j] = Math.min(matrix[i-1][j-1], matrix[i-1][j]) + triangle[i][j];\n            }\n        }\n        int minimum = matrix[rows - 1][0];\n        for (int i = 1; i < rows; i++) {\n            if (matrix[rows - 1][i] < minimum) {\n                minimum = matrix[rows - 1][i];\n            }\n        }\n        return minimum;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/triangle/triangleTest.java",
    "content": "package dynamicProgramming.triangle;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 15/10/15.\n */\npublic class triangleTest {\n\n    @Test\n    public void testMinimumTotal() throws Exception {\n        int[][][] inputes = {\n            {\n                {2},\n                {3,4},\n                {6,5,7},\n                {4,1,8,3},\n            }\n        };\n\n        int[] results = {11};\n\n        for (int i = 0; i < results.length; i++) {\n            triangle t = new triangle();\n            int r = t.minimumTotal2(inputes[i]);\n            assertEquals(results[i], r);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/uniquePaths/uniquePaths.java",
    "content": "// Source : https://oj.leetcode.com/problems/unique-paths/\n// Inspired by : http://www.jiuzhang.com/solutions/unique-paths/\n// Author : Lei Cao\n// Date   : 2015-10-11\n\n/**********************************************************************************\n *\n * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).\n *\n * The robot can only move either down or right at any point in time. The robot is trying to reach\n * the bottom-right corner of the grid (marked 'Finish' in the diagram below).\n *\n *\n *    start                                                  \n *    +---------+----+----+----+----+----+\n *    |----|    |    |    |    |    |    |\n *    |----|    |    |    |    |    |    |\n *    +----------------------------------+\n *    |    |    |    |    |    |    |    |\n *    |    |    |    |    |    |    |    |\n *    +----------------------------------+\n *    |    |    |    |    |    |    |----|\n *    |    |    |    |    |    |    |----|\n *    +----+----+----+----+----+---------+\n *                                   finish\n *\n *\n * How many possible unique paths are there?\n *\n * Above is a 3 x 7 grid. How many possible unique paths are there?\n *\n * Note: m and n will be at most 100.\n *\n **********************************************************************************/\n\npackage dynamicProgramming.uniquePaths;\n\npublic class uniquePaths {\n    /**\n     * @param n, m: positive integer (1 <= n ,m <= 100)\n     * @return an integer\n     */\n    public int uniquePaths(int m, int n) {\n        // write your code here\n        int[][] matrix = new int[m][n];\n        for (int i = 0; i < m; i++) {\n            matrix[i][0] = 1;\n        }\n        for (int i = 0; i < n; i++) {\n            matrix[0][i] = 1;\n        }\n\n        for (int i = 1; i < m; i++)  {\n            for (int j = 1; j < n; j++) {\n                matrix[i][j] = matrix[i-1][j] + matrix[i][j-1];\n            }\n        }\n        return matrix[m-1][n-1];\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsII.java",
    "content": "// Source : https://oj.leetcode.com/problems/unique-paths-ii/\n// Inspired by : http://www.jiuzhang.com/solutions/unique-paths/\n// Author : Lei Cao\n// Date   : 2015-10-11\n\n/**********************************************************************************\n *\n * Follow up for \"Unique Paths\":\n *\n * Now consider if some obstacles are added to the grids. How many unique paths would there be?\n *\n * An obstacle and empty space is marked as 1 and 0 respectively in the grid.\n *\n * For example,\n * There is one obstacle in the middle of a 3x3 grid as illustrated below.\n *\n * [\n *   [0,0,0],\n *   [0,1,0],\n *   [0,0,0]\n * ]\n *\n * The total number of unique paths is 2.\n *\n * Note: m and n will be at most 100.\n *\n **********************************************************************************/\n\npackage dynamicProgramming.uniquePaths;\n\npublic class uniquePathsII {\n    /**\n     * @param obstacleGrid: A list of lists of integers\n     * @return: An integer\n     */\n    public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n        if (obstacleGrid.length == 0 || obstacleGrid[0].length ==0) {\n            return 0;\n        }\n        if (obstacleGrid[0][0] == 1) {\n            return 0;\n        }\n        int m = obstacleGrid.length;\n        int n = obstacleGrid[0].length;\n        // write your code here\n        int[][] matrix = new int[m][n];\n        for (int i = 0; i < m; i++) {\n            if (obstacleGrid[i][0] != 1) {\n                matrix[i][0] = 1;\n            } else {\n                break;\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            if (obstacleGrid[0][i] != 1) {\n                matrix[0][i] = 1;\n            } else {\n                break;\n            }\n        }\n\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                if (obstacleGrid[i][j] == 1) {\n                    matrix[i][j] = 0;\n                } else {\n                    matrix[i][j] = matrix[i-1][j] + matrix[i][j-1];\n                }\n            }\n        }\n        return matrix[m-1][n-1];\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsIITest.java",
    "content": "package dynamicProgramming.uniquePaths;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 11/10/15.\n */\npublic class uniquePathsIITest {\n\n    @Test\n    public void testUniquePathsWithObstacles() throws Exception {\n        int[][][] inputs = {\n            {\n                {0,0,0},\n                {0,1,0},\n                {0,0,0},\n            }\n        };\n        int[] results = {2};\n        for (int i = 0; i < inputs.length; i++) {\n            uniquePathsII u = new uniquePathsII();\n            int r = u.uniquePathsWithObstacles(inputs[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsTest.java",
    "content": "package dynamicProgramming.uniquePaths;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 11/10/15.\n */\npublic class uniquePathsTest {\n\n    @Test\n    public void testUniquePaths() throws Exception {\n        int[][] inputs = {\n                {2,2},\n                {3,7},\n        };\n        int[] results = {2,28};\n        for (int i = 0; i < inputs.length; i++) {\n            uniquePaths u = new uniquePaths();\n            int r = u.uniquePaths(inputs[i][0], inputs[i][1]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.java",
    "content": "// Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n// Inspired by : http://www.jiuzhang.com/solutions/find-minimum-in-rotated-sorted-array/\n// Author : Lei Cao\n// Date   : 2014-10-05\n\n/**********************************************************************************\n *\n * Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n *\n * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n *\n * Find the minimum element.\n *\n * You may assume no duplicate exists in the array.\n *\n **********************************************************************************/\n\npackage findMinimumInRotatedSortedArray;\n\npublic class findMinimumInRotatedSortedArray {\n    public int findMin(int[] num) {\n        if (num == null || num.length == 0) {\n            return Integer.MIN_VALUE;\n        }\n\n        int start = 0;\n        int end = num.length - 1;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (num[start] < num[end]) {\n                end = mid;\n            } else if (num[start] < num[mid]) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (num[start] < num[end]) {\n            return num[start];\n        } else {\n            return num[end];\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArrayTest.java",
    "content": "package findMinimumInRotatedSortedArray;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class findMinimumInRotatedSortedArrayTest {\n\n    @Test\n    public void testFindMin() throws Exception {\n        int[][] inputs = {\n            {4,5,6,7,0,1,2},\n            {1,2,3},\n            {2,3,1},\n            {1,2,3,4},\n            {2,3,4,1}\n        };\n\n        int [] results = {0,1,1,1,1};\n\n        findMinimumInRotatedSortedArray f = new findMinimumInRotatedSortedArray();\n        for (int i = 0; i < results.length; i++) {\n            int r = f.findMin(inputs[i]);\n            System.out.println(results[i]);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/findPeakElement/findPeakElement.java",
    "content": "// Source : https://oj.leetcode.com/problems/find-peak-element/\n// Inspired by : http://www.jiuzhang.com/solutions/find-peak-element/\n// Author : Lei Cao\n// Date   : 2014-10-05\n\n/**********************************************************************************\n *\n * A peak element is an element that is greater than its neighbors.\n *\n * Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.\n *\n * You may imagine that num[-1] = num[n] = -∞.\n *\n * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.\n *\n * click to show spoilers.\n *\n * Note:\n * Your solution should be in logarithmic complexity.\n *\n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *\n **********************************************************************************/\n\npackage findPeakElement;\n\npublic class findPeakElement {\n    public int findPeakElement(int[] nums) {\n        if (nums.length == 0) {\n            return Integer.MIN_VALUE;\n        }\n\n        int start = 0;\n        int end = nums.length - 1;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) {\n                return mid;\n            } else if (nums[mid - 1] < nums[mid]) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (nums[start] > nums[end]) {\n            return start;\n        } else {\n            return end;\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/findPeakElement/findPeakElementTest.java",
    "content": "package findPeakElement;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class findPeakElementTest {\n\n    @Test\n    public void testFindPeak() throws Exception {\n        //* For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.\n        int [][] inputs = {\n            {1,2,3,1}\n        };\n        int[] results = {2};\n\n        findPeakElement f = new findPeakElement();\n        for (int i = 0; i < results.length; i++) {\n            int r = f.findPeakElement(inputs[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/firstBadVersion/VersionControl.java",
    "content": "package firstBadVersion;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class VersionControl {\n    int firstBadVersion;\n    boolean isBadVersion(int version) {\n        if (version >= firstBadVersion) {\n            return true;\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/firstBadVersion/firstBadVersion.java",
    "content": "// Source : https://leetcode.com/problems/first-bad-version/\n// Inspired by : http://www.jiuzhang.com/solutions/first-bad-version/\n// Author : Lei Cao\n// Date   : 2014-10-05\n\n/**********************************************************************************\n *\n * The code base version is an integer start from 1 to n.\n * One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests.\n * Find the first bad version.\n *\n * You can call isBadVersion to help you determine which version is the first bad one.\n * The details interface can be found in the code's annotation part.\n *\n **********************************************************************************/\n\npackage firstBadVersion;\n\n/* The isBadVersion API is defined in the parent class VersionControl.\n      boolean isBadVersion(int version); */\npublic class firstBadVersion extends VersionControl {\n    public int firstBadVersion(int n) {\n        if (n < 1) {\n            return 0;\n        }\n        int start = 1;\n        int end = n;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (super.isBadVersion(mid)) {\n                end = mid;\n            } else {\n                start = mid;\n            }\n        }\n\n        if (super.isBadVersion(start)) {\n            return start;\n        }\n        if (super.isBadVersion(end)) {\n            return end;\n        }\n        return 0;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/firstBadVersion/firstBadVersionTest.java",
    "content": "package firstBadVersion;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class firstBadVersionTest {\n\n    @Test\n    public void testFirstBadVersion() throws Exception {\n        int[] inputs = {1,22,34,40,5232,6342342,71231};\n        int[] targets = {1, 10, 20, 25, 323, 45454, 23232};\n\n        firstBadVersion f = new firstBadVersion();\n        for (int i = 0; i < targets.length; i++) {\n            f.firstBadVersion = targets[i];\n            int r = f.firstBadVersion(inputs[i]);\n            System.out.println(r);\n            assertEquals(targets[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/inorderSuccessorInBST/TreeNode.java",
    "content": "package inorderSuccessorInBST;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBST.java",
    "content": "// Source : http://www.lintcode.com/en/problem/inorder-successor-in-bst/\n//          https://leetcode.com/problems/inorder-successor-in-bst/\n// Inspired by : http://www.jiuzhang.com/solutions/inorder-successor-in-bst/\n// Author : Lei Cao\n// Date   : 2015-10-06\n\n/**********************************************************************************\n *\n * Given a binary search tree and a node in it, find the in-order successor of that node in the BST.\n *\n * Example\n * Given tree = [2,1] and node = 1:\n *\n *    2\n *   /\n *  1\n * return node 2.\n *\n * Given tree = [2,1,3] and node = 2:\n *\n *    2\n *   / \\\n *  1  3\n *\n * return node 3.\n *\n * Note\n * If the given node has no in-order successor in the tree, return null.\n *\n * Challenge\n * O(h), where h is the height of the BST.\n **********************************************************************************/\n\npackage inorderSuccessorInBST;\n\npublic class inorderSuccessorInBST {\n    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {\n        TreeNode successor = null;\n        if (root == null) {\n            return null;\n        }\n        while (root != null && root.val != p.val) {\n            if (root.val > p.val) {\n                successor = root;\n                root = root.left;\n            } else {\n                root = root.right;\n            }\n        }\n\n        if (root == null) {\n            return null;\n        }\n\n        if (root.right == null) {\n            return successor;\n        }\n\n        root = root.right;\n        while (root.left != null) {\n            root = root.left;\n        }\n        return root;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBSTTest.java",
    "content": "package inorderSuccessorInBST;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 7/10/15.\n */\npublic class inorderSuccessorInBSTTest {\n\n    @Test\n    public void testInorderSuccessor() throws Exception {\n        ArrayList<TreeNode> inputes = new ArrayList<>();\n        ArrayList<TreeNode> targets = new ArrayList<>();\n\n        TreeNode n0 = new TreeNode(2);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(3);\n        n0.left = n1;\n        n0.right = n2;\n        inputes.add(n0);\n        targets.add(n2);\n\n        TreeNode nn0 = new TreeNode(2);\n        TreeNode nn1 = new TreeNode(1);\n        nn0.left = nn1;\n        inputes.add(nn0);\n        targets.add(nn1);\n\n        TreeNode t0 = new TreeNode(1);\n        TreeNode t1 = new TreeNode(2);\n        t0.right = t1;\n        inputes.add(t0);\n        targets.add(t0);\n\n\n        ArrayList<TreeNode> results = new ArrayList<>();\n        results.add(null);\n        results.add(nn0);\n        results.add(t1);\n\n        for (int i = 0; i < results.size(); i++) {\n            inorderSuccessorInBST finder = new inorderSuccessorInBST();\n            TreeNode node = finder.inorderSuccessor(inputes.get(i), targets.get(i));\n            System.out.println(node);\n            boolean result = node == results.get(i)  || node.val == results.get(i).val;\n            assertTrue(result);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java",
    "content": "// Source : https://leetcode.com/problems/length-of-last-word/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.\n * \n * If the last word does not exist, return 0.\n * \n * Note: A word is defined as a character sequence consists of non-space characters only.\n * \n * Example:\n * \n *  Input: \"Hello World\"\n *  Output: 5\n * \n **********************************************************************************/\npackage lengthOfLastWord;\n\npublic class LengthOfLastWord {\n\n\tpublic int lengthOfLastWord(String s) {\n\t\t// don't forget rangeCheck\n\t\tif (s == null || s.length() == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint len = s.length();\n\t\tint i = len - 1;\n\t\twhile (i >= 0 && s.charAt(i) == ' ') {\n\t\t\ti--;\n\t\t}\n\t\tif (i == -1) {\n\t\t\treturn 0;\n\t\t}\n\t\tint count = 0;\n\t\twhile (i >= 0 && s.charAt(i) != ' ') {\n\t\t\tcount++;\n\t\t\ti--;\n\t\t}\n\t\treturn count;\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/java/src/lengthOfLastWord/TestLengthOfLastWord.java",
    "content": "package lengthOfLastWord;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 58. Length of Last Word\n */\npublic class TestLengthOfLastWord {\n\t@Test\n\tpublic void test() {\n\t\tLengthOfLastWord solution = new LengthOfLastWord();\n\t\tString str1 = \"Hello World\";\n\t\tAssert.assertTrue(solution.lengthOfLastWord(str1) == 5);\n\t\tString str2 = \"Thank you very much  \";\n\t\tAssert.assertTrue(solution.lengthOfLastWord(str2) == 4);\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/lowestCommonAncestorOfABinaryTree/TreeNode.java",
    "content": "package lowestCommonAncestorOfABinaryTree;\n\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTree.java",
    "content": "// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/lowest-common-ancestor/\n// Author : Lei Cao\n// Date   : 2015-10-07\n\n/**********************************************************************************\n *\n * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the\n * tree.\n *\n * According to the definition of LCA on Wikipedia: “The lowest common ancestor is\n * defined between two nodes v and w as the lowest node in T that has both v and w as\n * descendants (where we allow a node to be a descendant of itself).”\n *\n *         _______3______\n *        /              \\\n *     ___5__          ___1__\n *    /      \\        /      \\\n *    6      _2       0       8\n *          /  \\\n *          7   4\n *\n * For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example\n * is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according\n * to the LCA definition.\n *\n *\n *\n **********************************************************************************/\n\npackage lowestCommonAncestorOfABinaryTree;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\n/**\n * Definition of TreeNode:\n * public class TreeNode {\n *     public int val;\n *     public TreeNode left, right;\n *     public TreeNode(int val) {\n *         this.val = val;\n *         this.left = this.right = null;\n *     }\n * }\n */\npublic class lowestCommonAncestorOfABinaryTree {\n    /**\n     * @param root: The root of the binary search tree.\n     * @param A and B: two nodes in a Binary.\n     * @return: Return the least common ancestor(LCA) of the two nodes.\n     */\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {\n        if (root == null || root == A || root == B) {\n            return root;\n        }\n        TreeNode left = lowestCommonAncestor(root.left, A, B);\n        TreeNode right = lowestCommonAncestor(root.right, A, B);\n        if (left != null && right != null) {\n            return root;\n        }\n\n        if (left != null) {\n            return left;\n        }\n\n        if (right != null) {\n            return right;\n        }\n        return null;\n    }\n}\n\n\n\n"
  },
  {
    "path": "algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTreeTest.java",
    "content": "package lowestCommonAncestorOfABinaryTree;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 7/10/15.\n */\npublic class lowestCommonAncestorOfABinaryTreeTest {\n\n    @Test\n    public void testLowestCommonAncestor() throws Exception {\n        ArrayList<TreeNode> inputeRoots = new ArrayList<>();\n        ArrayList<TreeNode> inputeAs = new ArrayList<>();\n        ArrayList<TreeNode> inputeBs = new ArrayList<>();\n        ArrayList<TreeNode> results = new ArrayList<>();\n\n        TreeNode n0 = new TreeNode(0);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        n0.left = n1;\n        n0.right = n2;\n        inputeRoots.add(n0);\n        inputeAs.add(n1);\n        inputeBs.add(n2);\n        results.add(n0);\n\n        for (int i = 0; i < results.size(); i++) {\n            lowestCommonAncestorOfABinaryTree l = new lowestCommonAncestorOfABinaryTree();\n            TreeNode r = l.lowestCommonAncestor(inputeRoots.get(i), inputeAs.get(i), inputeBs.get(i));\n            assertEquals(results.get(i).val, r.val);\n        }\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/lruCache/LRUCache.java",
    "content": "/*\nAnalogous to the C++ solution at:\nhttps://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp\nwhich uses linked list + hash map. But the Java stdlib provides LinkedHashMap\nwhich already implements that for us, making this solution shorter.\n\nThis could also be done by using, but that generates\nsome inheritance boilerplate, and ends up taking the same number of lines:\nhttps://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd\n*/\n\nimport java.util.LinkedHashMap;\nimport java.util.Iterator;\n\npublic class LRUCache {\n\n    private int capacity;\n    private LinkedHashMap<Integer,Integer> map;\n\n    public LRUCache(int capacity) {\n        this.capacity = capacity;\n        this.map = new LinkedHashMap<>();\n    }\n\n    public int get(int key) {\n        Integer value = this.map.get(key);\n        if (value == null) {\n            value = -1;\n        } else {\n            this.set(key, value);\n        }\n        return value;\n    }\n\n    public void set(int key, int value) {\n        if (this.map.containsKey(key)) {\n            this.map.remove(key);\n        } else if (this.map.size() == this.capacity) {\n            Iterator<Integer> it = this.map.keySet().iterator();\n            it.next();\n            it.remove();\n        }\n        map.put(key, value);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/lruCache/LRUCacheTest.java",
    "content": "import java.util.ArrayList;\n\nimport org.junit.Test;\nimport static org.junit.Assert.*;\n\npublic class LRUCacheTest {\n\n    private LRUCache c;\n\n    public LRUCacheTest() {\n        this.c = new LRUCache(2);\n    }\n\n    @Test\n    public void testCacheStartsEmpty() {\n        assertEquals(c.get(1), -1);\n    }\n\n    @Test\n    public void testSetBelowCapacity() {\n        c.set(1, 1);\n        assertEquals(c.get(1), 1);\n        assertEquals(c.get(2), -1);\n        c.set(2, 4);\n        assertEquals(c.get(1), 1);\n        assertEquals(c.get(2), 4);\n    }\n\n    @Test\n    public void testCapacityReachedOldestRemoved() {\n        c.set(1, 1);\n        c.set(2, 4);\n        c.set(3, 9);\n        assertEquals(c.get(1), -1);\n        assertEquals(c.get(2), 4);\n        assertEquals(c.get(3), 9);\n    }\n\n    @Test\n    public void testGetRenewsEntry() {\n        c.set(1, 1);\n        c.set(2, 4);\n        assertEquals(c.get(1), 1);\n        c.set(3, 9);\n        assertEquals(c.get(1), 1);\n        assertEquals(c.get(2), -1);\n        assertEquals(c.get(3), 9);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/maximumDepthOfBinaryTree/TreeNode.java",
    "content": "package maximumDepthOfBinaryTree;\n\npublic class TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n    TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.java",
    "content": "// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/\n// Author : Lei Cao\n// Date   : 2015-10-03\n\n/**********************************************************************************\n *\n * Given a binary tree, find its maximum depth.\n *\n * The maximum depth is the number of nodes along the longest path from the root node\n * down to the farthest leaf node.\n *\n **********************************************************************************/\n\n\npackage maximumDepthOfBinaryTree;\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode(int x) { val = x; }\n * }\n */\npublic class maximumDepthOfBinaryTree {\n    public int maxDepth(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n        return theDepth(root);\n    }\n\n    private int theDepth(TreeNode root) {\n        int leftDepth = 1;\n        int rightDepth = 1;\n\n        if (root.left != null) {\n           leftDepth = theDepth(root.left) + 1;\n        }\n        if (root.right != null) {\n            rightDepth = theDepth(root.right) + 1;\n        }\n        return Math.max(leftDepth, rightDepth);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTreeTest.java",
    "content": "package maximumDepthOfBinaryTree;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class maximumDepthOfBinaryTreeTest {\n\n    @Test\n    public void testMaxDepth() throws Exception {\n        TreeNode t0 = new TreeNode(0);\n\n        TreeNode n0 = new TreeNode(0);\n        TreeNode n1 = new TreeNode(1);\n        TreeNode n2 = new TreeNode(2);\n        TreeNode n3 = new TreeNode(3);\n        TreeNode n4 = new TreeNode(5);\n        TreeNode n5 = new TreeNode(6);\n        TreeNode n6 = new TreeNode(6);\n\n        n0.left = n1;\n        n0.right = n2;\n        n1.left = n3;\n        n1.right = n4;\n        n4.left = n5;\n        n2.right = n6;\n\n        ArrayList<TreeNode> inputes = new ArrayList<>();\n        inputes.add(t0);\n        inputes.add(n0);\n        int[] results = {1,3};\n\n        maximumDepthOfBinaryTree m = new maximumDepthOfBinaryTree();\n        for (int i = 0; i < results.length; i++) {\n            int d = m.maxDepth(inputes.get(i));\n            System.out.println(d);\n            assertEquals(results[i], d);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/minStack/MinStack.java",
    "content": "// Source : https://leetcode.com/problems/min-stack/description/\n// Author : Tianming Cao\n// Date   : 2018-02-02\n\n/**********************************************************************************\n * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n *\n *\tpush(x) -- Push element x onto stack.\n *\tpop() -- Removes the element on top of the stack.\n *\ttop() -- Get the top element.\n *\tgetMin() -- Retrieve the minimum element in the stack.\n * Example:\n *\tMinStack minStack = new MinStack();\n *\tminStack.push(-2);\n *\tminStack.push(0);\n *\tminStack.push(-3);\n *\tminStack.getMin();   --> Returns -3.\n *\tminStack.pop();\n *\tminStack.top();      --> Returns 0.\n *\tminStack.getMin();   --> Returns -2.\n * \n **********************************************************************************/\npackage minStack;\n\nimport java.util.Stack;\n\npublic class MinStack {\n\tpublic Stack<Integer> mainStack;\n\t/**\n\t * Call an extra stack named assistStack to store the min value.\n\t * While we doing push operation, compare x with the top of assistStack and push the smaller value into assistStack.\n\t * The other operations pop,top and getMin is very simple.\n\t **/\n\tpublic Stack<Integer> assistStack;\n\tpublic MinStack() {\n\t\tmainStack = new Stack<Integer>();\n\t\tassistStack = new Stack<Integer>();\n\t}\n\tpublic void push(int x) {\n\t\tmainStack.push(x);\n\t\tif (assistStack.isEmpty()) {\n\t\t\tassistStack.push(x);\n\t\t} else {\n\t\t\tassistStack.push(Math.min(x, getMin()));\n\t\t}\n\t}\n\n\tpublic void pop() {\n\t\tmainStack.pop();\n\t\tassistStack.pop();\n\t}\n\n\tpublic int top() {\n\t\treturn mainStack.peek();\n\t}\n\n\tpublic int getMin() {\n\t\treturn assistStack.peek();\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/minStack/TestMinStack.java",
    "content": "package minStack;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 155. Min Stack\n */\npublic class TestMinStack {\n\t@Test\n\tpublic void test() {\n\t\tMinStack minStack = new MinStack();\n\t\tminStack.push(3);\n\t\tminStack.push(4);\n\t\tminStack.push(1);\n\t\tminStack.push(2);\n\t\tAssert.assertTrue(minStack.getMin() == 1);\n\t\tminStack.pop();\n\t\tminStack.pop();\n\t\tAssert.assertTrue(minStack.getMin() == 3);\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/myQueue/MyQueue.java",
    "content": "// Source : https://leetcode.com/problems/implement-queue-using-stacks/description/\n// Author : Tianming Cao\n// Date   : 2018-02-02\n\n/**********************************************************************************\n * Implement the following operations of a queue using stacks.\n *\n * \tpush(x) -- Push element x to the back of queue.\n *  pop() -- Removes the element from in front of queue.\n *  peek() -- Get the front element.\n *  empty() -- Return whether the queue is empty.\n *\n * Notes:\n *  You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.\n *  Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.\n *  You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).\n *\n **********************************************************************************/\npackage myQueue;\n\nimport java.util.Stack;\n\n/**\n * This problem is a sibling of problem 225(https://leetcode.com/problems/implement-stack-using-queues/description/)\n * The solution is:\n *\t1. stack1 is always in charge of push operation\n *\t2. stack2 is always in charge of peek and pop operation\n *\t3. if we want to do peek or pop operation, but stack2 is empty,\n *     we should first pop all the elements from stack1 and push them into stack2 in turn.\n * Give a Example:\n * \n *  First, push numbers \"1,2,3,4,5\" to stack1, then stack1's structure is:\n * \n * |5|\n * |4|\n * |3|\n * |2|\n * |1|\n * \n *\tSecond, if we want to get the front element \"1\",we should pop all the elements of stack1 and push them into stack2,\n *\tafter this, stack1 is empty, and stack2's structrue is:\n * \n * |1|\n * |2|\n * |3|\n * |4|\n * |5|\n * \n *\tSo we can get stack2's top element \"1\" as the front element of queue. \n * \n *\tNext, if we want to push \"6\" to the back of queue, we should push \"6\" into stack1 as before, so stack1's structure is:\n * \n * |6|\n * \n *\tFinally, if we want to do pop operation twice ,we should remove the top element of stack2 twice, so stack2's structure is:\n * \n * |3|\n * |4|\n * |5|\n * \n *\tas expect, the removed element is \"1\" and \"2\".\n */\npublic class MyQueue {\n\tpublic Stack<Integer> stack1;\n\tpublic Stack<Integer> stack2;\n\tpublic int size;\n\tpublic MyQueue() {\n\t\tstack1 = new Stack<>();\n\t\tstack2 = new Stack<>();\n\t\tsize = 0;\n\t}\n\n\tpublic void push(int x) {\n\t\tstack1.push(x);\n\t\tsize++;\n\t}\n\n\tpublic int pop() {\n\t\tif (stack2.isEmpty()) {\n\t\t\twhile (!stack1.isEmpty()) {\n\t\t\t\tstack2.push(stack1.pop());\n\t\t\t}\n\t\t}\n\t\tint value = stack2.pop();\n\t\tsize--;\n\t\treturn value;\n\t}\n\n\tpublic int peek() {\n\t\tif (stack2.isEmpty()) {\n\t\t\twhile (!stack1.isEmpty()) {\n\t\t\t\tstack2.push(stack1.pop());\n\t\t\t}\n\t\t}\n\t\treturn stack2.peek();\n\t}\n\n\tpublic boolean empty() {\n\t\treturn size == 0 ? true : false;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/myQueue/TestMyQueue.java",
    "content": "package myQueue;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 232. Implement Queue using Stacks\n */\npublic class TestMyQueue {\n\t@Test\n    public void test(){\n    \tMyQueue queue=new MyQueue();\n    \tAssert.assertTrue(queue.empty());\n    \tqueue.push(1);\n    \tqueue.push(2);\n    \tqueue.push(3);\n    \tqueue.push(4);\n    \tAssert.assertTrue(queue.pop()==1);\n    \tAssert.assertTrue(queue.pop()==2);\n    \tqueue.push(5);\n    \tAssert.assertTrue(queue.peek()==3);\n    \tAssert.assertTrue(!queue.empty());\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/myStack/MyStack.java",
    "content": "// Source : https://leetcode.com/problems/implement-stack-using-queues/description/\n// Author : Tianming Cao\n// Date   : 2018-02-02\n\n/**********************************************************************************\n * Implement the following operations of a stack using queues.\n\n * \tpush(x) -- Push element x onto stack.\n * \tpop() -- Removes the element on top of the stack.\n * \ttop() -- Get the top element.\n * \tempty() -- Return whether the stack is empty.\n * Notes:\n * \tYou must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.\n *  Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.\n *  You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).\n *\n **********************************************************************************/\npackage myStack;\n\nimport java.util.LinkedList;\nimport java.util.Queue;\n/**********************************************************************************\n * This problem is a sibling of problem 232(https://leetcode.com/problems/implement-queue-using-stacks/description/).\n * The train of thought is:\n *\tIf we want to pop a element,first we should judge which queue is not empty assumed queue1,another empty queue assumed queue2.\n *\tNext,we pop all element from queue1 and push them into queue2 util queue1's size is 1.\n *\tFinally the last element in queue1 is the correct pop value.\n *\tIf queue1 is empty and queue2 is not empty,the step is symmetric.\n *\tThe top operation is similar with pop operation.\n **********************************************************************************/\npublic class MyStack {\n\tpublic Queue<Integer> queue1;\n\tpublic Queue<Integer> queue2;\n\tpublic int flag;\n\tpublic int size;\n\t    public MyStack() {\n\t        queue1=new LinkedList<Integer>();\n\t        queue2=new LinkedList<Integer>();\n\t        flag=1;\n\t        size=0;\n\t    }\n\t    \n\t    public void push(int x) {\n\t        if(flag==1){\n\t        \tqueue1.offer(x);\n\t        }else{\n\t        \tqueue2.offer(x);\n\t        }\n\t        size++;\n\t    }\n\t    \n\t    public int pop() {\n\t    \tint value;\n\t        if(flag==1){\n\t        \twhile(queue1.size()>1){\n\t        \t\tqueue2.offer(queue1.poll());\n\t        \t}\n\t        \tvalue=queue1.poll();\n\t        \tflag=2;\n\t        }else{\n\t        \twhile(queue2.size()>1){\n\t        \t\tqueue1.offer(queue2.poll());\n\t        \t}\n\t        \tvalue=queue2.poll();\n\t        \tflag=1;\n\t        }\n\t        size--;\n\t        return value;\n\t    }\n\t    \n\t    public int top() {\n\t    \tif(flag==1){\n\t        \twhile(queue1.size()>1){\n\t        \t\tqueue2.offer(queue1.poll());\n\t        \t}\n\t        \tint value=queue1.poll();\n\t        \tqueue2.offer(value);\n\t        \tflag=2;\n\t        \treturn value;\n\t        }else{\n\t        \twhile(queue2.size()>1){\n\t        \t\tqueue1.offer(queue2.poll());\n\t        \t}\n\t        \tint value=queue2.poll();\n\t        \tqueue1.offer(value);\n\t        \tflag=1;\n\t        \treturn value;\n\t        }\n\t    }\n\t    \n\t    public boolean empty() {\n\t        return size==0?true:false;\n\t    }\n}\n"
  },
  {
    "path": "algorithms/java/src/myStack/TestMyStack.java",
    "content": "package myStack;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 225. Implement Stack using Queues\n */\npublic class TestMyStack {\n@Test\npublic void test(){\n\tMyStack stack=new MyStack();\n\tstack.push(1);\n\tstack.push(2);\n\tstack.push(3);\n\tstack.push(4);\n\tAssert.assertTrue(stack.empty()==false);\n\tAssert.assertTrue(stack.pop()==4);\n\tAssert.assertTrue(stack.pop()==3);\n\tAssert.assertTrue(stack.top()==2);\n\tstack.push(5);\n\tAssert.assertTrue(stack.top()==5);\n}\n}\n"
  },
  {
    "path": "algorithms/java/src/palindromeNumber/PalindromeNumber.java",
    "content": "// Source : https://oj.leetcode.com/problems/palindrome-number/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Determine whether an integer is a palindrome. Do this without extra space.\n * \n * Some hints:\n * Could negative integers be palindromes? (ie, -1)\n * \n * If you are thinking of converting the integer to string, note the restriction of using extra space.\n * \n * You could also try reversing an integer. \n * However, if you have solved the problem \"Reverse Integer\", you know that the reversed integer might overflow. \n * How would you handle such case?\n * \n * There is a more generic way of solving this problem.\n * \n **********************************************************************************/\npackage palindromeNumber;\n\npublic class PalindromeNumber {\n\t\n\t/**\n\t * The simple way is :\n\t * Reverse x to reverseX and judge whether reverseX is equal to x\n\t * For example:\n\t * x is 1234321, then reverseX is 1234321, they are equal, so 1234321 is palindrome\n\t * x is 1234123, then reverseX is 3214321, they are not equal, so 1234123 is not palindrome\n\t */\n\tpublic boolean isPalindrome(int x) {\n\t\tif (x < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (x < 10) {\n\t\t\treturn true;\n\t\t}\n\t\tint n = x;\n\t\tint reverseX = 0;\n\t\twhile (n > 0) {\n\t\t\treverseX = 10 * reverseX + n % 10;\n\t\t\tn /= 10;\n\t\t}\n\t\tif (reverseX == x) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/palindromeNumber/TestPalindromeNumber.java",
    "content": "package palindromeNumber;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 9. Palindrome Number\n */\npublic class TestPalindromeNumber {\n\t@Test\n\tpublic void test() {\n\t\tPalindromeNumber solution = new PalindromeNumber();\n\t\tboolean flag1 = solution.isPalindrome(1234567);\n\t\tAssert.assertTrue(!flag1);\n\t\tboolean flag2 = solution.isPalindrome(1234321);\n\t\tAssert.assertTrue(flag2);\n\t\tboolean flag3 = solution.isPalindrome(12344321);\n\t\tAssert.assertTrue(flag3);\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/powXn/PowXn.java",
    "content": "// Source : https://leetcode.com/problems/powx-n/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Implement pow(x, n).\n * \n * Example 1:\n * \n *  Input: 2.00000, 10\n *  Output: 1024.00000\n *  \n * Example 2:\n * \n *  Input: 2.10000, 3\n *  Output: 9.26100\n * \n **********************************************************************************/\npackage powXn;\n\npublic class PowXn {\n\t\n\t/**\n\t * Divide-and-Conquer method\n\t * For example:\n\t * \n\t * 3^9=(3^4)^2*3 \n\t *     ↓                          \n\t * 3^4=(3^2)^2\n\t *     ↓\n\t * 3^2=3*3\n\t *     ↓\n\t * 3=3\n\t * \n\t * So, both Space and Time are O(logN)\n\t */\n\tpublic double recursion(double x, long n) {\n\t\tif (n == 1) {\n\t\t\treturn x;\n\t\t}\n\t\t//We'd better use unsigned right shift\n\t\tdouble half = recursion(x, n >>> 1);\n\t\tif ((n & 1) == 0) {\n\t\t\treturn half * half;\n\t\t} else {\n\t\t\treturn half * half * x;\n\t\t}\n\t}\n\t\n\tpublic double myPow01(double x, int n) {\n\t\tif (n == 0 || x == 1) {\n\t\t\treturn 1;\n\t\t}\n\t\t// Avoid being out of bounds, we should cast int to long\n\t\tlong m = n;\n\t\tdouble result = recursion(x, Math.abs(m));\n\t\tif (n > 0) {\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn 1 / result;\n\t\t}\n\t}\n\t\n\tpublic double myPow02(double x, int n) {\n\t\tif (n == 0 || x == 1) {\n\t\t\treturn 1;\n\t\t}\n\t\t// Avoid being out of bounds, we should cast int to long\n\t\tlong m = n;\n\t\tdouble result = bitFunction(x, Math.abs(m));\n\t\tif (n > 0) {\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn 1 / result;\n\t\t}\n\t}\n\t\n\t/**\n\t * Solution with bit-manipulation\n\t * For example:\n\t * 9=1001\n\t * 3^9=(3^1)^1*(3^2)^0*(3^4)^0*(3^8)^1\n\t * Space is O(1), Time is O(logN)\n\t */\n\tpublic double bitFunction(double x, long n) {\n\t\tdouble multy = 1;\n\t\tdouble base = x;\n\t\tfor (long k = n; k >= 1; k >>>= 1) {\n\t\t\tif ((k & 1) > 0) {\n\t\t\t\tmulty = multy * base;\n\t\t\t}\n\t\t\tbase *= base;\n\t\t}\n\t\treturn multy;\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/java/src/powXn/TestPowXn.java",
    "content": "package powXn;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 50. Pow(x, n)\n */\npublic class TestPowXn {\n\t@Test\n\tpublic void test() {\n\t\tPowXn solution = new PowXn();\n\t\tAssert.assertTrue(solution.myPow01(3, 9) == 19683);\n\t\tAssert.assertTrue(solution.myPow02(3, 9) == 19683);\n\t\tAssert.assertTrue(solution.myPow01(2.10000, -3)-0.10798<0.0001);\n\t\tAssert.assertTrue(solution.myPow02(2.10000, -3)-0.10798<0.0001);\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/removeDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArray.java",
    "content": "// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/\n// Author : Tianming Cao\n// Date   : 2018-02-02\n\n/**********************************************************************************\n * Implement the following operations of a stack using queues.\n\n * Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.\n\n * Do not allocate extra space for another array, \n * you must do this by modifying the input array in-place with O(1) extra memory.\n\n * Example:\n\n * \tGiven nums = [1,1,2],\n\n * \tYour function should return length = 2, with the first two elements of nums being 1 and 2 respectively.\n * \tIt doesn't matter what you leave beyond the new length.\n * \n **********************************************************************************/\npackage removeDuplicatesFromSortedArray;\n\npublic class RemoveDuplicatesFromSortedArray {\n\tpublic int removeDuplicates(int[] nums) {\n\t\tif (nums == null || nums.length == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint n = nums.length;\n\t\tint len = 0;\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tif (nums[i] != nums[len]) {\n\t\t\t\tnums[len + 1] = nums[i];\n\t\t\t\tlen++;\n\t\t\t}\n\t\t}\n\t\treturn len + 1;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/removeDuplicatesFromSortedArray/TestRemoveDuplicates.java",
    "content": "package removeDuplicatesFromSortedArray;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 26. Remove Duplicates from Sorted Array\n */\npublic class TestRemoveDuplicates {\n\t@Test\n\tpublic void test() {\n\t\tint[] nums1 = {0, 0, 0, 0, 0, 1, 2, 2, 3, 3, 4, 4};\n\t\tRemoveDuplicatesFromSortedArray solution = new RemoveDuplicatesFromSortedArray();\n\t\tint len1 = solution.removeDuplicates(nums1);\n\t\tAssert.assertTrue(len1 == 5);\n\t\tassertSorted(nums1, len1);\n\t\tint[] nums2 = {1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8};\n\t\tint len2 = solution.removeDuplicates(nums2);\n\t\tAssert.assertTrue(len2 == 8);\n\t\tassertSorted(nums2, len2);\n\t}\n\tprivate void assertSorted(int[] array, int len) {\n\t\tfor (int i = 0; i < len - 1; i++) {\n\t\t\tAssert.assertTrue(array[i] < array[i + 1]);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedList/ListNode.java",
    "content": "package reverseLinkedList;\n\npublic class ListNode {\n\tpublic int val;\n\tpublic ListNode next;\n\tpublic ListNode(int x) {\n\t\tval = x;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ListNode [val=\" + val + \"]\";\n\t}\n\tpublic ListNode(int val, ListNode next) {\n\t\tsuper();\n\t\tthis.val = val;\n\t\tthis.next = next;\n\t}\n\t/**\n\t * This is an assistant function, use it, we can easily see the structure of list\n\t */\n\tpublic static String listToString(ListNode head) {\n\t\tif (head == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\twhile (head.next != null) {\n\t\t\tsb.append(head.val).append(\",\");\n\t\t\thead = head.next;\n\t\t}\n\t\tsb.append(head.val);\n\t\treturn sb.toString();\n\t}\n\t\n\t/**\n\t * This is an assistant function, use it, we can create a linkedList by array.\n\t */\n\tpublic static ListNode arrayToList(int[] array) {\n\t\tListNode head = new ListNode(0);\n\t\tListNode p = head;\n\t\tfor (int i : array) {\n\t\t\tp.next = new ListNode(i);\n\t\t\tp = p.next;\n\t\t}\n\t\treturn head.next;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedList/ReverseLinkedList.java",
    "content": "// Source : https://leetcode.com/problems/reverse-linked-list/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Reverse a singly linked list.\n * \n * Hint:\n * A linked list can be reversed either iteratively or recursively. Could you implement both?\n * \n **********************************************************************************/\npackage reverseLinkedList;\n\npublic class ReverseLinkedList {\n\n\t/**\n\t * The iterative solution\n\t */\n\tpublic ListNode reverseList(ListNode head) {\n\t\tif (head == null) {\n\t\t\treturn head;\n\t\t}\n\t\tListNode p = head;\n\t\tListNode next = p.next;\n\t\twhile (next != null) {\n\t\t\tListNode temp = next.next;\n\t\t\tnext.next = p;\n\t\t\tp = next;\n\t\t\tnext = temp;\n\t\t}\n\t\thead.next = null;\n\t\treturn p;\n\t}\n\t\n\tpublic ListNode reverseListRecursion(ListNode head) {\n\t\tif (head == null) {\n\t\t\treturn head;\n\t\t}\n\t\tListNode newHead = recursion(head);\n\t\thead.next = null;\n\t\treturn newHead;\n\t}\n\t/**\n\t * The recursive solution\n\t */\n\tpublic ListNode recursion(ListNode p) {\n\t\tif (p.next == null) {\n\t\t\treturn p;\n\t\t} else {\n\t\t\tListNode next = p.next;\n\t\t\tListNode newHead = recursion(next);\n\t\t\tnext.next = p;\n\t\t\treturn newHead;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedList/TestReverseLinkedList.java",
    "content": "package reverseLinkedList;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 206. Reverse Linked List\n */\npublic class TestReverseLinkedList {\n\t@Test\n\tpublic void test(){\n\t\tReverseLinkedList solution=new ReverseLinkedList();\n\t\tint[] array1={1,2,3,4,5,6};\n\t\tListNode head1=ListNode.arrayToList(array1);\n\t\tListNode newHead1=solution.reverseList(head1);\n\t\tAssert.assertTrue(ListNode.listToString(newHead1).equals(\"6,5,4,3,2,1\"));\n\t\tint[] array2={6,5,4,3,2,1};\n\t\tListNode head2=ListNode.arrayToList(array2);\n\t\tListNode newHead2=solution.reverseListRecursion(head2);\n\t\tAssert.assertTrue(ListNode.listToString(newHead2).equals(\"1,2,3,4,5,6\"));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedListII/ListNode.java",
    "content": "package reverseLinkedListII;\n\npublic class ListNode {\n\tpublic int val;\n\tpublic ListNode next;\n\tpublic ListNode(int x) {\n\t\tval = x;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ListNode [val=\" + val + \"]\";\n\t}\n\tpublic ListNode(int val, ListNode next) {\n\t\tsuper();\n\t\tthis.val = val;\n\t\tthis.next = next;\n\t}\n\t/**\n\t * This is an assistant function, use it, we can easily see the structure of list\n\t */\n\tpublic static String listToString(ListNode head) {\n\t\tif (head == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\twhile (head.next != null) {\n\t\t\tsb.append(head.val).append(\",\");\n\t\t\thead = head.next;\n\t\t}\n\t\tsb.append(head.val);\n\t\treturn sb.toString();\n\t}\n\t\n\t/**\n\t * This is an assistant function, use it, we can create a linkedList by array.\n\t */\n\tpublic static ListNode arrayToList(int[] array) {\n\t\tListNode head = new ListNode(0);\n\t\tListNode p = head;\n\t\tfor (int i : array) {\n\t\t\tp.next = new ListNode(i);\n\t\t\tp = p.next;\n\t\t}\n\t\treturn head.next;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedListII/ReverseLinkedListII.java",
    "content": "// Source : https://leetcode.com/problems/reverse-linked-list-ii/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Reverse a linked list from position m to n. Do it in-place and in one-pass.\n * \n * For example:\n * Given 1->2->3->4->5->NULL, m = 2 and n = 4,\n * \n * return 1->4->3->2->5->NULL.\n * \n * Note:\n * Given m, n satisfy the following condition:\n * 1 ≤ m ≤ n ≤ length of list.\n * \n **********************************************************************************/\npackage reverseLinkedListII;\n\npublic class ReverseLinkedListII {\n\tpublic ListNode reverseBetween(ListNode head, int m, int n) {\n\t\t// Assume that the list is:[1,2,3,4,5,6,7] m=3 n=5\n\t\tif (head == null || m == n) {\n\t\t\t// bounds check\n\t\t\treturn head;\n\t\t}\n\t\t// We'd better create a default head due to m may equals 1\n\t\tListNode defaultHead = new ListNode(0);\n\t\tdefaultHead.next = head;\n\t\tint index = 1;\n\t\tListNode pre = defaultHead;\n\t\twhile (index < m) {\n\t\t\tpre = pre.next;\n\t\t\tindex++;\n\t\t}\n\t\t// pre is 2, first is 3\n\t\tListNode first = pre.next;\n\t\tListNode p = first;\n\t\tListNode next = p.next;\n\t\twhile (index < n) {\n\t\t\tListNode t = next.next;\n\t\t\tnext.next = p;\n\t\t\tp = next;\n\t\t\tnext = t;\n\t\t\tindex++;\n\t\t}\n\t\t// next is 6\n\t\tfirst.next = next;\n\t\tpre.next = p;\n\t\treturn defaultHead.next;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseLinkedListII/TestReverseLinkedListII.java",
    "content": "package reverseLinkedListII;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 92. Reverse Linked List II\n */\npublic class TestReverseLinkedListII {\n\t@Test\n\tpublic void test() {\n\t\tReverseLinkedListII solution = new ReverseLinkedListII();\n\t\tint[] array1 = {1, 2, 3, 4, 5, 6, 7};\n\t\tListNode head1 = ListNode.arrayToList(array1);\n\t\tListNode newHead1 = solution.reverseBetween(head1, 3, 5);\n\t\tAssert.assertTrue(ListNode.listToString(newHead1).equals(\n\t\t\t\t\"1,2,5,4,3,6,7\"));\n\t\tint[] array2 = {7, 6, 5, 4, 3, 2, 1};\n\t\tListNode head2 = ListNode.arrayToList(array2);\n\t\tListNode newHead2 = solution.reverseBetween(head2, 1, 7);\n\t\tAssert.assertTrue(ListNode.listToString(newHead2).equals(\n\t\t\t\t\"1,2,3,4,5,6,7\"));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseWordsInAString/ReverseWordsInAString.java",
    "content": "// Source : https://leetcode.com/problems/reverse-words-in-a-string/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Given an input string, reverse the string word by word.\n * \n * For example,\n * Given s = \"the sky is blue\",\n * return \"blue is sky the\".\n * \n * Update (2015-02-12):\n * For C programmers: Try to solve it in-place in O(1) space.\n * \n **********************************************************************************/\npackage reverseWordsInAString;\n\npublic class ReverseWordsInAString {\n\n\tpublic String reverseWords(String s) {\n\t\tif (s == null || s.length() == 0) {\n\t\t\treturn s;\n\t\t}\n\t\ts = s.trim();\n\t\tString[] array = s.split(\"\\\\s+\");\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint len = array.length;\n\t\tfor (int i = len - 1; i > 0; i--) {\n\t\t\tsb.append(array[i]).append(\" \");\n\t\t}\n\t\tsb.append(array[0]);\n\t\treturn sb.toString();\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/reverseWordsInAString/TestReverseWordsInAString.java",
    "content": "package reverseWordsInAString;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 151. Reverse Words in a String\n */\npublic class TestReverseWordsInAString {\n\t@Test\n\tpublic void test() {\n\t\tReverseWordsInAString solution = new ReverseWordsInAString();\n\t\tString str = \" the    sky is   blue   \";\n\t\tString result = solution.reverseWords(str);\n\t\tAssert.assertTrue(result.equals(\"blue is sky the\"));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/rotateArray/RotateArray.java",
    "content": "// Source : https://leetcode.com/problems/rotate-array/description/\n// Author : Tianming Cao\n// Date   : 2018-02-02\n\n/**********************************************************************************\n * Rotate an array of n elements to the right by k steps.\n * \n * For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].\n * \n * Note:\n * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.\n * \n * Hint:\n * Could you do it in-place with O(1) extra space?\n * Related problem: Reverse Words in a String II\n * \n **********************************************************************************/\npackage rotateArray;\n/**********************************************************************************\n *\n * For example, with n = 9 and k = 4, the array is [1,2,3,4,5,6,7,8,9]\n * The train of thought is:\n *  1. Reverse 1-5 to [5,4,3,2,1]\n *  2. Reverse 6-9 to [9,8,7,6]\n *  3. Reverse the entire array [5,4,3,2,1,9,8,7,6] to [6,7,8,9,1,2,3,4,5]\n * It's a liner time and in-place algorithm\n * \n **********************************************************************************/\npublic class RotateArray {\n\n\tpublic void rotate(int[] nums, int k) {\n\t\t//bounds check\n\t\tif (nums == null || nums.length == 0 || k == 0) {\n\t\t\treturn;\n\t\t}\n\t\tint n = nums.length;\n\t\t//k may be larger than n\n\t\tk = k % n;\n\t\trotateRange(0, n - k - 1, nums);\n\t\trotateRange(n - k, n - 1, nums);\n\t\trotateRange(0, n - 1, nums);\n\t}\n\t\n\tprivate void rotateRange(int start, int end, int[] array) {\n\t\tfor (int i = start, j = end; i < j; i++, j--) {\n\t\t\tswap(array, i, j);\n\t\t}\n\t}\n\tprivate void swap(int[] array, int i, int j) {\n\t\tint t = array[i];\n\t\tarray[i] = array[j];\n\t\tarray[j] = t;\n\t}\n\t\n}\n"
  },
  {
    "path": "algorithms/java/src/rotateArray/TestRotateArray.java",
    "content": "package rotateArray;\n\nimport java.util.Arrays;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 189. Rotate Array\n *\n */\npublic class TestRotateArray {\n\t@Test\n\tpublic void test() {\n\t\tRotateArray solution = new RotateArray();\n\t\tint[] array1 = {1, 2, 3, 4, 5, 6, 7};\n\t\tint k1 = 24;\n\t\tsolution.rotate(array1, k1);\n\t\tint[] expectArray1 = {5, 6, 7, 1, 2, 3, 4};\n\t\tAssert.assertTrue(Arrays.equals(array1, expectArray1));\n\t\tint[] array2 = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n\t\tint k2 = 4;\n\t\tsolution.rotate(array2, k2);\n\t\tint[] expectArray2 = {6, 7, 8, 9, 1, 2, 3, 4, 5};\n\t\tAssert.assertTrue(Arrays.equals(array2, expectArray2));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/search2DMatrix/search2DMatrix.java",
    "content": "// Source : https://oj.leetcode.com/problems/search-a-2d-matrix/\n// Inspired by : http://www.jiuzhang.com/solutions/search-a-2d-matrix/\n// Author : Lei Cao\n// Date   : 2015-10-03\n\n/**********************************************************************************\n *\n * Write an efficient algorithm that searches for a value in an m x n matrix.\n * This matrix has the following properties:\n *\n * Integers in each row are sorted from left to right.\n * The first integer of each row is greater than the last integer of the previous row.\n *\n * For example,\n *\n * Consider the following matrix:\n *\n * [\n *   [1,   3,  5,  7],\n *   [10, 11, 16, 20],\n *   [23, 30, 34, 50]\n * ]\n *\n * Given target = 3, return true.\n *\n **********************************************************************************/\n\npackage search2DMatrix;\n\npublic class search2DMatrix {\n    int rows = 0;\n    int cols = 0;\n    int[][] m;\n    public boolean searchMatrix(int[][] matrix, int target) {\n        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {\n            return false;\n        }\n\n        m = matrix;\n        rows = matrix.length;\n        cols = matrix[0].length;\n\n        int start = 0;\n        int end = rows * cols - 1;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (getValue(mid) == target) {\n                return true;\n            } else if (getValue(mid) < target) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (getValue(start) == target) {\n            return true;\n        }\n        if (getValue(end) == target) {\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Get the value of the 2D matrix from the index\n     * @param index\n     * @return\n     */\n    private int getValue(int index) {\n        return m[index / cols][index % cols];\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/search2DMatrix/search2DMatrixTest.java",
    "content": "package search2DMatrix;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 3/10/15.\n */\npublic class search2DMatrixTest {\n\n    @Test\n    public void testSearchMatrix() throws Exception {\n        int[][][] inputes = {\n                {\n                        {1,3,5,7},\n                        {10,11,16,20},\n                        {23,30,34,50},\n                },\n        };\n        int[] targets =  {3};\n        boolean[] outputs = {true};\n\n        search2DMatrix s = new search2DMatrix();\n        for (int i = 0; i < targets.length; i++) {\n            boolean r = s.searchMatrix(inputes[i], targets[i]);\n            System.out.println(r);\n            assertEquals(outputs[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/searchA2DMatrixII/SearchA2DMatrixII.java",
    "content": "﻿// Source : https://leetcode.com/problems/search-a-2d-matrix-ii/description/\n// Author : Tianming Cao\n// Date   : 2018-01-27\n/**********************************************************************************\n * Write an efficient algorithm that searches for a value in an m x n matrix. \n * This matrix has the following properties:\n * \n * Integers in each row are sorted in ascending from left to right.\n * Integers in each column are sorted in ascending from top to bottom.\n * For example,\n * \n * Consider the following matrix:\n * \n * [\n *   [1,   4,  7, 11, 15],\n *   [2,   5,  8, 12, 19],\n *   [3,   6,  9, 16, 22],\n *   [10, 13, 14, 17, 24],\n *   [18, 21, 23, 26, 30]\n * ]\n * Given target = 5, return true.\n * \n * Given target = 20, return false.\n *\n **********************************************************************************/\npackage searchA2DMatrixII;\n/**********************************************************************************\n * This probleam is similar to problem 74(https://leetcode.com/problems/search-a-2d-matrix/description/).\n * One solution is:\n * Compare rightTopNumber with target to judge rowIndex and colIndex which place to move,\n * until thay out of range or find target.\n * Another solution is using binarySearch.\n **********************************************************************************/\npublic class SearchA2DMatrixII {\n\tpublic boolean searchMatrix(int[][] matrix, int target) {\n\t\tif (matrix == null || matrix.length == 0 || matrix[0].length == 0) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tint m=matrix.length;\n\t\t\tint n=matrix[0].length;\n\t\t\tint row=0;\n\t\t\tint col=n-1;\n\t\t\twhile(row<m&&col>=0){\n\t\t\t\tint rightTopNumber=matrix[row][col];\n\t\t\t\tif(rightTopNumber==target){\n\t\t\t\t\treturn true;\n\t\t\t\t}else if(target>rightTopNumber){\n\t\t\t\t\trow++;\n\t\t\t\t}else{\n\t\t\t\t\tcol--;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/java/src/searchA2DMatrixII/Test_240.java",
    "content": "package searchA2DMatrixII;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 240. Search a 2D Matrix II\n */\npublic class Test_240 {\n\t@Test\n\tpublic void test() {\n\t\tSearchA2DMatrixII solution = new SearchA2DMatrixII();\n\t\tint[][] matrix = {{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19},\n\t\t\t\t{3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}};\n\t\tint target = 5;\n\t\tAssert.assertTrue(solution.searchMatrix(matrix, target));\n\t\ttarget = 20;\n\t\tAssert.assertTrue(!solution.searchMatrix(matrix, target));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/searchForRange/searchForRange.java",
    "content": "// Source : https://oj.leetcode.com/problems/search-for-a-range/\n// Inspired by : http://www.jiuzhang.com/solutions/search-for-a-range/\n// Author : Lei Cao\n// Date   : 2015-10-03\n\n/**********************************************************************************\n *\n * Given a sorted array of integers, find the starting and ending position of a given target value.\n *\n * Your algorithm's runtime complexity must be in the order of O(log n).\n *\n * If the target is not found in the array, return [-1, -1].\n *\n * For example,\n * Given [5, 7, 7, 8, 8, 10] and target value 8,\n * return [3, 4].\n *\n *\n **********************************************************************************/\n\npackage searchForRange;\n\npublic class searchForRange {\n    public int[] searchRange(int[] nums, int target) {\n        int[] result = {-1, -1};\n        if (nums == null) {\n            return result;\n        }\n\n        int start = 0;\n        int end = nums.length - 1;\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid] >= target) {\n                end = mid;\n            } else if (nums[mid] < target) {\n                start = mid;\n            }\n        }\n\n        if (nums[start] == target) {\n            result[0] = start;\n        } else if (nums[end] == target) {\n            result[0] = end;\n        }\n\n        start = 0;\n        end = nums.length - 1;\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid] <= target) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n        if (nums[end] == target) {\n            result[1] = end;\n        } else if (nums[start] == target) {\n            result[1] = start;\n        }\n        return result;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/searchForRange/searchForRangeTest.java",
    "content": "package searchForRange;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 3/10/15.\n */\npublic class searchForRangeTest {\n\n    @Test\n    public void testSearchRange() throws Exception {\n\n        int[][] inputs = {\n            {5, 7, 7, 8, 8, 10}\n        };\n        int[] targets = {8};\n        int[][] results = {\n            {3,4}\n        };\n\n        searchForRange s = new searchForRange();\n        for (int i = 0; i < inputs.length; i++) {\n            int[] r = s.searchRange(inputs[i], targets[i]);\n            System.out.println(r);\n            assertArrayEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/searchInABigSortedArray/searchInABigSortedArray.java",
    "content": "// Source : http://www.lintcode.com/en/problem/search-in-a-big-sorted-array/\n// Inspired by : http://www.jiuzhang.com/solutions/search-in-a-big-sorted-array/\n// Author : Lei Cao\n// Date   : 2015-10-05\n\n/**********************************************************************************\n *\n * Given a big sorted array, find the first index of a target number. Your algorithm should be in O(log k), where k is the first index of the target number.\n *\n * Return -1, if the number doesn't exist in the array.\n *\n * Example\n * Given [1, 3, 6, 9, 21], and target = 3, return 1.\n *\n * Challenge\n * O(log k), k is the first index of the given target number.\n *\n **********************************************************************************/\n\npackage searchInABigSortedArray;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class searchInABigSortedArray {\n    public int searchBigSortedArray(int[] A, int target) {\n        if (A == null || A.length == 0) {\n            return -1;\n        }\n\n        int start = 0;\n        int end = A.length - 1;\n        int upperBound = 1;\n\n        // @TODO The logic here needs to be reviewed.\n        for (int i = 0; i < Math.sqrt(A.length) + 1; i++) {\n            if (upperBound < 0) {\n                end = A.length - 1;\n                break;\n            }\n            if (A.length > upperBound && A[upperBound] > target) {\n                end = upperBound - 1;\n                break;\n            }\n            upperBound = upperBound * 2;\n        }\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (A[mid] == target) {\n                end = mid;\n            } else if (A[mid] < target) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (A[start] == target) {\n            return start;\n        }\n        if (A[end] == target) {\n            return end;\n        }\n\n        return -1;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/searchInABigSortedArray/searchInABigSortedArrayTest.java",
    "content": "package searchInABigSortedArray;\n\nimport org.junit.Test;\nimport searchInsertPosition.searchInsertPosition;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class searchInABigSortedArrayTest {\n\n    @Test\n    public void testSearchBigSortedArray() throws Exception {\n        int [][] inputs = {\n                {1,2,3,4},\n                {1,1,1,1,2,2,3,3,3,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,\n                10,10,10,10,10,11,11,11,11,12,12,12,13,13,13,13,13,14,14,14,14,14,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,17,17,\n                17,17,17,17,17,18,18,19,19,19,19,20,20,20,20,20,20,20,20,20},\n        };\n        int[] targets = {3, 4};\n        int[] results = {2, 9};\n        searchInABigSortedArray s = new searchInABigSortedArray();\n        for (int i = 0; i < inputs.length; i++) {\n            int r = s.searchBigSortedArray(inputs[i], targets[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n\n\n    }\n}"
  },
  {
    "path": "algorithms/java/src/searchInRotatedSortedArray/searchInRotatedSortedArray.java",
    "content": "// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array/\n// Inspired by : http://www.jiuzhang.com/solutions/search-in-rotated-sorted-array/\n// Author : Lei Cao\n// Date   : 2015-10-03\n\n/**********************************************************************************\n *\n * Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n *\n * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n *\n * You are given a target value to search. If found in the array return its index, otherwise return -1.\n *\n * You may assume no duplicate exists in the array.\n *\n **********************************************************************************/\n\npackage searchInRotatedSortedArray;\n\npublic class searchInRotatedSortedArray {\n    /**\n     * start [....1....] rotated pivot [....2...] end\n     * @param nums\n     * @param target\n     * @return\n     */\n    public int search(int[] nums, int target) {\n        if (nums == null || nums.length == 0) {\n            return -1;\n        }\n\n        int start = 0;\n        int end = nums.length - 1;\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid] == target) {\n                return mid;\n            }\n\n            if (nums[start] <= nums[mid]) { // in higher part\n                if (nums[start] <= target && target <= nums[mid]) { // target within the start and mid.\n                    end = mid;\n                } else {\n                    start = mid;\n                }\n            } else {\n                if (nums[mid] <= target && target <= nums[nums.length -1]) { // target within the mid and the end\n                    start = mid;\n                } else {\n                    end = mid;\n                }\n            }\n        }\n\n        if (nums[start] == target) {\n            return start;\n        }\n        if (nums[end] == target) {\n            return end;\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/searchInRotatedSortedArray/searchInRotatedSortedArrayTest.java",
    "content": "package searchInRotatedSortedArray;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 3/10/15.\n */\npublic class searchInRotatedSortedArrayTest {\n\n    @Test\n    public void testSearch() throws Exception {\n\n        int[][] inputes = {\n            {1},\n            {1},\n            {6,8,9,1,3,5},\n            {1,2},\n            {2,1},\n            {4,5,6,7,0,1,2},\n            {0,1,2,4,5,6,7},\n        };\n        int[] targets = {0,1,5,2,2,6,6};\n        int[] results = {-1,0,5,1,0,2,5};\n\n        searchInRotatedSortedArray s = new searchInRotatedSortedArray();\n        for (int i = 0; i < inputes.length; i++) {\n            int r = s.search(inputes[i], targets[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/searchInsertPosition/searchInsertPosition.java",
    "content": "// Source : https://oj.leetcode.com/problems/search-insert-position/\n// Inspired by : http://www.jiuzhang.com/solutions/search-insert-position/\n// Author : Lei Cao\n// Date   : 2015-10-03\n\n/**********************************************************************************\n *\n * Given a sorted array and a target value, return the index if the target is found.\n * If not, return the index where it would be if it were inserted in order.\n *\n * You may assume no duplicates in the array.\n *\n * Here are few examples.\n * [1,3,5,6], 5 → 2\n * [1,3,5,6], 2 → 1\n * [1,3,5,6], 7 → 4\n * [1,3,5,6], 0 → 0\n *\n *\n **********************************************************************************/\n\npackage searchInsertPosition;\n\npublic class searchInsertPosition {\n    public int searchInsert(int[] nums, int target) {\n        int i = searchInsertI(nums, target);\n        int j = searchInsertII(nums, target);\n        if (i == j) {\n            return i;\n        }\n        return -1;\n    }\n\n    // Find the first position >= target\n    private int searchInsertI(int[] nums, int target) {\n         if (nums == null || nums.length == 0) {\n            return 0;\n        }\n\n        int start = 0;\n        int end = nums.length - 1;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid] == target) {\n                return mid;\n            } else if (nums[mid] < target) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (nums[start] >= target) {\n            return start;\n        }\n        if (nums[end] >= target) {\n            return end;\n        }\n        return end + 1;\n    }\n\n    // Find the last position < target, return + 1\n    // 1,2,3,5,6\n    private int searchInsertII(int[] nums, int target) {\n        if (nums == null || nums.length == 0) {\n            return 0;\n        }\n        if (target < nums[0]) {\n            return 0;\n        }\n\n        int start = 0;\n        int end = nums.length - 1;\n\n        while (start + 1 < end) {\n            int mid = start + (end - start) / 2;\n            if (nums[mid] == target) {\n                return mid;\n            } else if (nums[mid] < target) {\n                start = mid;\n            } else {\n                end = mid;\n            }\n        }\n\n        if (nums[end] == target) {\n            return end;\n        } else if (nums[end] < target) {\n            return end + 1;\n        } else if (nums[start] == target) {\n            return start;\n        }\n        return start + 1;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/searchInsertPosition/searchInsertPositionTest.java",
    "content": "package searchInsertPosition;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 3/10/15.\n */\npublic class searchInsertPositionTest {\n\n    @Test\n    public void testSearchInsert() throws Exception {\n        int [][] inputs = {\n                {1,3,5,6},\n                {1,3,5,6},\n                {1,3,5,6},\n                {1,3,5,6},\n        };\n        int[] targets = {5,2,7,0};\n        int[] results = {2,1,4,0};\n        searchInsertPosition s = new searchInsertPosition();\n        for (int i = 0; i < inputs.length; i++) {\n            int r = s.searchInsert(inputs[i], targets[i]);\n            System.out.println(r);\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/searchRangeInBinarySearchTree/TreeNode.java",
    "content": "package searchRangeInBinarySearchTree;\n\n/**\n * Created by leicao on 5/10/15.\n */\npublic class TreeNode {\n     int val;\n     TreeNode left;\n     TreeNode right;\n     TreeNode(int x) { val = x; }\n}\n"
  },
  {
    "path": "algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTree.java",
    "content": "// Source : http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/search-range-in-binary-search-tree/\n// Author : Lei Cao\n// Date   : 2015-10-09\n\n/**********************************************************************************\n *\n * Search Range in Binary Search Tree\n *\n * Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree.\n * Find all the keys of tree in range k1 to k2.\n * i.e. print all x such that k1<=x<=k2 and x is a key of given BST.\n * Return all the keys in ascending order.\n *\n * Example:\n *\n * If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].\n *\n *     20\n *    / \\\n *   8  22\n *  / \\\n * 4  12\n *\n *\n **********************************************************************************/\n\npackage searchRangeInBinarySearchTree;\n\nimport java.util.ArrayList;\n\npublic class searchRangeInBinarySearchTree {\n    /**\n     * @param root: The root of the binary search tree.\n     * @param k1 and k2: range k1 to k2.\n     * @return: Return all keys that k1<=key<=k2 in ascending order.\n     */\n    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {\n        ArrayList<Integer> result = new ArrayList<Integer>();\n        if (root == null) {\n            return result;\n        }\n\n        ArrayList<Integer> left = searchRange(root.left, k1, k2);\n        ArrayList<Integer> right = searchRange(root.right, k1, k2);\n\n        result.addAll(left);\n        if (root.val >= k1 && root.val <= k2) {\n            result.add(root.val);\n        }\n        result.addAll(right);\n        return result;\n    }\n\n}\n"
  },
  {
    "path": "algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTreeTest.java",
    "content": "package searchRangeInBinarySearchTree;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 9/10/15.\n */\npublic class searchRangeInBinarySearchTreeTest {\n\n    @Test\n    public void testSearchRange() throws Exception {\n        ArrayList<TreeNode> inputs = new ArrayList<TreeNode>();\n\n        TreeNode t1 = new TreeNode(20);\n        TreeNode t2 = new TreeNode(8);\n        TreeNode t3 = new TreeNode(22);\n        TreeNode t4 = new TreeNode(4);\n        TreeNode t5 = new TreeNode(12);\n\n        t1.left = t2;\n        t1.right = t3;\n        t2.left = t4;\n        t2.right = t5;\n\n        inputs.add(t1);\n\n        int[][] ranges = {\n            {10,22}\n        };\n\n        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(12);\n                add(20);\n                add(22);\n            }});\n        }};\n\n        for (int i = 0; i < results.size(); i++) {\n            searchRangeInBinarySearchTree s = new searchRangeInBinarySearchTree();\n            ArrayList<Integer> r = s.searchRange(inputs.get(i), ranges[i][0], ranges[i][1]);\n            assertTrue(r.containsAll(results.get(i)) && r.size() == results.get(i).size());\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/strStr/StrStrKmp.java",
    "content": "// Source : https://leetcode.com/problems/implement-strstr/description/\n// Inspired by : http://wiki.jikexueyuan.com/project/kmp-algorithm/define.html\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Implement strStr().\n * \n * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n * \n * Example 1:\n * \n *  Input: haystack = \"hello\", needle = \"ll\"\n *  Output: 2\n *  \n * Example 2:\n * \n *  Input: haystack = \"aaaaa\", needle = \"bba\"\n *  Output: -1\n * \n **********************************************************************************/\npackage strStr;\n\npublic class StrStrKmp {\n\t\n\t/**\n\t * KMP-Algorithm\n\t */\n\tpublic int strStr(String haystack, String needle) {\n\t\tif (haystack == null && needle == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (haystack == null && needle != null) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (haystack != null && needle == null) {\n\t\t\treturn -1;\n\t\t}\n\t\tint m = haystack.length();\n\t\tint n = needle.length();\n\t\tif (m < n) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (n == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint[] nextArray = getNext(needle);\n\t\tint i = 0;\n\t\tint j = 0;\n\t\twhile (i < m) {\n\t\t\tif (j == -1) {\n\t\t\t\t// If pointer j is in boundary, move i to the right and reset j\n\t\t\t\ti++;\n\t\t\t\tj = 0;\n\t\t\t} else {\n\t\t\t\tif (haystack.charAt(i) == needle.charAt(j)) {\n\t\t\t\t\t// While matching succeess, move both pointer i and pointer j to the right\n\t\t\t\t\ti++;\n\t\t\t\t\tj++;\n\t\t\t\t\tif (j == n) {\n\t\t\t\t\t\treturn i - n;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t/***\n\t\t\t\t\t * For example:\n\t\t\t\t\t * \n\t\t\t\t\t * next: [-1,0,0,0,0,1,2]\n\t\t\t\t\t * \n\t\t\t\t\t *                    i\n\t\t\t\t\t *                    ↓ \n\t\t\t\t\t * haystack:BBC ABCDAB ABCDABCDABDE\n\t\t\t\t\t *                    j\n\t\t\t\t\t *                    ↓\n\t\t\t\t\t * needle:      ABCDABD\n\t\t\t\t\t * \n\t\t\t\t\t * \n\t\t\t\t\t * So the next step is:\n\t\t\t\t\t * \n\t\t\t\t\t *                    i\n\t\t\t\t\t *                    ↓ \n\t\t\t\t\t * haystack:BBC ABCDAB ABCDABCDABDE\n\t\t\t\t\t *                    j\n\t\t\t\t\t *                    ↓\n\t\t\t\t\t * needle:          ABCDABD\n\t\t\t\t\t */\n\t\t\t\t\tj = nextArray[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\t/**\n\t * Generate the next-array of needle string\n\t * \n\t * For example:\n\t * \n\t * next-array of \"ABCDABD\" is: [-1,0,0,0,0,1,2]\n\t * \n\t * For letter \"D\", the longest prefix \"AB\" is equal to the longest suffix \"AB\", \n\t * the string \"AB\"'s length is 2, so letter \"D\"'s next value is 2.\n\t */\n\tpublic int[] getNext(String str) {\n\t\tint len = str.length();\n\t\tint[] next = new int[len];\n\t\tnext[0] = -1;\n\t\tint k = -1;\n\t\tint j = 0;\n\t\twhile (j < len - 1) {\n\t\t\tif (k == -1) {\n\t\t\t\tk = 0;\n\t\t\t\tnext[j + 1] = 0;\n\t\t\t\tj++;\n\t\t\t} else {\n\t\t\t\tif (str.charAt(j) == str.charAt(k)) {\n\t\t\t\t\tnext[j + 1] = k + 1;\n\t\t\t\t\tk++;\n\t\t\t\t\tj++;\n\t\t\t\t} else {\n\t\t\t\t\tk = next[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn next;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/strStr/TestStrStrKmp.java",
    "content": "package strStr;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 28. Implement strStr() using KMP-Algorithm\n */\npublic class TestStrStrKmp {\n\t@Test\n\tpublic void testKmp() {\n\t\tStrStrKmp solution = new StrStrKmp();\n\t\tString hayStack1 = \"aabbccagdbbccdec\";\n\t\tString needle1 = \"bbccd\";\n\t\tint result1 = solution.strStr(hayStack1, needle1);\n\t\tAssert.assertTrue(result1 == 9);\n\t\tString hayStack2 = \"aabbccagdbbccdec\";\n\t\tString needle2 = \"bbccf\";\n\t\tint result2 = solution.strStr(hayStack2, needle2);\n\t\tAssert.assertTrue(result2 == -1);\n\t\tString hayStack3 = \"BBC ABCDAB ABCDABCDABDE\";\n\t\tString needle3 = \"ABCDABD\";\n\t\tint result3 = solution.strStr(hayStack3, needle3);\n\t\tAssert.assertTrue(result3 == 15);\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/strStr/strStr.java",
    "content": "// Source : https://oj.leetcode.com/problems/implement-strstr/\n// Inspired by : http://www.jiuzhang.com/solutions/implement-strstr/\n// Author : Lei Cao\n// Date   : 2015-10-02\n\n/**********************************************************************************\n *\n * Implement strStr().\n *\n * Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.\n *\n *\n **********************************************************************************/\n\npackage strStr;\n\n/**\n * Created by leicao on 2/10/15.\n */\npublic class strStr {\n    public int strStr(String haystack, String needle) {\n        if (haystack == null || needle == null) {\n            return -1;\n        }\n        int i, j = 0;\n        for (i = 0; i < haystack.length() - needle.length() + 1; i++) {\n            for (j = 0; j < needle.length(); j++) {\n                if (haystack.charAt(i + j) != needle.charAt(j)) {\n                    break;\n                }\n            }\n            if (j == needle.length()) {\n                return i;\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/strStr/strStrTest.java",
    "content": "package strStr;\n\nimport com.sun.org.apache.xpath.internal.operations.Equals;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 2/10/15.\n */\npublic class strStrTest {\n\n    @org.junit.Test\n    public void testStrStr() throws Exception {\n        strStr strStr = new strStr();\n        String[][]  inputs = {\n            {\"I am the haystack!\",\"haystack!\"},\n            {\"I am the haystack!\",\"haytack\"},\n        };\n        int[] outputs = {9, -1};\n        for (int i = 0; i < inputs.length; i++) {\n            assertEquals(outputs[i], strStr.strStr(inputs[i][0], inputs[i][1]));\n        }\n    }\n}"
  },
  {
    "path": "algorithms/java/src/subsets/subsets.java",
    "content": "// Source : https://oj.leetcode.com/problems/subsets/\n// Inspired by : http://www.jiuzhang.com/solutions/subsets/\n// Author : Lei Cao\n// Date   : 2015-10-02\n\n/**********************************************************************************\n *\n * Given a set of distinct integers, S, return all possible subsets.\n *\n * Note:\n *\n * Elements in a subset must be in non-descending order.\n * The solution set must not contain duplicate subsets.\n *\n * For example,\n * If S = [1,2,3], a solution is:\n *\n * [\n *   [3],\n *   [1],\n *   [2],\n *   [1,2,3],\n *   [1,3],\n *   [2,3],\n *   [1,2],\n *   []\n * ]\n *\n *\n **********************************************************************************/\n\npackage subsets;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class subsets {\n    /**\n     * Leetcode version\n     * @param nums\n     * @return\n     */\n    public List<List<Integer>> subsets(int [] nums) {\n        List<List<Integer>> result = new ArrayList<List<Integer>>();\n        if (nums == null || nums.length == 0) {\n            return result;\n        }\n        ArrayList<Integer> list = new ArrayList<Integer>();\n        Arrays.sort(nums);\n        addSubset(result, list, nums, 0);\n        return result;\n    }\n\n    private void addSubset(List<List<Integer>> result, ArrayList<Integer> list, int[] nums, int pos) {\n        result.add(new ArrayList<Integer>(list));\n        for (int i = pos; i < nums.length; i++) {\n            list.add(nums[i]);\n            addSubset(result, list, nums, i + 1);\n            list.remove(list.size()-1);\n        }\n    }\n\n    /**\n     * Lintcode version\n     * @param S: A set of numbers.\n     * @return: A list of lists. All valid subsets.\n     */\n    public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> s) {\n        // write your code here\n        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();\n        if (s == null || s.size() == 0) {\n            return result;\n        }\n        ArrayList<Integer> list = new ArrayList<Integer>();\n        Collections.sort(s);\n        addSubset(s, result, list, 0);\n        return result;\n    }\n\n    private void addSubset(\n            ArrayList<Integer> s,\n            ArrayList<ArrayList<Integer>> result,\n            ArrayList<Integer> list,\n            int pos) {\n        result.add(new ArrayList<Integer>(list));\n        for (int i = pos; i < s.size(); i++) {\n            list.add(s.get(i));\n            addSubset(s, result, list, i + 1);\n            list.remove(list.size() - 1);\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/subsets/subsetsII.java",
    "content": "// Source : https://oj.leetcode.com/problems/subsets-ii/\n// Inspired by : http://www.jiuzhang.com/solutions/subsets-ii/\n// Author : Lei Cao\n// Date   : 2015-10-02\n\n/**********************************************************************************\n *\n * Given a collection of integers that might contain duplicates, S, return all possible subsets.\n *\n * Note:\n *\n * Elements in a subset must be in non-descending order.\n * The solution set must not contain duplicate subsets.\n *\n * For example,\n * If S = [1,2,2], a solution is:\n *\n * [\n *   [2],\n *   [1],\n *   [1,2,2],\n *   [2,2],\n *   [1,2],\n *   []\n * ]\n *\n *\n **********************************************************************************/\n\npackage subsets;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class subsetsII {\n    /**\n     * Leetcode version\n     * @param nums\n     * @return\n     */\n    public List<List<Integer>> subsetsWithDup(int [] nums) {\n        List<List<Integer>> result = new ArrayList<List<Integer>>();\n        if (nums == null || nums.length == 0) {\n            return result;\n        }\n        ArrayList<Integer> list = new ArrayList<Integer>();\n        Arrays.sort(nums);\n        addSubset(result, list, nums, 0);\n        return result;\n    }\n\n    private void addSubset(List<List<Integer>> result, ArrayList<Integer> list, int[] nums, int pos) {\n        result.add(new ArrayList<Integer>(list));\n        for (int i = pos; i < nums.length; i++) {\n            // in this level, if current loop is not the start element, check if it's duplicated with the previous element\n            if (i != pos && nums[i - 1] == nums[i]) {\n                continue;\n            }\n            list.add(nums[i]);\n            addSubset(result, list, nums, i + 1);\n            list.remove(list.size() - 1);\n        }\n    }\n\n    /**\n     * Lintcode version\n     * @param S: A set of numbers.\n     * @return: A list of lists. All valid subsets.\n     */\n    public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> s) {\n        // write your code here\n        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();\n        if (s == null || s.size() == 0) {\n            return result;\n        }\n        ArrayList<Integer> list = new ArrayList<Integer>();\n        Collections.sort(s);\n        addSubset(s, result, list, 0);\n        return result;\n    }\n\n    private void addSubset(\n            ArrayList<Integer> s,\n            ArrayList<ArrayList<Integer>> result,\n            ArrayList<Integer> list,\n            int pos) {\n        result.add(new ArrayList<Integer>(list));\n        for (int i = pos; i < s.size(); i++) {\n            if (i != pos && s.get(i - 1) == s.get(i)) {\n                continue;\n            }\n            list.add(s.get(i));\n            addSubset(s, result, list, i + 1);\n            list.remove(list.size() - 1);\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/subsets/subsetsIITest.java",
    "content": "package subsets;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.Assert.assertTrue;\n\n/**\n * Created by leicao on 2/10/15.\n */\npublic class subsetsIITest {\n\n    @Test\n    public void testSubsetsIILintcode() throws Exception {\n\n        ArrayList<Integer> inputs = new ArrayList<Integer>(){{\n            add(1);\n            add(2);\n            add(2);\n        }};\n        ArrayList<ArrayList<Integer>> outputs = new ArrayList<ArrayList<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n            }});\n        }};\n        subsetsII s = new subsetsII();\n        ArrayList<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>();\n        r = s.subsetsWithDup(inputs);\n\n        System.out.println(r);\n        assertTrue(r.containsAll(outputs) && r.size() == outputs.size());\n    }\n\n    @Test\n    public void testSubsetsIILeetcode() throws Exception {\n        int[] inputs = {1,2,2};\n        List<List<Integer>> outputs = new ArrayList<List<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n            }});\n        }};\n        subsetsII s = new subsetsII();\n        List<List<Integer>> r = new ArrayList<List<Integer>>();\n        r = s.subsetsWithDup(inputs);\n\n        System.out.println(r);\n        assertTrue(r.containsAll(outputs) && r.size() == outputs.size());\n    }\n}"
  },
  {
    "path": "algorithms/java/src/subsets/subsetsTest.java",
    "content": "package subsets;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 2/10/15.\n */\npublic class subsetsTest {\n\n    @Test\n    public void testSubsets() throws Exception {\n\n        ArrayList<Integer> inputs = new ArrayList<Integer>(){{\n            add(1);\n            add(2);\n            add(3);\n        }};\n        ArrayList<ArrayList<Integer>> outputs = new ArrayList<ArrayList<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n            }});\n        }};\n        subsets s = new subsets();\n        ArrayList<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>();\n        r = s.subsets(inputs);\n\n        System.out.println(r);\n        assertTrue(r.containsAll(outputs) && r.size() == outputs.size());\n    }\n\n    @Test\n    public void testSubsets1() throws Exception {\n        int[] inputs = {1,2,3};\n        List<List<Integer>> outputs = new ArrayList<List<Integer>>(){{\n            add(new ArrayList<Integer>(){{\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(2);\n                add(3);\n            }});\n            add(new ArrayList<Integer>(){{\n                add(1);\n                add(2);\n            }});\n            add(new ArrayList<Integer>(){{\n            }});\n        }};\n        subsets s = new subsets();\n        List<List<Integer>> r = new ArrayList<List<Integer>>();\n        r = s.subsets(inputs);\n\n        System.out.println(r);\n        assertTrue(r.containsAll(outputs) && r.size() == outputs.size());\n    }\n}"
  },
  {
    "path": "algorithms/java/src/validAnagram/TestValidAnagram.java",
    "content": "package validAnagram;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n/**\n * Test for 242. Valid Anagram\n */\npublic class TestValidAnagram {\n\t@Test\n\tpublic void test() {\n\t\tValidAnagram solution = new ValidAnagram();\n\t\tAssert.assertTrue(solution.isAnagram(\"anagram\", \"nagaram\"));\n\t\tAssert.assertTrue(!solution.isAnagram(\"rat\", \"car\"));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/validAnagram/ValidAnagram.java",
    "content": "// Source : https://leetcode.com/problems/valid-anagram/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Given two strings s and t, write a function to determine if t is an anagram of s.\n * \n * For example,\n * s = \"anagram\", t = \"nagaram\", return true.\n * s = \"rat\", t = \"car\", return false.\n * \n * Note:\n * You may assume the string contains only lowercase alphabets.\n * \n * Follow up:\n * What if the inputs contain unicode characters? How would you adapt your solution to such case?\n * \n **********************************************************************************/\npackage validAnagram;\n\npublic class ValidAnagram {\n\t\n\t/**\n\t * Like counting-sort\n\t */\n\tpublic boolean isAnagram(String s, String t) {\n\t\tif (s == null && t == null) {\n\t\t\treturn true;\n\t\t}\n\t\tif (s.length() != t.length()) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal int mapLen = 26;\n\t\tint[] map1 = new int[mapLen];\n\t\tint[] map2 = new int[mapLen];\n\t\tint len = s.length();\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tchar c1 = s.charAt(i);\n\t\t\tmap1[c1 - 'a']++;\n\t\t\t// ASCII of letter a is 97\n\t\t\tint c2 = t.charAt(i);\n\t\t\tmap2[c2 - 97]++;\n\t\t}\n\t\tfor (int i = 0; i < mapLen; i++) {\n\t\t\tif (map1[i] != map2[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\t\n}\n"
  },
  {
    "path": "algorithms/java/src/validPalindrome/TestValidPalindrome.java",
    "content": "package validPalindrome;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n/**\n * Test for 125. Valid Palindrome\n */\npublic class TestValidPalindrome {\n\t@Test\n\tpublic void test() {\n\t\tValidPalindrome solution = new ValidPalindrome();\n\t\tString str1 = \"A man, a plan, a canal: Panama\";\n\t\tAssert.assertTrue(solution.isPalindrome(str1));\n\t\tString str2 = \"race a car\";\n\t\tAssert.assertTrue(!solution.isPalindrome(str2));\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/validPalindrome/ValidPalindrome.java",
    "content": "// Source : https://leetcode.com/problems/valid-palindrome/description/\n// Author : Tianming Cao\n// Date   : 2018-02-11\n\n/**********************************************************************************\n * \n * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n * \n * For example,\n * \"A man, a plan, a canal: Panama\" is a palindrome.\n * \"race a car\" is not a palindrome.\n * \n * Note:\n * Have you consider that the string might be empty? This is a good question to ask during an interview.\n * \n * For the purpose of this problem, we define empty string as valid palindrome.\n * \n **********************************************************************************/\npackage validPalindrome;\n\npublic class ValidPalindrome {\n\tprivate boolean isAlphaNumber(char c) {\n\t\tif ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t/**\n\t * We need two pointers like below:\n\t * \n\t *  i                   j   \n\t *  ↓------->  <--------↓\n\t *  a,b c d e e d;c b a +\n\t *  \n\t *  Move them from border to mid, util i meet j or s[i]!=s[j]\n\t */\n\tpublic boolean isPalindrome(String s) {\n\t\tif (s == null || s.length() <= 1) {\n\t\t\treturn true;\n\t\t}\n\t\ts = s.toLowerCase();\n\t\tint i = 0, j = s.length() - 1;\n\t\twhile (i < j) {\n\t\t\twhile (!isAlphaNumber(s.charAt(i)) && i < j) {\n\t\t\t\ti++;\n\t\t\t}\n\t\t\twhile (!isAlphaNumber(s.charAt(j)) && i < j) {\n\t\t\t\tj--;\n\t\t\t}\n\t\t\tif (s.charAt(i) != s.charAt(j)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ti++;\n\t\t\tj--;\n\t\t}\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "algorithms/java/src/validateBinarySearchTree/TreeNode.java",
    "content": "package validateBinarySearchTree;\n\npublic class TreeNode {\n    public int val;\n    public TreeNode left, right;\n    public TreeNode(int val) {\n        this.val = val;\n        this.left = this.right = null;\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/validateBinarySearchTree/validateBinarySearchTree.java",
    "content": "// Source : https://oj.leetcode.com/problems/validate-binary-search-tree/\n// Inspired by : http://www.jiuzhang.com/solutions/validate-binary-search-tree/\n// Author : Lei Cao\n// Date   : 2015-10-06\n\n/**********************************************************************************\n *\n * Given a binary tree, determine if it is a valid binary search tree (BST).\n *\n * Assume a BST is defined as follows:\n *\n * The left subtree of a node contains only nodes with keys less than the node's key.\n * The right subtree of a node contains only nodes with keys greater than the node's key.\n * Both the left and right subtrees must also be binary search trees.\n *\n * confused what \"{1,#,2,3}\" means? > read more on how binary tree is serialized on OJ.\n *\n * OJ's Binary Tree Serialization:\n *\n * The serialization of a binary tree follows a level order traversal, where '#' signifies\n * a path terminator where no node exists below.\n *\n * Here's an example:\n *\n *    1\n *   / \\\n *  2   3\n *     /\n *    4\n *     \\\n *      5\n *\n * The above binary tree is serialized as \"{1,2,3,#,#,4,#,#,5}\".\n *\n *\n **********************************************************************************/\n\npackage validateBinarySearchTree;\n\npublic class validateBinarySearchTree {\n    public boolean isValidBST(TreeNode root) {\n        return isBSTTraversal(root) && isBSTDivideAndConquer(root);\n    }\n\n    // Solution 1: Traversal\n    // The inorder sequence of a BST is a sorted ascending list\n    private int lastValue = 0; // the init value of it doesn't matter.\n    private boolean firstNode = true;\n    public boolean isBSTTraversal(TreeNode root) {\n        if (root == null) {\n            return true;\n        }\n\n        if (!isValidBST(root.left)) {\n            return false;\n        }\n\n        // firstNode is needed because of if firstNode is Integer.MIN_VALUE,\n        // even if we set lastValue to Integer.MIN_VALUE, it will still return false\n        if (!firstNode && lastValue >= root.val) {\n            return false;\n        }\n\n        firstNode = false;\n        lastValue = root.val;\n\n        if (!isValidBST(root.right)) {\n            return false;\n        }\n\n        return true;\n\n    }\n\n    // Solution 2: divide && conquer\n    private class Result {\n        int min;\n        int max;\n        boolean isBST;\n        Result(int min, int max, boolean isBST) {\n            this.min = min;\n            this.max = max;\n            this.isBST = isBST;\n        }\n    }\n\n    public boolean isBSTDivideAndConquer(TreeNode root) {\n        return isBSTHelper(root).isBST;\n    }\n\n    public Result isBSTHelper(TreeNode root) {\n        // For leaf node's left or right\n        if (root == null) {\n            // we set min to Integer.MAX_VALUE and max to Integer.MIN_VALUE\n            // because of in the previous level which is the leaf level,\n            // we want to set the min or max to that leaf node's val (in the last return line)\n            return new Result(Integer.MAX_VALUE, Integer.MIN_VALUE, true);\n        }\n\n        Result left = isBSTHelper(root.left);\n        Result right = isBSTHelper(root.right);\n\n        if (!left.isBST || !right.isBST) {\n            return new Result(0,0, false);\n        }\n\n        // For non-leaf node\n        if (root.left != null && left.max >= root.val\n                && root.right != null && right.min <= root.val) {\n            return new Result(0, 0, false);\n        }\n\n        return new Result(Math.min(left.min, root.val),\n                Math.max(right.max, root.val), true);\n    }\n}\n"
  },
  {
    "path": "algorithms/java/src/validateBinarySearchTree/validateBinarySearchTreeTest.java",
    "content": "package validateBinarySearchTree;\n\nimport org.junit.Test;\nimport java.util.ArrayList;\nimport static org.junit.Assert.*;\n\n/**\n * Created by leicao on 6/10/15.\n */\npublic class validateBinarySearchTreeTest {\n\n    @Test\n    public void testIsValidBST() throws Exception {\n        // [10,5,15,null,null,6,20]\n        TreeNode t0 = new TreeNode(0);\n\n        TreeNode n0 = new TreeNode(10);\n        TreeNode n1 = new TreeNode(5);\n        TreeNode n2 = new TreeNode(15);\n        TreeNode n3 = null;\n        TreeNode n4 = null;\n        TreeNode n5 = new TreeNode(6);\n        TreeNode n6 = new TreeNode(20);\n\n        n0.left = n1;\n        n0.right = n2;\n\n        n1.left = n3;\n        n1.right = n4;\n\n        n2.left = n5;\n        n2.right = n6;\n\n        TreeNode tt0 = new TreeNode(1);\n        TreeNode tt1 = new TreeNode(1);\n        tt0.left = tt1;\n\n        TreeNode ttt0 = new TreeNode(2147483647);\n\n        //[-2147483648,null,2147483647]\n        TreeNode nn0 = new TreeNode(-2147483648);\n        TreeNode nn1 = new TreeNode(2147483647);\n        nn0.left = null;\n        nn0.right = nn1;\n\n        ArrayList<TreeNode> inputes = new ArrayList<TreeNode>();\n        inputes.add(t0);\n        inputes.add(n0);\n        inputes.add(tt0);\n        inputes.add(ttt0);\n        inputes.add(nn0);\n\n        boolean[] results = {\n                true,\n                false,\n                false,\n                true,\n                true\n        };\n\n        for (int i = 0; i < results.length; i++) {\n            validateBinarySearchTree v = new validateBinarySearchTree();\n            boolean r = v.isValidBST(inputes.get(i));\n            assertEquals(results[i], r);\n        }\n    }\n}"
  },
  {
    "path": "algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py",
    "content": "def isOneBitCharacter(self, bits):\n    i = 0\n    while i < len(bits):\n        if bits[i] == 0:\n            i += 1\n        if i >= len(bits): return True\n        if bits[i] == 1:\n            i += 2\n        if i >= len(bits): return False\n        if i == len(bits) - 1: return True"
  },
  {
    "path": "algorithms/python/AddOneRowToTree/addOneRow.py",
    "content": "# get the nodes at (d - 1) layer:\n\ndef addOneRow(self, root, v, d):\n    dummy, dummy.left = TreeNode(v), root\n    row = [dummy]\n    for _ in range(d - 1):\n        row = [kid for node in row for kid in (node.left, node.right) if kid]\n    \n    for node in row:\n        node.left, node.left.left = TreeNode(v), node.left\n        node.right, node.right.right = TreeNode(v), node.right\n    return dummy.left"
  },
  {
    "path": "algorithms/python/BinarySearchTreeIterator/BSTIterator.py",
    "content": "# straight forward solution: do a inorder traversal\n\nclass BSTIterator(object):\n    def __init__(self, root):\n        self.inorder = []\n        def helper(root):\n            if root:\n                helper(root.left)\n                self.inorder.append(root.val)\n                helper(root.right)\n        helper(root)\n        \n    def hasNext(self):\n        return len(self.inorder) != 0\n\n    def next(self):\n        return self.inorder.pop(0)\n\n# Alternative solution:\nclass BSTIterator(object):\n    def __init__(self, root):\n        self.stack = []\n        while root:\n            self.stack.append(root)\n            root = root.left\n        \n\n    def hasNext(self):\n        return len(self.stack) != 0\n        \n\n    def next(self):\n        node = self.stack.pop()\n        x = node.right\n        while x:\n            self.stack.append(x)\n            x = x.left\n        return node.val\n    "
  },
  {
    "path": "algorithms/python/BinaryTreePostorderTraversal/postorderTraversal.py",
    "content": "\"\"\"\nMethod 1: recursive\n\"\"\"\ndef postorderTraversal(self, root):\n    res = []\n    def helper(root):\n        if root:\n            helper(root.left)\n            helper(root.right)\n            res.append(root.val)\n    helper(root)\n    return res\n\n\"\"\"\nMethod 2: iterative, using two stacks\ninitialize first stack with root node, do the following if first is not None:\n    pop from first stack, append the popped element to second stack,\n    add left and right node to first stack if they are not None\nreturn the second stack's value in reverse order\n\"\"\"\ndef postorderTraversal(self, root):\n    if not root: return []\n    first, second = [root], []\n    while first:\n        node = first.pop()\n        second.append(node)\n        if node.left: first.append(node.left)\n        if node.right: first.append(node.right)\n    res = [node.val for node in second]\n    res.reverse()\n    return res"
  },
  {
    "path": "algorithms/python/BinaryTreeTilt/findTilt.py",
    "content": "def findTilt(self, root):\n    self.res = 0\n    def helper(root):\n        if not root: return 0\n        left = helper(root.left)\n        right = helper(root.right)\n        self.res += abs(left - right)\n        return root.val + left + right\n    helper(root)\n    return self.res"
  },
  {
    "path": "algorithms/python/BinaryTreeZigzagLevelOrderTraversal/zigzagLevelOrder.py",
    "content": "\"\"\"\nsimple bfs\n\"\"\"\n\ndef zigzagLevelOrder(self, root):\n    if not root: return []\n    stack = [[root]]\n    res = [[root.val]]\n    level = 0\n    while True:\n        level += 1\n        children = [child for node in stack[-1] for child in (node.left, node.right) if child]\n        if not children: break\n        temp = [node.val for node in children]\n        if level % 2 == 1: temp.reverse()\n        res.append(temp)\n        stack.append(children)\n    return res"
  },
  {
    "path": "algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py",
    "content": "def isCompleteTree(self, root):\n    stack = [[(root, 0)]]\n    layer = 0\n    while True:\n        children = []\n        for node, value in stack[-1]:\n            if node.left: children.append((node.left, 2 * value))\n            if node.right: children.append((node.right, 2 * value + 1))\n            if node.right and not node.left: return False\n        if not children: break\n        if len(stack[-1]) != pow(2, layer): return False\n        stack.append(children)\n        layer += 1\n    return len(stack[-1]) == stack[-1][-1][1] + 1"
  },
  {
    "path": "algorithms/python/ConstructBinaryTreeFromInorderAndPostorderTraversal/buildTree.py",
    "content": "def buildTree(self, inorder, postorder):\n    if inorder:\n        i = inorder.index(postorder.pop())\n        root = TreeNode(inorder[i])\n        root.right = self.buildTree(inorder[i+1:], postorder)\n        root.left = self.buildTree(inorder[:i], postorder)\n        return root"
  },
  {
    "path": "algorithms/python/ConstructBinaryTreeFromPreorderAndInorderTraversal/buildTree.py",
    "content": "def buildTree(self, preorder, inorder):\n    if inorder:\n        i = inorder.index(preorder.pop(0))\n        root = TreeNode(inorder[i])\n        root.left = self.buildTree(preorder, inorder[:i])\n        root.right = self.buildTree(preorder, inorder[i+1:])\n        return root"
  },
  {
    "path": "algorithms/python/ContainsDuplicateII/containsNearbyDuplicate.py",
    "content": "# Method 1: using set\n\ndef containsNearbyDuplicate(self, nums, k):\n    if len(nums) <= k + 1: return len(nums) != len(set(nums))\n    if k == 0: return False\n    s = set(nums[:k])\n    for i in range(k, len(nums)):\n        if nums[i] in s: return True\n        else:\n            s.remove(nums[i - k])\n            s.add(nums[i])\n    return False\n\n# Method 2: using dictionary\ndef containsNearbyDuplicate(self, nums, k):\n    d = {}\n    for i, n in enumerate(nums):\n        if n in d and i - d[n] <= k:\n            return True\n        d[n] = i\n    return False\n"
  },
  {
    "path": "algorithms/python/ContainsDuplicateIII/containsNearbyAlmostDuplicate.py",
    "content": "def containsNearbyAlmostDuplicate(self, nums, k, t):\n    if k < 1 or t < 0: return False\n    d = {}\n    w = t + 1\n    for i, n in enumerate(nums):\n        m = n // w\n        if m in d: return True\n        if m - 1 in d and abs(d[m-1] - n) <= t: return True\n        if m + 1 in d and abs(d[m+1] - n) <= t: return True\n        d[m] = n\n        if i >= k: del d[nums[i - k] // w]\n    return False"
  },
  {
    "path": "algorithms/python/ConvertBSTtoGreaterTree/convertBST.py",
    "content": "\"\"\"\nsince this is a BST, we can do a inorder traversal (inversed, from right to left),\nduring this process, track the sum and update the node.val\n\"\"\"\n\nclass Solution:\n    def convertBST(self, root):\n        self.total = 0\n        \n        def helper(node):\n            if not node: return\n            helper(node.right)\n            node.val += self.total\n            self.total = node.val\n            helper(node.left)\n        \n        helper(root)\n        return root"
  },
  {
    "path": "algorithms/python/CopyListWithRandomPointer/copyRandomList.py",
    "content": "# method 1: using a dict and store each node as key, each copied node as value\n# Space complexity: O(n)\n# Time complexity: O(n)\n\ndef copyRandomList(self, head):\n    d = {}\n    m = n = head\n    while m:\n        d[m] = RandomListNode(m.label)\n        m = m.next\n        \n    while n:\n        d[n].next = d.get(n.next)\n        d[n].random = d.get(n.random)\n        n = n.next\n        \n    return d.get(head)\n\n# Method 2:\n# Space complexity: O(1)\n# Time complexity: O(n)\n\ndef copyRandomList(self, head):\n    if not head: return None\n    \n    # Step 1: copy each node and link them together with original ones \n    curr = head\n    while curr:\n        new = RandomListNode(curr.label)\n        new.next = curr.next\n        curr.next = new\n        curr = curr.next.next\n    \n    # Step 2: build random node for each copied nodes\n    curr = head    \n    while curr:\n        if curr.random: curr.next.random = curr.random.next\n        curr = curr.next.next\n        \n    # Step 3: restore the original list and extract copied list\n    newhead = head.next\n    pold = head\n    pnew = newhead\n    while pnew.next:\n        pold.next = pnew.next\n        pold = pold.next\n        pnew.next = pold.next\n        pnew = pnew.next\n    pold.next = None\n    pnew.next = None\n    return newhead"
  },
  {
    "path": "algorithms/python/CountCompleteTreeNodes/countNodes.py",
    "content": "def countNodes(self, root):\n    if not root: return 0\n    hl, hr = 0, 0\n    l, r = root, root\n    while l:\n        hl += 1\n        l = l.left\n    while r:\n        hr += 1\n        r = r.right\n    if hl == hr: return pow(2, hl) - 1\n    return 1 + self.countNodes(root.left) + self.countNodes(root.right)"
  },
  {
    "path": "algorithms/python/DeleteNodeInABST/deleteNode.py",
    "content": "\"\"\"\ncase 1: if node we want to delete has no children: simply delete it\ncase 2: if it has only one child, then replace it with its child\ncase 3: if it has two children, first find the inorder successor (or predecessor),\n        then replace the node's value with successor's value, and finally delete this successor\n\"\"\"\n\ndef deleteNode(self, root, key):\n    if not root: return None\n    if key < root.val: \n        root.left = self.deleteNode(root.left, key)\n    elif key > root.val:\n        root.right = self.deleteNode(root.right, key)\n    else:\n        # if this node has only one child or no child:\n        if not root.left:\n            temp = root.right\n            root = None\n            return temp\n        elif not root.right:\n            temp = root.left\n            root = None\n            return temp\n        \n        # otherwise, find the inorder successor:\n        curr = root.right\n        while curr.left:\n            curr = curr.left\n        \n        root.val = curr.val\n        root.right = self.deleteNode(root.right, curr.val)\n    return root"
  },
  {
    "path": "algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py",
    "content": "def diameterOfBinaryTree(self, root):\n    self.res = 0\n    def helper(root):\n        if not root: return 0\n        left, right = helper(root.left), helper(root.right)\n        self.res = max(self.res, left + right)\n        return 1 + max(left, right)\n    helper(root)\n    return self.res"
  },
  {
    "path": "algorithms/python/DifferentWaysToAddParentheses/diffWaysToCompute.py",
    "content": "def diffWaysToCompute(self, input):\n    return [a + b if c == '+' else a - b if c == '-' else a * b \\\n            for i, c in enumerate(input) if c in '+-*' \\\n            for a in self.diffWaysToCompute(input[:i]) \\\n            for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]"
  },
  {
    "path": "algorithms/python/FibonacciNumber/fib.py",
    "content": "\"\"\"\nMethod 1: iterative:\n\"\"\"\ndef fib1(self, N):\n    if N <= 1: return N\n    a, b = 0, 1\n    for _ in range(2, N + 1):\n        a, b = b, a + b\n    return b\n    \n\"\"\"\nMethod 2: recursive without memorization:\n\"\"\"\ndef fib2(self, N):\n    if N <= 1: return N\n    return self.fib(N - 1) + self.fib(N - 2)\n\n\"\"\"\nMethod 3: recursive with memorization\n\"\"\"\ndef fib3(self, N):\n    memo = {0:0, 1:1}\n    def helper(n):\n        if n not in memo:\n            memo[n] = helper(n - 1) + helper(n - 2)\n        return memo[n]\n    return helper(N)"
  },
  {
    "path": "algorithms/python/FindDuplicateSubtrees/findDuplicateSubtrees.py",
    "content": "def findDuplicateSubtrees(self, root):\n    nodes = collections.defaultdict(list)\n    \n    def helper(root):\n        if not root: return 'None'\n        struct = '%s,%s,%s' % (str(root.val), helper(root.left), helper(root.right))\n        nodes[struct].append(root)\n        return struct\n    \n    helper(root)\n    return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1]"
  },
  {
    "path": "algorithms/python/FindTheDuplicateNumber/findDuplicate.py",
    "content": "# the same as linked list cycle problem\ndef findDuplicate(self, nums):\n    if len(nums) <= 1: return -1\n    slow, fast = nums[0], nums[nums[0]]\n    while slow != fast:\n        slow = nums[slow]\n        fast = nums[nums[fast]]\n    \n    fast = 0\n    while slow != fast:\n        slow = nums[slow]\n        fast = nums[fast]\n    return slow"
  },
  {
    "path": "algorithms/python/FlattenBinaryTreeToLinkedList/flatten.py",
    "content": "class Solution(object):\n    def __init__(self):\n        self.prev = None\n        \n    def flatten(self, root):\n        if not root: return None\n        self.flatten(root.right)\n        self.flatten(root.left)\n        root.right = self.prev\n        root.left = None\n        self.prev = root"
  },
  {
    "path": "algorithms/python/FlipBinaryTreeToMatchPreorderTraversal/flipMatchVoyage.py",
    "content": "def flipMatchVoyage(self, root, voyage):\n    res = []\n    self.i = 0\n    def dfs(root):\n        if not root: return True\n        if root.val != voyage[self.i]: return False\n        self.i += 1\n        if root.left and root.left.val != voyage[self.i]:\n            res.append(root.val)\n            root.left, root.right = root.right, root.left\n        return dfs(root.left) and dfs(root.right)\n    return res if dfs(root) else [-1]"
  },
  {
    "path": "algorithms/python/FlipEquivalentBinaryTrees/flipEquiv.py",
    "content": "\"\"\"\nMethod 1: \n    naive recursive solution, divide the original problem into four subproblems,\n    time complexity and space complexity are both O(n^2)\n\"\"\"\ndef flipEquiv1(self, root1, root2):\n    if not root1 or not root2:\n        return root1 == root2\n    if root1.val != root2.val:\n        return False\n    return self.flipEquiv(root1.left, root2.left) and \\\n            self.flipEquiv(root1.right, root2.right) or \\\n            self.flipEquiv(root1.left, root2.right) and \\\n            self.flipEquiv(root1.right, root2.left)\n\n\"\"\"\nMethod 2: \n    Step 1: first preprocessing these two trees, sort them in the following order:\n    if node.left.val > node.right.val, then swap them, make the smaller one to be left node\n    if the left node is None, then also swap them, make the non-None node to be left node\n\n    Step 2: compare the swapped trees\n\n    After preprocessing, the original problem is divided into two subproblems, time complexity: O(n)\n\"\"\"\ndef flipEquiv2(self, root1, root2):\n    def flip(root):\n        if root:\n            if root.left and root.right and root.left.val > root.right.val:\n                root.left, root.right = root.right, root.left\n            if not root.left:\n                root.left, root.right = root.right, root.left\n            flip(root.left)\n            flip(root.right)\n    \n    def is_equal(root1, root2):\n        if not root1 or not root2:\n            return root1 == root2\n        return root1.val == root2.val and \\\n                is_equal(root1.left, root2.left) and \\\n                is_equal(root1.right, root2.right)\n    \n    flip(root1)\n    flip(root2)\n    return is_equal(root1, root2)"
  },
  {
    "path": "algorithms/python/HappyNumber/isHappy.py",
    "content": "# Method 1: straight forward solution, use a set to track if there is a cycle\n\ndef isHappy1(self, n):\n    if n <= 0: return False\n    s = set()\n    while n not in s:\n        s.add(n)\n        n = sum([int(i) ** 2 for i in str(n)])\n        if n == 1: return True\n    return False\n\n# Method 2: using a slow and fast pointer to determine cycle (like in linked list)\n# No extra space needed\ndef isHappy2(self, n):\n    \"\"\"\n    :type n: int\n    :rtype: bool\n    \"\"\"\n    if n <= 0: return False\n    def helper(n):\n        res = 0\n        while n:\n            res += (n % 10) ** 2\n            n = n // 10\n        return res\n    \n    slow = fast = n\n    while True:\n        slow = helper(slow)\n        fast = helper(helper(fast))\n        if slow == 1: return True\n        if slow == fast: break\n    return False"
  },
  {
    "path": "algorithms/python/HouseRobber/rob.py",
    "content": "def rob(self, nums):\n    temp = [0, 0]\n    for n in nums:\n        temp[0], temp[1] = max(temp), n + temp[0]\n    \n    return max(temp)"
  },
  {
    "path": "algorithms/python/HouseRobberIII/rob.py",
    "content": "\"\"\"\nAnswe inspired by the post from here: \nhttps://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem\n\"\"\"\n# Method 1: dynamic programming solution:\ndef rob1(self, root):\n        lookup = {}\n        def helper(root):\n            if not root: return 0\n            if root in lookup: return lookup[root]\n            val = 0\n        \n            if root.left:\n                val += helper(root.left.left) + helper(root.left.right)\n            if root.right:\n                val += helper(root.right.left) + helper(root.right.right)\n            val = max(val + root.val, helper(root.left) + helper(root.right))\n            lookup[root] = val\n            return val\n        return helper(root)\n\n# Method 2: Greedy approach:\ndef rob2(self, root):\n    def helper(root):\n        if not root: return [0, 0]\n        left, right = helper(root.left), helper(root.right)\n        not_robbed = max(left) + max(right)\n        robbed = root.val + left[0] + right[0]\n        return [not_robbed, robbed]\n    return max(helper(root))"
  },
  {
    "path": "algorithms/python/ImageSmoother/imageSmoother.py",
    "content": "def imageSmoother(self, M):\n    from copy import deepcopy\n    \n    if not M or not M[0]: return [[]]\n    row, col = len(M), len(M[0])\n    res = deepcopy(M)\n    for x in range(row):\n        for y in range(col):\n            temp = [M[i][j] for i in [x - 1, x, x + 1] for j in [y - 1, y, y + 1] if \\\n                    0 <= i < row and 0 <= j < col]\n            res[x][y] = sum(temp) // len(temp)\n            \n    return res"
  },
  {
    "path": "algorithms/python/InsertionSortList/insertionSortList.py",
    "content": "def insertionSortList(self, head):\n    if not head: return head\n    \n    dummy = ListNode(0)\n    curr = head\n    prev = dummy\n    \n    while curr:\n        next = curr.next\n        while prev.next and prev.next.val < curr.val:\n            prev = prev.next\n        \n        curr.next = prev.next\n        prev.next = curr\n        prev = dummy\n        \n        curr = next\n    \n    return dummy.next"
  },
  {
    "path": "algorithms/python/K-diffPairsInAnArray/findPairs.py",
    "content": "def findPairs(self, nums, k):\n    if k > 0:\n        return len(set(nums) & set(a + k for a in nums))\n    elif k == 0:\n        return sum(v > 1 for v in collections.Counter(nums).values())\n    return 0"
  },
  {
    "path": "algorithms/python/KthSmallestElementInABST/kthSmallest.py",
    "content": "# Method 1: recursive in-order traversal\ndef kthSmallest1(self, root, k):\n    inorder = []\n    def helper(root):\n        if root:\n            helper(root.left)\n            inorder.append(root.val)\n            helper(root.right)\n    \n    helper(root)\n    return inorder[k-1]\n\n# Method 2: iterative in-order traversal\ndef kthSmallest2(self, root, k):\n    stack = []\n    while root or stack:\n        while root:\n            stack.append(root)\n            root = root.left\n        root = stack.pop()\n        k -= 1\n        if k == 0: return root.val\n        root = root.right"
  },
  {
    "path": "algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py",
    "content": "def dominantIndex(self, nums):\n    i = nums.index(max(nums))\n    l = nums[i]\n    del nums[i]\n    if not nums: return 0\n    return i if l >= 2 * max(nums) else -1"
  },
  {
    "path": "algorithms/python/LargestPerimeterTriangle/largestPerimeter.py",
    "content": "def largestPerimeter(self, A):\n    A.sort()\n    n = len(A)\n    for i in range(1, len(A) - 1):\n        if A[n - i - 2] + A[n - i - 1] > A[n - i]:\n            return A[n - i - 2] + A[n - i - 1] + A[n - i]\n    return 0"
  },
  {
    "path": "algorithms/python/LinkedListCycleII/detectCycle.py",
    "content": "def detectCycle(self, head):\n    slow, fast = head, head\n    while fast and fast.next:\n        slow = slow.next\n        fast = fast.next.next\n        if slow == fast: break\n    \n    if not fast or not fast.next: return None\n    slow = head\n    while slow != fast:\n        slow = slow.next\n        fast = fast.next\n    return slow"
  },
  {
    "path": "algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py",
    "content": "def longestConsecutive(self, nums):\n    \n    #first, create a hashmap\n    hm = set(nums)\n    longest = 0\n    #find the longest consecutive sequence from each number in the new\n    #hashmap (set)\n    for num in hm:\n        if (num - 1) not in hm:\n            current = num + 1\n            cons = 1\n            while current in hm:\n                current += 1\n                cons += 1\n            if cons > longest:\n                longest = cons\n            \n    return longest"
  },
  {
    "path": "algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py",
    "content": "def findLengthOfLCIS(self, nums):\n    if not nums: return 0\n    res = 1\n    temp = 1\n    for i in range(1, len(nums)):\n        if nums[i] > nums[i - 1]:\n            temp += 1\n        else:\n            res = max(temp, res)\n            temp = 1\n    return max(temp, res)"
  },
  {
    "path": "algorithms/python/LongestTurbulentSubarray/maxTurbulenceSize.py",
    "content": "def maxTurbulenceSize(self, A):\n    res = inc = dec = 1\n    for i in range(1, len(A)):\n        if A[i] > A[i - 1]:\n            inc = dec + 1\n            dec = 1\n        elif A[i] < A[i - 1]:\n            dec = inc + 1\n            inc = 1\n        else:\n            inc = 1\n            dec = 1\n        res = max(res, max(inc, dec))\n    return res"
  },
  {
    "path": "algorithms/python/LongestUnivaluePath/longestUnivaluePath.py",
    "content": "def longestUnivaluePath(self, root):\n    self.longest = 0\n    def helper(root):\n        if not root: return 0\n        l, r = helper(root.left), helper(root.right)\n        left = (l + 1) if root.left and root.left.val == root.val else 0\n        right = (r + 1) if root.right and root.right.val == root.val else 0\n        self.longest = max(self.longest, left + right)\n        return max(left, right)\n    helper(root)\n    return self.longest"
  },
  {
    "path": "algorithms/python/LowestCommonAncestorOfABinarySearchTree/lowestCommonAncestor.py",
    "content": "# straight forward recursive solution\n\ndef lowestCommonAncestor(self, root, p, q):\n    if not root: return None\n    if root.val > p.val and root.val > q.val:\n        return self.lowestCommonAncestor(root.left, p, q)\n    elif root.val < p.val and root.val < q.val:\n        return self.lowestCommonAncestor(root.right, p, q)\n    return root"
  },
  {
    "path": "algorithms/python/LowestCommonAncestorOfABinaryTree/lowestCommonAncestor.py",
    "content": "def lowestCommonAncestor(self, root, p, q):\n    if root in (None, p, q): return root\n    left = self.lowestCommonAncestor(root.left, p, q)\n    right = self.lowestCommonAncestor(root.right, p, q)\n    return root if left and right else left or right"
  },
  {
    "path": "algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py",
    "content": "def maxDistToClosest(self, seats):\n    first = seats.index(1)\n    last = 0\n    for i in range(len(seats) - 1, -1, -1):\n        if seats[i]: \n            last = i\n            break\n    res = 0\n    temp = 0\n    for i in range(first, last + 1):\n        if seats[i] == 1:\n            res = max(temp, res)\n            temp = 0\n        else:\n            temp += 1\n    return max(first, len(seats) - last - 1, (res + 1) // 2)"
  },
  {
    "path": "algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py",
    "content": "# Method 1: sliding window\n\ndef findMaxAverage(self, nums, k):\n    total = 0\n    temp = float('-inf')\n    for i, n in enumerate(nums):\n        total += n\n        if i >= k: total -= nums[i- k]\n        if i >= k - 1:\n            temp = max(temp, total)\n    return temp / k\n    \n    \n    \n# Method 2: prefix sum\n def findMaxAverage(self, nums, k):\n        temp = [0]\n        for n in nums:\n            temp.append(temp[-1] + n)\n        \n        res = max(temp[i + k] - temp[i] for i in range(len(nums) - k + 1))\n        return res / k"
  },
  {
    "path": "algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py",
    "content": "# simply find the three largest and two smallest\n# Method 1: sort\ndef maximumProduct(self, nums):\n    nums.sort()\n    return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3])\n\n# Method 2: using heapq, O(n) time\ndef maximumProduct(self, nums):\n    import heapq\n    a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)\n    return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1])"
  },
  {
    "path": "algorithms/python/MaximumWidthOfBinaryTree/widthOfBinaryTree.py",
    "content": "def widthOfBinaryTree(self, root):\n    if not root: return 0\n    stack = [[(root, 0)]]\n    res = 1\n    while True:\n        children = []\n        for node, value in stack[-1]:\n            if node.left: children.append((node.left, value * 2))\n            if node.right: children.append((node.right, value * 2 + 1))\n        if not children: break\n        stack.append(children)\n        res = max(res, children[-1][1] - children[0][1] + 1)\n    return res"
  },
  {
    "path": "algorithms/python/MiddleOfTheLinkedList/middleOfTheLinkedList.py",
    "content": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\n\nclass Solution:\n    def middleNode(self, head: ListNode) -> ListNode:\n        aux = head\n        cont = 1\n        while aux.next:\n            cont += 1\n            aux = aux.next\n        print(cont)\n        if cont%2 == 0:\n            posicao = (cont/2)+1\n        else:\n            posicao = (cont//2)+1\n        aux = head\n        cont = 1\n        while True:\n            if cont == posicao:\n                return aux\n            aux = aux.next\n            cont += 1"
  },
  {
    "path": "algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py",
    "content": "def minCostClimbingStairs(self, cost):\n    temp = [0, cost[0]]\n    for i in range(1, len(cost)):\n        temp[0], temp[1] = temp[1], min(temp) + cost[i]\n    return min(temp)"
  },
  {
    "path": "algorithms/python/Non-decreasingArray/checkPossibility.py",
    "content": "def checkPossibility(self, nums):\n    count = 0\n    for i in range(1, len(nums)):\n        if nums[i] < nums[i - 1]:\n            count += 1\n            if i == 1 or nums[i - 2] <= nums[i]: nums[i - 1] = nums[i]\n            else: nums[i] = nums[i - 1]\n        \n        if count >= 2: return False\n    return True"
  },
  {
    "path": "algorithms/python/NumberOfIslands/numIslands.py",
    "content": "def numIslands(self, grid):\n    if not grid or not grid[0]: return 0\n    row, col = len(grid), len(grid[0])\n    self.visited = [[False for _ in range(col)] for _ in range(row)]\n    \n    def floodfill(i, j):\n        if grid[i][j] == '1' and self.visited[i][j] == False:\n            self.visited[i][j] = True\n            if i > 0:\n                floodfill(i - 1, j)\n            if i < row - 1:\n                floodfill(i + 1, j)\n            if j > 0:\n                floodfill(i, j - 1)\n            if j < col - 1:\n                floodfill(i, j + 1)\n    \n    res = 0\n    for i in range(row):\n        for j in range(col):\n            if grid[i][j] == '1' and self.visited[i][j] == False:\n                res += 1\n                floodfill(i, j)\n    return res"
  },
  {
    "path": "algorithms/python/PancakeSorting/pancakeSort.py",
    "content": "\"\"\"\nbasic idea: find the index of smallest element in A, filp the list from that index, this makes the smallest element\ncomes to the first, then filp the whole list, to make smallest element goes to the tail. And then delete that element.\n\nDo this step until all the smallest element comes to the tail, then just filp the whole list again, and we can get what we want\n\"\"\"\n\ndef pancakeSort(self, A):\n    res = []\n    n = len(A)\n    while A:\n        smallest = A.index(min(A))\n        res.append(smallest + 1)\n        res.append(len(A))\n        A = list(reversed(A[:smallest + 1])) + A[smallest + 1:]\n        A.reverse()\n        del A[-1]\n    res.append(n)\n    return res"
  },
  {
    "path": "algorithms/python/PartitionList/partition.py",
    "content": "def partition(self, head, x):\n    h1 = l1 = ListNode(0)\n    h2 = l2 = ListNode(0)\n    while head:\n        if head.val < x:\n            l1.next = head\n            l1 = l1.next\n        else:\n            l2.next = head\n            l2 = l2.next\n        head = head.next\n    l2.next = None\n    l1.next = h2.next\n    return h1.next"
  },
  {
    "path": "algorithms/python/PathSumII/pathSum.py",
    "content": "\"\"\"\nMethod 1\n\"\"\"\ndef pathSum(self, root, sum):\n    if not root: return []\n    res = []\n\n    def dfs(root, sum, ls, res):\n        if not root.left and not root.right and sum == root.val:\n            ls.append(root.val)\n            res.append(ls)\n        if root.left:\n            dfs(root.left, sum - root.val, ls + [root.val], res)\n        if root.right:\n            dfs(root.right, sum - root.val, ls + [root.val], res)\n\n    dfs(root, sum, [], res)\n    return res\n\n\"\"\"\nMethod 2\n\"\"\"\ndef pathSum(self, root, sum):\n    if not root: return []\n    if not root.left and not root.right and root.val == sum: return [[root.val]]\n    temp = self.pathSum(root.left, sum - root.val) + self.pathSum(root.right, sum - root.val)\n    return [[root.val] + i for i in temp]"
  },
  {
    "path": "algorithms/python/PathSumIII/pathSum.py",
    "content": "def pathSum(self, root, target):\n    self.result = 0\n    cache = {0:1}\n    \n    def dfs(root, currPathSum):\n        if not root: return  \n\n        currPathSum += root.val\n        oldPathSum = currPathSum - target\n\n        self.result += cache.get(oldPathSum, 0)\n        cache[currPathSum] = cache.get(currPathSum, 0) + 1\n\n\n        dfs(root.left, currPathSum)\n        dfs(root.right, currPathSum)\n\n        cache[currPathSum] -= 1\n    \n    dfs(root, 0)\n    return self.result"
  },
  {
    "path": "algorithms/python/PopulatingNextRightPointersInEachNode/connect.py",
    "content": "def connect(self, root):\n    if not root: return\n    stack = [[root]]\n    while True:\n        children = [child for node in stack[-1] for child in (node.left, node.right) if child]\n        if not children: break\n        stack.append(children)\n        for i in range(len(children) - 1):\n            children[i].next = children[i+1]"
  },
  {
    "path": "algorithms/python/PopulatingNextRightPointersInEachNodeII/connect.py",
    "content": "def connect(self, root):\n    if not root: return root\n    stack = [[root]]\n    while True:\n        children = [child for node in stack[-1] for child in (node.left, node.right) if child]\n        if not children: break\n        stack.append(children)\n        for i in range(len(children) - 1):\n            children[i].next = children[i + 1]"
  },
  {
    "path": "algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py",
    "content": "def largeGroupPositions(self, S):\n    res = []\n    i = 0\n    while i < len(S) - 2:\n        if S[i] == S[i + 1] and S[i] == S[i + 2]:\n            val = S[i]\n            index = i\n            while i < len(S) and S[i] == val:\n                i += 1\n            res.append([index, i - 1])\n            i -= 1\n        i += 1\n    return res"
  },
  {
    "path": "algorithms/python/PrintBinaryTree/printTree.py",
    "content": "# recursive solution: takes O(n) time\n# first get the height of the tree, then recusivly update the value\n\ndef printTree(self, root):\n    def get_height(root):\n        if not root: return 0\n        return 1 + max(get_height(root.left), get_height(root.right))\n    \n    def update(res, node, row, left, right):\n        if not node: return\n        mid = (left + right) // 2\n        res[row][mid] = str(node.val)\n        update(res, node.left, row + 1, left, mid - 1)\n        update(res, node.right, row + 1, mid + 1, right)\n    \n    height = get_height(root)\n    width = 2 ** height - 1\n    res = [['' for _ in range(width)] for _ in range(height)]\n    update(res, root, 0, 0, width - 1)\n    return res"
  },
  {
    "path": "algorithms/python/RedundantConnection/findRedundantConnection.py",
    "content": "\"\"\"\nsimple union find with path compression:\nat first, each vertices are disjoint, there are N connected components at the begining,\nafter add each edge, we unify those two connected components, if two vertices are already \nin the same connected component, then this edge will form a circle, just return this edge\n\"\"\"\n\ndef findRedundantConnection(self, edges):\n    id = list(range(len(edges) + 1))\n    \n    def find(u):\n        root = u\n        while root != id[root]: root = id[root]\n        \n        # path compression:\n        while u != root:\n            next = id[u]\n            id[u] = root\n            u = next\n        \n        return root\n    \n    for u, v in edges:\n        root1, root2 = find(u), find(v)\n        if root1 == root2: return [u, v]\n        \n        # else, unify these two components:\n        id[root1] = root2"
  },
  {
    "path": "algorithms/python/RemoveDuplicatesFromSortedListII/deleteDuplicates.py",
    "content": "def deleteDuplicates(self, head):\n    dummy = prev = ListNode(0)\n    dummy.next = head\n    while head and head.next:\n        if head.val == head.next.val:\n            while head and head.next and head.val == head.next.val:\n                head = head.next\n            head = head.next\n            prev.next = head\n        else:\n            prev = prev.next\n            head = head.next\n    return dummy.next"
  },
  {
    "path": "algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py",
    "content": "def removeNthFromEnd(self, head, n):\n    slow = fast = head\n    for i in range(n):\n        fast = fast.next\n    if not fast: return head.next\n    while fast.next:\n        fast = fast.next\n        slow = slow.next\n    slow.next = slow.next.next\n    return head"
  },
  {
    "path": "algorithms/python/ReorderList/reorderList.py",
    "content": "def reorderList(self, head):\n    if not head or not head.next: return\n    \n    # Step 1: find the middle node\n    middle = None\n    slow, fast = head, head\n    while fast and fast.next:\n        middle = slow\n        slow = slow.next\n        fast = fast.next.next\n    middle.next = None\n    \n    # Step 2: reverse the second half\n    prev = None\n    while slow:\n        nextNode = slow.next\n        slow.next = prev\n        prev, slow = slow, nextNode\n        \n    # Step 3: merge two lists\n    while head and prev:\n        first, second = head.next, prev.next\n        head.next = prev\n        if first: prev.next = first\n        head, prev = first, second"
  },
  {
    "path": "algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py",
    "content": "def deckRevealedIncreasing(self, deck):\n    deck.sort()\n    res = [0] * len(deck)\n    index = list(range(len(deck)))\n    \n    for i in range(len(deck)):\n        res[index.pop(0)] = deck[i]\n        if index: index.append(index.pop(0))\n    return res"
  },
  {
    "path": "algorithms/python/ReverseLinkedListII/reverseBetween.py",
    "content": "def reverseBetween(self, head, m, n):\n    if not head or n == m: return head\n    p = dummy = ListNode(0)\n    dummy.next = head\n    for _ in range(m - 1):\n        p = p.next\n    tail = p.next\n    \n    for _ in range(n - m):\n        temp = p.next\n        p.next = tail.next\n        tail.next = tail.next.next\n        p.next.next = temp\n    return dummy.next"
  },
  {
    "path": "algorithms/python/SearchA2DMatrixII/searchMatrix.py",
    "content": "# Method 1: Binary Search on each row, if the first element of the row is already bigger than target, then skip\n# Time Complexity: O(mlogn)\ndef searchMatrix1(self, matrix, target):\n    def helper(low, high, row):\n        while low <= high:\n            mid = (low + high) // 2\n            if matrix[row][mid] < target: low = mid + 1\n            elif matrix[row][mid] > target: high = mid - 1\n            else: return True\n        return False\n    \n    if not matrix or not matrix[0]: return False\n    for i in range(len(matrix)):\n        if matrix[i][0] > target: return False\n        elif matrix[i][0] == target: return True\n        if helper(0, len(matrix[i]) - 1, i): return True\n    return False\n\n# Method 2: compare the element with top-right corner, and reduce the search range\n# Time complexity: O(m + n)\ndef searchMatrix2(self, matrix, target):\n    if not matrix or not matrix[0]: return False\n    row, col = 0, len(matrix[0]) - 1\n    while row < len(matrix) and col >= 0:\n        if matrix[row][col] > target: col -= 1\n        elif matrix[row][col] < target: row += 1\n        else: return True\n    return False"
  },
  {
    "path": "algorithms/python/SecondMinimumNodeInABinaryTree/findSecondMinimumValue.py",
    "content": "\"\"\"\nbecause of the special porperty of the tree, the question basically is asking to find\nthe smallest element in the subtree of root. So, we can recursively find left and right\nvalue that is not equal to the root's value, and then return the smaller one of them\n\"\"\"\ndef findSecondMinimumValue(self, root):\n    if not root: return -1\n    if not root.left and not root.right: return -1\n    \n    left, right = root.left.val, root.right.val\n    if left == root.val: left = self.findSecondMinimumValue(root.left)\n    if right == root.val: right = self.findSecondMinimumValue(root.right)\n    if left != -1 and right != -1: return min(left, right)\n    if left == -1: return right\n    if right == -1: return left"
  },
  {
    "path": "algorithms/python/SerializeAndDeserializeBST/serialize.py",
    "content": "class Codec:\n\n    def serialize(self, root):\n        preorder = []\n        \n        def helper(node):\n            if node:\n                preorder.append(node.val)\n                helper(node.left)\n                helper(node.right)\n        helper(root)\n        return ' '.join(map(str, preorder))\n        \n\n    def deserialize(self, data):\n        vals = collections.deque(int(val) for val in data.split())\n        \n        def build(minval, maxval):\n            if vals and minval < vals[0] < maxval:\n                val = vals.popleft()\n                node = TreeNode(val)\n                node.left = build(minval, val)\n                node.right = build(val, maxval)\n                return node\n\n        return build(float('-infinity'), float('infinity'))"
  },
  {
    "path": "algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py",
    "content": "def findUnsortedSubarray(self, nums):\n    same = [a == b for a, b in zip(nums, sorted(nums))]\n    return 0 if all(same) else len(nums) - same.index(False) - same[::-1].index(False)"
  },
  {
    "path": "algorithms/python/SingleNumberII/SingleNumberII.py",
    "content": "def singleNumber(self, nums):\n           \n    #1. make hashmap\n    #2. while traversing list, add each element\n    #3. remove it once it has been seen 3 times\n    #4. finally, the only value left is the one we're looking for\n    \n    hashmap = defaultdict(int)\n    for num in nums:\n        hashmap[num] += 1\n        if hashmap[num] == 3:\n            del hashmap[num]\n            \n    singleNum = hashmap.keys()[0]\n    return singleNum\n"
  },
  {
    "path": "algorithms/python/SortList/sortList.py",
    "content": "# merge sort:\n\ndef sortList(self, head):\n    if not head or not head.next: return head\n    leftHalf, rightHalf = self.split(head)\n    left = self.sortList(leftHalf)\n    right = self.sortList(rightHalf)\n    return self.mergeSorted(left, right)\n    \ndef mergeSorted(self, a, b):\n    res = dummy = ListNode(0)\n    while a and b:\n        if a.val < b.val:\n            dummy.next = a\n            dummy = a\n            a = a.next\n        else:\n            dummy.next = b\n            dummy = b\n            b = b.next\n    if not a: dummy.next = b\n    else: dummy.next = a\n\n    return res.next\n    \ndef split(self, node):\n    if not node or not node.next:\n        return node, None\n    slow, fast = node, node\n    prev = None\n    while fast.next:\n        prev = slow\n        slow = slow.next\n        fast = fast.next.next\n        if not fast: break\n    prev.next = None\n    return node, slow"
  },
  {
    "path": "algorithms/python/SquaresOfSortedArray/sortedSquares.py",
    "content": "def sortedSquares(self, A):\n    return list(sorted([a ** 2 for a in A]))"
  },
  {
    "path": "algorithms/python/Subsets/subsets.py",
    "content": "def subsets(self, nums):\n    res = []\n    def backtracking(temp, start):\n        res.append(temp[:])\n        for i in range(start, len(nums)):\n            temp.append(nums[i])\n            backtracking(temp, i + 1)\n            temp.pop()\n    \n    backtracking([], 0)\n    return res\n    "
  },
  {
    "path": "algorithms/python/SubtreeOfAnotherTree/isSubtree.py",
    "content": "def isSubtree(self, s, t):\n    stack = [s]\n    while stack:\n        node = stack.pop(0)\n        if node.val == t.val:\n            if self.check(node, t): return True\n        stack += [child for child in [node.left, node.right] if child]\n    return False\n\ndef check(self, first, second):\n    if not first and not second:\n        return True\n    if first and second:\n        return first.val == second.val and self.check(first.left, second.left) and self.check(first.right, second.right)\n    return False"
  },
  {
    "path": "algorithms/python/SumOfLeftLeaves/sumOfLeftLeaves.py",
    "content": "\"\"\"\nstraight forward recursive solution:\nif left node is leave, add the value and the the right subtree\nif not, then recursively call left and right subtree\n\"\"\"\ndef sumOfLeftLeaves(self, root):\n    if not root: return 0\n    if root.left and not root.left.left and not root.left.right:\n        return root.left.val + self.sumOfLeftLeaves(root.right)\n    return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)"
  },
  {
    "path": "algorithms/python/SumRootToLeafNumbers/sumNumbers.py",
    "content": "\"\"\"\nMethod 1: dfs\n\"\"\"\ndef sumNumbers(self, root):\n    if not root: return 0\n    stack, res = [(root, root.val)], 0\n    while stack:\n        node, value = stack.pop()\n        if not node.left and not node.right:\n            res += value\n        if node.right:\n            stack.append((node.right, value * 10 + node.right.val))\n        if node.left:\n            stack.append((node.left, value * 10 + node.left.val))\n    return res\n    \n    \n    \n\"\"\"\nMethod 2: recursive solution\n\"\"\"\ndef sumNumbers(self, root):\n    return self.helper(root, 0)\n\ndef helper(self, node, s):\n    if not node: return 0\n    if not node.left and not node.right: return s * 10 + node.val\n    return self.helper(node.left, s * 10 + node.val) + \\\n            self.helper(node.right, s * 10 + node.val)"
  },
  {
    "path": "algorithms/python/SwimInRisingWater/swim_in_rising_water.py",
    "content": "\"\"\"\nSolution to LeetCode problem Swim in Rising Water (#778)\nDifficulty: Hard\n\nExplanation:\nWe are approaching the problem through Djikstras Algorith. Essentially a BFS but with a minimum heap. The neighbors that you are adding into the queue, you are only popping the minimum value neighbor. Amongst those popped value you are checking if that value is the max value seen so far. If it is, then you have found the solution.\n\"\"\"\nfrom heapq import heappush, heappop\nfrom typing import List\n\nclass Solution:\n    def swimInWater(self, grid: List[List[int]]) -> int:\n        src, dst = grid[0][0], grid[len(grid)-1][len(grid)-1]\n        visited = set()\n        heap_queue = [(src, 0, 0)]  # src, row, col\n        output = 0\n        directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n        while heap_queue:\n            current, row, col = heappop(heap_queue)\n            output = max(current, output)\n\n            # if we already hit the destination, break out of the loop\n            if current == dst:\n                break\n\n            for x, y in directions:\n                dx, dy = row+x, col+y\n                if self.check_bounds(dx, dy, grid) and (dx, dy) not in visited:\n                    heappush(heap_queue, (grid[dx][dy], dx, dy))\n                    visited.add((dx, dy))\n        return output\n\n    def check_bounds(self, r, c, grid) -> bool:\n        if 0 <= r < len(grid[0]) and 0 <= c < len(grid):\n            return True\n        return False\n\n\nif __name__ == \"__main__\":\n    grid = [[0, 2], [1, 3]]\n    print(Solution().swimInWater(grid))"
  },
  {
    "path": "algorithms/python/ThirdMaximumNumber/thirdMax.py",
    "content": "def thirdMax(self, nums):\n    if len(set(nums)) < 3: return max(nums)\n    first = second = third = float('-inf')\n    for n in nums:\n        if n > first:\n            third = second\n            second = first\n            first = n\n        elif second < n < first:\n            third = second\n            second = n\n        elif third < n < second:\n            third = n\n    return third"
  },
  {
    "path": "algorithms/python/UniqueBinarySearchTrees/numTrees.py",
    "content": "def numTrees(self, n):\n    if n == 1: return 1\n    res = [1, 1]\n    for i in range(2, n + 1):\n        val = 0\n        for j in range(i):\n            val += res[j] * res[i - j - 1]\n        res.append(val)\n    return res[n]"
  },
  {
    "path": "algorithms/python/UniqueBinarySearchTreesII/generateTrees.py",
    "content": "def generateTrees(self, n):\n    if n == 0: return []\n    \n    def helper(start, end):\n        ls = []\n        if start > end:\n            ls.append(None)\n            return ls\n        if start == end:\n            ls.append(TreeNode(start))\n            return ls\n        \n        for i in range(start, end + 1):\n            left = helper(start, i - 1)\n            right = helper(i + 1, end)\n            for lnode in left:\n                for rnode in right:\n                    root = TreeNode(i)\n                    root.left = lnode\n                    root.right = rnode\n                    ls.append(root)\n        return ls\n    \n    return helper(1, n)"
  },
  {
    "path": "algorithms/python/ValidMountainArray/validMountainArray.py",
    "content": "# Method 1: using index find the max first, and then process\n\ndef validMountainArray(self, A):\n    if len(A) < 3: return False\n    index = A.index(max(A))\n    if index == 0 or index == len(A) -1: return False\n    for i in range(1, len(A)):\n        if i <= index:\n            if A[i] <= A[i - 1]: return False\n        else:\n            if A[i] >= A[i - 1]: return False\n    return True\n\n\n# Method 2: one pass, using two pointers trace from the begining and end\ndef validMountainArray(self, A):\n    i, j = 0, len(A) - 1\n    while i < len(A) - 1 and A[i] < A[i + 1]: i += 1\n    while j > 0 and A[j - 1] > A[j]: j -= 1\n    return 0 < i == j < len(A) - 1"
  },
  {
    "path": "algorithms/python/ValidateBinarySearchTree/isValidBST.py",
    "content": "# method 1: using recursion\n\ndef isValidBST1(self, root, lower = float('-inf'), upper = float('inf')):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: bool\n    \"\"\"\n    if not root: return True\n    if root.val <= lower or root.val >= upper: return False\n    return self.isValidBST(root.left, lower, min(upper, root.val)) \\\n        and self.isValidBST(root.right, max(lower, root.val), upper)\n\n\n# method 2: a proper BST should have this porperty: inorder traversal is increasing\ndef isValidBST2(self, root):\n    inorder = []\n    def helper(root):\n        if root:\n            helper(root.left)\n            inorder.append(root.val)\n            helper(root.right)\n            \n    helper(root)\n    for i in range(len(inorder) - 1):\n        if inorder[i + 1] <= inorder[i]: return False\n    return True"
  },
  {
    "path": "algorithms/python/XOfAKindInADeckOfCards/hasGroupsSizeX.py",
    "content": "# Method 1: find the greatest common divisor using iteration\n\ndef hasGroupsSizeX(self, deck):\n    if len(deck) < 2: return False\n    vals = collections.Counter(deck).values()\n    for n in range(2, max(vals) + 1):\n        if all(v % n == 0 for v in vals): return True\n    return False\n\n# Method 2: find the greatest common divisor using reduce\n# Time complexity: O(n)\ndef hasGroupsSizeX(self, deck):\n    from functools import reduce\n    if len(deck) < 2: return False\n    vals = collections.Counter(deck).values()\n    def gcd(a, b):\n        while b: a, b = b, a % b\n        return a\n    return reduce(gcd, vals)"
  },
  {
    "path": "algorithms/python/firstMissingPositive/firstMissingPositive.py",
    "content": "# question : https://leetcode.com/problems/first-missing-positive/\n# Author : Samir Rajesh Prajapati\n# Date : 2020-10-01\n\n# ********************************************************************************* \n# * \n# * Given an unsorted integer array, find the first missing positive integer.\n# * \n# * For example,\n# * Given [1,2,0] return 3,\n# * and [3,4,-1,1] return 2.\n# * \n# * Your algorithm should run in O(n) time and uses constant space.\n# * \n# *               \n# **********************************************************************************\n\nclass Solution:\n    def firstMissingPositive(self, nums: [int]) -> int:\n        for i in range(len(nums)):\n            while nums[i]>0 and nums[i]<len(nums) and nums[i]-1!=i and nums[i]!=nums[nums[i]-1]:\n                nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]\n        for i in range(len(nums)):\n            if i + 1 != nums[i]:\n                return i + 1 \n        return len(nums) + 1\n                \nif __name__ == '__main__':\n    number = Solution()\n    print(number.firstMissingPositive([3,4,-1,1]))\n"
  },
  {
    "path": "algorithms/python/jumpGame/jumpGame.py",
    "content": "# Source : https://leetcode.com/problems/jump-game/\n# Author : Sudesh Chaudhary\n# Date   : 2020-10-01\n\n#  Given an array of non-negative integers, you are initially positioned at the first index of the array.\n\n#  Each element in the array represents your maximum jump length at that position.\n\n#  Determine if you are able to reach the last index.\n\n#  For example:\n#  A = [2,3,1,1,4], return true.\n\n#  A = [3,2,1,0,4], return false.\n\n\n# Solution\n# time O(n) space O(1)\n\n# traverse array, maintain the most far we can go\nclass Solution:\n    def canJump(self, nums: List[int]) -> bool:\n        n = len(nums)\n        # max index where we can go\n        farest = 0;\n        for i in range(n):\n            if i > farest:\n                return False\n            farest = max(farest, i + nums[i])\n        return True\n"
  },
  {
    "path": "algorithms/python/uniquePaths/uniquePathsIII.py",
    "content": "# 980. Unique Paths III\n# On a 2-dimensional grid, there are 4 types of squares:\n\n# 1 represents the starting square.  There is exactly one starting square.\n# 2 represents the ending square.  There is exactly one ending square.\n# 0 represents empty squares we can walk over.\n# -1 represents obstacles that we cannot walk over.\n# Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n\n \n\n# Example 1:\n\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n# Output: 2\n# Explanation: We have the following two paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n# 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n# Example 2:\n\n# Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n# Output: 4\n# Explanation: We have the following four paths: \n# 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n# 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n# 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n# 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n# Example 3:\n\n# Input: [[0,1],[2,0]]\n# Output: 0\n# Explanation: \n# There is no path that walks over every empty square exactly once.\n# Note that the starting and ending square can be anywhere in the grid.\n \n\n# Note:\n\n# 1 <= grid.length * grid[0].length <= 20\n\nclass Solution:\n    ans = 0\n    def findPathNum(self, i, j, grid: List[List[int]], curLen, pLen)->None:\n        if(grid[i][j]==2):\n            if(pLen-1==curLen):\n                self.ans+=1\n            return\n        elif (grid[i][j]==-1):\n            return\n        curLen+=1\n        grid[i][j]=-1\n        if(i-1>=0):\n            self.findPathNum(i-1, j, grid, curLen, pLen)\n        if(j-1>=0):\n            self.findPathNum(i, j-1, grid, curLen, pLen)\n        if(i+1<len(grid)):\n            self.findPathNum(i+1, j, grid, curLen, pLen)\n        if(j+1<len(grid[0])):\n            self.findPathNum(i, j+1, grid, curLen, pLen)\n        grid[i][j]=0\n        \n            \n    def uniquePathsIII(self, grid: List[List[int]]) -> int:\n        pathLen = 0\n        start = (0, 0)\n        for i in range(len(grid)):\n            for j in range(len(grid[0])):\n                if(grid[i][j]!=-1):\n                    pathLen+=1\n                    if(grid[i][j]==1):\n                        start = (i, j)\n        self.findPathNum(start[0], start[1], grid, 0, pathLen)\n        return self.ans\n        "
  },
  {
    "path": "database/README.md",
    "content": "### LeetCode Database\n\n\n| # | Title | Solution | Difficulty |\n|---| ----- | -------- | ---------- |\n|1|[Trips and Users](https://leetcode.com/problems/trips-and-users/)| [MySQL](./TripsAndUsers.sql)|Hard|\n"
  },
  {
    "path": "database/TripsAndUsers.sql",
    "content": "SELECT t.`Request_at` AS Day,\nROUND(COUNT(CASE WHEN t.`Status` = 'cancelled_by_driver' OR t.`Status` = 'cancelled_by_client' THEN 1 END) / COUNT(*), 2) AS \"Cancellation Rate\"\nFROM Trips t \nINNER JOIN Users u \nON t.Client_Id = u.Users_Id\nWHERE u.Banned = 'No'\nAND t.Request_at >= '2013-10-01'\nAND t.Request_at <= '2013-10-03'\nGROUP BY t.Request_at"
  },
  {
    "path": "scripts/README.md",
    "content": "Helpful Scripts\n============\n\n- [Helpful Scripts](#helpful-scripts)\n  - [workflow.sh](#workflowsh)\n  - [comments.sh](#commentssh)\n  - [readme.sh](#readmesh)\n\n## workflow.sh\n\n`workflow.sh` - it's used to run a number of operations. It depends on `comments.sh` and `readme.sh`\n\nFor example:\n```\n$ cd leetcode/algorithms/cpp\n$ ../../scripts/workflow.sh https://leetcode.com/problems/design-authentication-manager/\nStep 1 : Created \"designAuthenticationManager\" directory!\nStep 2 : Created \"designAuthenticationManager/DesignAuthenticationManager.cpp\" source file!\nStep 3 : Run \"git add designAuthenticationManager/DesignAuthenticationManager.cpp\"!\nStep 4 : Edited the \"designAuthenticationManagerDesignAuthenticationManager.cpp\"!\nStep 5 : Copied the readme text to Clipboard!\nStep 6 : Edited the \"README.md\"!\nStep 7 : You can commit the changes by running the following command line...\n\n            git commit -am \"New Problem Solution -\\\"Design Authentication Manager\\\"\"\n```\n\n## comments.sh\n\n`comments.sh` - it's used to generate author and problem description comments \n\n> **Notes**: \n> - The  `comments.sh`  is compatible for both Linux and Mac platform.\n> - The  `comments.sh`  needs [jq](https://stedolan.github.io/jq/) to grab & parse the json contents. \n> - The  `comments.sh`  currently can automatically detect the problem's type, if the problem is `algorithm` type, it's going to create `.cpp` file, if the problem is `shell` type, the `.sh` file will be created.\n\n1. Create a file named largestNumber.cpp, and add Copyright & Problem description\n\n    ```sh\n    ./comments.sh https://leetcode.com/problems/largest-number/\n    ```\n\n2. Add Copyright & Problem description into existed file\n\n    ```sh\n    ./comments.sh https://leetcode.com/problems/largest-number/ largestNumber.cpp\n    ```\n\nThe comments would be generated by above examples as below:\n\n> **Notes**\n> If you need to customize the `Author` name, you have to change the `$AUTHOR` variable at the beginning of the scripts.\n\n```cpp\n// Source : https://oj.leetcode.com/problems/largest-number/\n// Author : Hao Chen\n// Date   : 2015-01-25\n\n/**********************************************************************************\n *\n * Given a list of non negative integers, arrange them such that they form the largest number.\n *\n * For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.\n *\n * Note: The result may be very large, so you need to return a string instead of an integer.\n *\n * Credits:Special thanks to @ts for adding this problem and creating all test cases.\n *\n **********************************************************************************/\n\n\n```\n\n## readme.sh\n\n`readme.sh` - it's used to generate the table item in README.md\n\nFor example:\n\n```sh\n$  ./readme.sh ../algorithms/cpp/nextPermutation/nextPermutation.cpp \n|31|[Next Permutation](https://oj.leetcode.com/problems/next-permutation/) | [C++](./algorithms/cpp/nextPermutation/nextPermutation.cpp)|Medium|\n```\n\n\n"
  },
  {
    "path": "scripts/comments.sh",
    "content": "#!/bin/bash\nset -e\n\nAUTHOR=\"NOBODY\"\nCOMMENT_TAG=\"//\"\nFILE_EXT=\".cpp\"\n\npushd `dirname $0` > /dev/null\nSCRIPT_PATH=`pwd -P`\npopd > /dev/null\nSCRIPT_FILE=`basename $0`\n\nCOLOR_INFO='\\033[0;36m'\nCOLOR_NONE='\\033[0m'\n\nsource ${SCRIPT_PATH}/lib/query_problem.sh\n\nfunction usage()\n{\n\n    echo -e \"Usage: ${0} [url] [source_file]\"\n    echo -e \"\"\n    echo -e \"Example:\"\n    echo -e \"\"\n    echo -e \"   1) Create a file named LargestNumber.cpp, and add Copyright & Problem description\"\n    echo -e \"   ${0} https://leetcode.com/problems/largest-number/\"\n    echo -e \"\"\n    echo -e \"   2) Add Copyright & Problem description into existed file\"\n    echo -e \"   ${0} https://leetcode.com/problems/largest-number/ LargestNumber.cpp\"\n    echo -e \"\"\n}\n\nfunction get_author_name()\n{\n    TRUE_CMD=`which true`\n    git=`type -P git || ${TRUE_CMD}`\n    if [ ! -z \"${git}\" ]; then\n       AUTHOR=`git config --get user.name`\n    else\n       AUTHOR=`whoami`\n    fi\n}\n\n\nfunction detect_os()\n{\n    platform='unknown'\n    ostype=`uname`\n    if [[ \"$ostype\" == 'Linux' ]]; then\n       platform='linux'\n    elif [[ \"$ostype\" == 'Darwin' ]]; then\n       platform='macos'\n    fi\n    echo ${platform}\n}\n\n\nif [ $# -lt 1 ] || [[ \"${1}\" != ${LEETCODE_NEW_URL}* ]] && [[ \"${1}\" != ${LEETCODE_OLD_URL}* ]]; then\n    usage\n    exit 255\nfi\n\nif [[ \"${1}\" == ${LEETCODE_OLD_URL}* ]]; then\n    LEETCODE_URL=${LEETCODE_OLD_URL}\nfi\n\n\nleetcode_url=$1\ncurrent_time=`date +%Y-%m-%d`\nplatform=`detect_os`\n\nget_question_slug ${leetcode_url}\n\n\nTRUE_CMD=`which true`\nJQ=`type -P jq || ${TRUE_CMD}`\nif [ -z \"${JQ}\" ]; then\n    echo \"jq command is not found !\"\n    install_jq\nfi\n\n#grab the problem information\nquery_problem ${leetcode_url} ${QUESTION_TITLE_SLUG}\n\nif [ \"${QUESTION_CATEGORY}\" == \"Shell\" ]; then\n    COMMENT_TAG='#'\n    FILE_EXT='.sh'\nfi\n\nif [ $# -gt 1 ] && [ -f $2 ]; then\n    source_file=$2\n    if [[ \"$platform\" == \"linux\" ]]; then\n        current_time=`stat -c %x ${source_file} | awk '{print \\$1}'`\n    elif [[ \"$platform\" == \"macos\" ]]; then\n        current_time=`stat -f %a ${source_file} | xargs -I time date -r time +%Y-%m-%d`\n    fi\nelse\n    source_file=$QUESTION_TITLE_SLUG\n    #source_file=${source_file::${#source_file}-1}\n    source_file=`echo $source_file | awk -F '-' '{for (i=1; i<=NF; i++) printf(\"%s\", toupper(substr($i,1,1)) substr($i,2)) }'`${FILE_EXT}\n\n    if [ ! -f ${source_file} ]; then\n        echo \"Create a new file - ${source_file}.\"\n        echo -e \"\\n\" > ${source_file}\n        current_time=`date +%Y-%m-%d`\n    else\n        if [[ \"$platform\" == \"linux\" ]]; then\n            current_time=`stat -c %x ${source_file} | awk '{print \\$1}'`\n        elif [[ \"$platform\" == \"macos\" ]]; then\n            current_time=`stat -f %a ${source_file} | xargs -I time date -r time +%Y-%m-%d`\n        fi\n    fi\nfi\n\n\n# the source file is existed but it is empty, add a line,\n# otherwise it could casue the comments inserts failed.\nif [ ! -s $source_file ]; then\n    echo \"\" > $source_file\nfi\n\n#detect the author name\nget_author_name;\n\n#adding the Copyright Comments\nif  ! grep -Fq  \"${COMMENT_TAG} Author :\" $source_file ; then\n    sed -i.bak '1i\\'$'\\n'\"${COMMENT_TAG} Source : ${leetcode_url}\"$'\\n' $source_file\n    sed -i.bak '2i\\'$'\\n'\"${COMMENT_TAG} Author : ${AUTHOR}\"$'\\n' $source_file\n    sed -i.bak '3i\\'$'\\n'\"${COMMENT_TAG} Date   : ${current_time}\"$'\\n' $source_file\n    sed -i.bak '4i\\'$'\\n'\"\"$'\\n' $source_file\n    rm ${source_file}.bak\nfi\n\n\n#echo \"--------------\"\n#echo \"$QUESTION_CONTENT\"\n#echo $QUESTION_DIFFICULTY\n#echo $QUESTION_TITLE\n#echo $QUESTION_ID\n#echo $QUESTION_CATEGORY\n#echo \"--------------\"\n\n\nfunction make_comments() {\n\n    # arguments - comment content, style and the outputfile\n    CONTENT=${1}\n    STYLE=${2}\n    OUTPUT_FILE=${3}\n\n    # the width of comments\n    WIDTH=100\n    WIDTH_SEQ=$(seq 1 ${WIDTH})\n\n    # 1) the `fold` command is used to wrap the text at centain column\n    # 2) the last two `sed` commands are used to add the comments tags\n    case ${STYLE} in\n        clike )     echo \"${CONTENT}\" |\n\t                sed 's/^[[:space:]]*$/'\"$(printf '\\n')\"'/g' | cat -s |         # replace the multiple empty line with a single empty line\n                        fold -w ${WIDTH} -s  |                                     # wrap the text at centain column\n                        sed 's/^/ * /'  |                                          # add the '*' for each line\n\t\t\tsed '1i\\'$'\\n'\"/*$(printf '%.0s*' ${WIDTH_SEQ}) \"$'\\n' |               # add the first line - /***********\n                        sed '2i\\'$'\\n'\"@@@*\"$'\\n' | sed 's/^@@@/ /g' |             # add the second line -  * (lead by a space)\n                        sed '$a\\'$'\\n'\"@@@*$(printf '%.0s*' ${WIDTH_SEQ})*/\"$'\\n'| # add the end line - **********/\n\t\t\tsed 's/^@@@/ /' > ${OUTPUT_FILE}\n                    ;;\n        script )    echo \"${CONTENT}\" |\n\t                sed 's/^[[:space:]]*$/'\"$(printf '\\n')\"'/g' | cat -s |         # replace the multiple empty line with a single empty line\n                        fold -w ${WIDTH} -s  |                                     # wrap the text at centain column\n                        sed 's/^/# /'  |                                           # add the '*' for each line\n\t\t\tsed '1i\\'$'\\n'\"#$(printf '%.0s#' ${WIDTH_SEQ}) \"$'\\n' |                # add the first line - ############\n                        sed '2i\\'$'\\n'\"#\"$'\\n' |                                   # add the second line - #\n                        sed '$a\\'$'\\n'\"#$(printf '%.0s#' ${WIDTH_SEQ})\"$'\\n' > ${OUTPUT_FILE} # add the end line - #############\n                    ;;\n          * )       echo \"Bad Comment Style!\"\n                    exit 1;\n    esac\n}\n\nTMP_FILE=/tmp/tmp.txt\ncase ${FILE_EXT} in\n     .c | .cpp | .java )\n         make_comments  \"${QUESTION_CONTENT}\" clike \"${TMP_FILE}\"\n         ;;\n    .sh | .py )\n         make_comments  \"${QUESTION_CONTENT}\" script \"${TMP_FILE}\"\n         ;;\n      * )\n         echo \"Bad file extension!\"\n         exit 1;\nesac\n\n#remove the ^M chars\ntr -d $'\\r' < ${TMP_FILE} > ${TMP_FILE}.1\nmv ${TMP_FILE}.1 ${TMP_FILE}\n\n#insert the problem description into the source file, and remove it\nsed -i.bak '4 r '${TMP_FILE}'' ${source_file}\nrm -f ${source_file}.bak\nrm -f /tmp/tmp.txt\n\necho \"${source_file} updated !\"\n\n"
  },
  {
    "path": "scripts/git.config.sh",
    "content": "#!/bin/bash\nset -e\n\ncase $1 in\n    -l) SCOPE=\"--local\"\n        ;;\n    -g) SCOPE=\"--global\"\n        ;;\n    *) SCOPE=\"--local\"\n        ;;\nesac\n\n\nOPTIONS=\"${SCOPE} --replace-all\"\nCMD=\"git config ${OPTIONS}\"\n\n${CMD} alias.lg0  \"log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --\"\n${CMD} alias.lg1  \"log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all\"\n${CMD} alias.lg2  \"log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all\"\n${CMD} alias.lg  !\"git lg0\"\n\n"
  },
  {
    "path": "scripts/lib/query_problem.sh",
    "content": "#!/bin/bash\n\nLEETCODE_URL=https://leetcode.com/problems/\nLEETCODE_NEW_URL=https://leetcode.com/problems/\nLEETCODE_OLD_URL=https://oj.leetcode.com/problems/\n\n\nfunction get_question_slug()\n{\n    QUESTION_TITLE_SLUG=${1#${LEETCODE_URL}}\n    QUESTION_TITLE_SLUG=$(echo $QUESTION_TITLE_SLUG | sed 's/\\/.*//g') # remove the needless url path\n}\n\nfunction query_problem_xidel()\n{\n    # xidel change the -q option to -s after 0.9.4 version, so we have to check that\n    # if xidel has -q option, then it will return error.\n\n    OPT=\n\n    set +e\n    xidel -q 2>/dev/null\n    if [ $? -ne 0 ]; then\n       OPT=-q\n    else\n       # if xidel has -s option, then it will return error.\n       xidel -s 2>/dev/null\n       if  [ $? -ne 0 ]; then\n           OPT=-s\n       fi\n    fi\n    set -e\n\n    QUESTION_CONTENT=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.content' | sed -e 's/<[^>]*>//g; s/&nbsp;/ /g; s/&amp;/\\&/g; s/&lt;/\\</g; s/&gt;/\\>/g; s/&quot;/\\\"/g; s/&#39;/\\'\"'\"'/g; s/&ldquo;/\\\"/g;')\n\n    QUESTION_DIFFICULTY=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.difficulty')\n\n    QUESTION_TITLE=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.title')\n\n    QUESTION_ID=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.questionId')\n\n    QUESTION_FRONTEND_ID=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.questionFrontendId')\n\n    #QUESTION_CATEGORY=$(xidel ${OPT} ${TMP_JSON_FILE} -e '$json(\"data\").question.categoryTitle')\n}\n\nfunction query_problem_jq()\n{\n    QUESTION_CONTENT=$(jq -r '.data.question.content' ${TMP_JSON_FILE} | sed -e 's/<sup>/\\^/g' | sed -e 's/<[^>]*>//g; s/&nbsp;/ /g; s/&amp;/\\&/g; s/&lt;/\\</g; s/&gt;/\\>/g; s/&quot;/\\\"/g; s/&#39;/\\'\"'\"'/g; s/&ldquo;/\\\"/g;')\n\n    QUESTION_DIFFICULTY=$(jq -r '.data.question.difficulty' ${TMP_JSON_FILE})\n\n    QUESTION_TITLE=$(jq -r '.data.question.title' ${TMP_JSON_FILE})\n\n    QUESTION_ID=$(jq -r '.data.question.questionId' ${TMP_JSON_FILE})\n\n    QUESTION_FRONTEND_ID=$(jq -r '.data.question.questionFrontendId' ${TMP_JSON_FILE})\n\n}\n\nfunction query_problem()\n{\n    TMP_JSON_FILE=tmp.json\n\n#    curl -s \"https://leetcode.com/graphql?query=query%20getQuestionDetail(%24titleSlug%3A%20String!)%20%7B%0A%20%20isCurrentUserAuthenticated%0A%20%20question(titleSlug%3A%20%24titleSlug)%20%7B%0A%20%20%20%20questionId%0A%20%20%20%20questionFrontendId%0A%20%20%20%20questionTitle%0A%20%20%20%20translatedTitle%0A%20%20%20%20questionTitleSlug%0A%20%20%20%20content%0A%20%20%20%20translatedContent%0A%20%20%20%20difficulty%0A%20%20%20%20stats%0A%20%20%20%20contributors%0A%20%20%20%20similarQuestions%0A%20%20%20%20discussUrl%0A%20%20%20%20mysqlSchemas%0A%20%20%20%20randomQuestionUrl%0A%20%20%20%20sessionId%0A%20%20%20%20categoryTitle%0A%20%20%20%20submitUrl%0A%20%20%20%20interpretUrl%0A%20%20%20%20codeDefinition%0A%20%20%20%20sampleTestCase%0A%20%20%20%20enableTestMode%0A%20%20%20%20metaData%0A%20%20%20%20enableRunCode%0A%20%20%20%20enableSubmit%0A%20%20%20%20judgerAvailable%0A%20%20%20%20infoVerified%0A%20%20%20%20envInfo%0A%20%20%20%20urlManager%0A%20%20%20%20article%0A%20%20%20%20questionDetailUrl%0A%20%20%20%20discussCategoryId%0A%20%20%20%20discussSolutionCategoryId%0A%20%20%20%20libraryUrl%0A%20%20%20%20companyTags%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20slug%0A%20%20%20%20%20%20translatedName%0A%20%20%20%20%7D%0A%20%20%20%20topicTags%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20slug%0A%20%20%20%20%20%20translatedName%0A%20%20%20%20%7D%0A%20%20%7D%0A%20%20interviewed%20%7B%0A%20%20%20%20interviewedUrl%0A%20%20%20%20companies%20%7B%0A%20%20%20%20%20%20id%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20slug%0A%20%20%20%20%7D%0A%20%20%20%20timeOptions%20%7B%0A%20%20%20%20%20%20id%0A%20%20%20%20%20%20name%0A%20%20%20%20%7D%0A%20%20%20%20stageOptions%20%7B%0A%20%20%20%20%20%20id%0A%20%20%20%20%20%20name%0A%20%20%20%20%7D%0A%20%20%7D%0A%20%20subscribeUrl%0A%20%20isPremium%0A%20%20loginUrl%0A%7D%0A&operationName=getQuestionDetail&variables=%7B%22titleSlug%22%3A%22${2}%22%7D\" > ${TMP_JSON_FILE}\n\n    #\n    # NOTE: leetcode server supports `br` encoding and make it high priority. But curl doesn't support it,\n    #       So, you need make sure the `accept-encoding` hasn't br in the request header.\n    #       (if you copy & paste the curl script from Chrome, the `br` could be added!)\n    #\n    curl -s 'https://leetcode.com/graphql' \\\n    -H 'origin: https://leetcode.com' \\\n    -H 'accept-encoding: gzip, deflate' \\\n    -H 'accept-language: zh-CN,zh;q=0.9,und;q=0.8,en;q=0.7' \\\n    -H 'cookie: __cfduid=dae082e425ee3916c04a5170b832e268e1524142659; _ga=GA1.2.1432146910.1524142661; _gid=GA1.2.650843898.1529736240; csrftoken=iSKedVXxGDkBBXbP9chsyXhbIrRedF7iw2EMRZiemtzKD8vjHSWZJKkKQVIwZKp7; __atuvc=2%7C25; __atuvs=5b2ded02313c83c4001; _gat=1' \\\n    -H 'x-csrftoken: iSKedVXxGDkBBXbP9chsyXhbIrRedF7iw2EMRZiemtzKD8vjHSWZJKkKQVIwZKp7' \\\n    -H 'pragma: no-cache' \\\n    -H 'content-type: application/json' \\\n    -H 'accept: */*' -H 'cache-control: no-cache' \\\n    -H 'authority: leetcode.com' \\\n     -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36' \\\n    -H \"referer: ${1}\" \\\n    --data-binary '{\"operationName\":\"questionData\",\"variables\":{\"titleSlug\":\"'${2}'\"},\"query\":\"query questionData($titleSlug: String!) {\\n  question(titleSlug: $titleSlug) {\\n    questionId\\n    questionFrontendId\\n    boundTopicId\\n    title\\n    titleSlug\\n    content\\n    translatedTitle\\n    translatedContent\\n    isPaidOnly\\n    difficulty\\n    likes\\n    dislikes\\n    isLiked\\n    similarQuestions\\n    contributors {\\n      username\\n      profileUrl\\n      avatarUrl\\n      __typename\\n    }\\n    langToValidPlayground\\n    topicTags {\\n      name\\n      slug\\n      translatedName\\n      __typename\\n    }\\n    companyTagStats\\n    codeSnippets {\\n      lang\\n      langSlug\\n      code\\n      __typename\\n    }\\n    stats\\n    hints\\n    solution {\\n      id\\n      canSeeDetail\\n      __typename\\n    }\\n    status\\n    sampleTestCase\\n    metaData\\n    judgerAvailable\\n    judgeType\\n    mysqlSchemas\\n    enableRunCode\\n    enableTestMode\\n    envInfo\\n    __typename\\n  }\\n}\\n\"}' --compressed > ${TMP_JSON_FILE}\n\n    query_problem_jq\n\n    rm -f ${TMP_JSON_FILE}\n}\n\nfunction detect_os()\n{\n    platform='unknown'\n    ostype=`uname`\n    if [[ \"$ostype\" == 'Linux' ]]; then\n       platform='linux'\n    elif [[ \"$ostype\" == 'Darwin' ]]; then\n       platform='macos'\n    fi\n    echo ${platform}\n}\n\nfunction install_brew()\n{\n    TRUE_CMD=`which true`\n    brew=`type -P brew || ${TRUE_CMD}`\n    if [ -z \"${brew}\" ]; then\n        echo \"brew not found !\"\n        /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)\"\n    fi\n}\n\n\nfunction manually_install_jq() {\n    echo \"Unknown platform, please install 'jq' manually!\"\n    echo \"Dowload Site: https://stedolan.github.io/jq/download/\"\n}\nfunction install_jq()\n{\n    echo \"Install jq ...\"\n\n    platform=`detect_os`\n\n    if [[ \"$platform\" == \"unknown\" ]]; then\n        manually_install_jq\n        exit 1;\n    fi\n\n    if [[ \"$platform\" == \"linux\" ]]; then\n        OS_RELEASE=\"/etc/os-release\"\n        if [ ! -f ${OS_RELEASE} ]; then\n            manually_install_jq\n            exit 1;\n        fi\n        DISTRO=`awk -F= '/^NAME/{print $2}' `\n        DISTRO=\"CentOS Linux\"\n        case $DISTRO in\n            Ubuntu* ) sudo apt-get install jq\n                     ;;\n            CentOS* ) echo sudo yum install jq\n                     ;;\n                 * ) manually_install_jq\n                     exit 1;\n        esac\n    fi\n\n    if [[ \"$platform\" == \"macos\" ]]; then\n        install_brew\n        echo \"brew install jq...\"\n        brew install jq\n    fi\n\n    echo \"Install jq successfullly !\"\n}\n\nfunction install_xidel()\n{\n    echo \"Install xidel ...\"\n    if [ ! -d ./xidel ]; then\n        mkdir xidel\n    fi\n    cd xidel\n\n    platform=`detect_os`\n\n    if [[ \"$platform\" == \"unknown\" ]]; then\n        echo \"Unknown platform, please install 'xidel' manually!\"\n        exit 1;\n    fi\n\n    #install the xidel on Linux platform\n    xidel_ver=0.9.8\n    if [[ \"$platform\" == \"linux\" ]]; then\n        hardware=`uname -m`\n        xidel_tar=xidel-${xidel_ver}.linux64.tar.gz\n        case $hardware in\n            x86_64 )    xidel_tar=xidel-${xidel_ver}.linux64.tar.gz\n                        ;;\n              i686 )    xidel_tar=xidel-${xidel_ver}.linux32.tar.gz\n                        ;;\n                 * )    echo \"Cannot install xidel, please install it manually!\"\n                        exit 1;\n        esac\n        if [ ! -f ${xidel_tar} ]; then\n            echo \"Downloading xidel......\"\n            curl -# -L https://github.com/benibela/xidel/releases/download/Xidel_${xidel_ver}/${xidel_tar} -o ${xidel_tar}\n        fi\n        tar -zxvf ${xidel_tar}\n        sudo ./install.sh\n    fi\n\n    #install the xidel on MacOS platform\n    #refer to: https://www.evernote.com/shard/s69/sh/ff1e78f3-a369-4855-b18f-6184ce789c45/f3511927d0fb356ce883835f2eb712e0\n    if [[ \"$platform\" == \"macos\" ]]; then\n        install_brew\n        echo \"brew install xidel...\"\n        brew install xidel\n    fi\n\n    cd ..\n    echo \"Install xidel successfullly !\"\n}\n"
  },
  {
    "path": "scripts/readme.sh",
    "content": "#!/bin/bash\n\npushd `dirname $0` > /dev/null\nSCRIPT_PATH=`pwd -P`\npopd > /dev/null\nSCRIPT_FILE=`basename $0`\n\nCOLOR_INFO='\\033[0;36m'\nCOLOR_NONE='\\033[0m'\n\nsource ${SCRIPT_PATH}/lib/query_problem.sh\n\nfunction usage()\n{\n\n    echo -e \"Usage: ${0} [file]\"\n    echo -e \"\"\n    echo -e \"Example:\"\n    echo -e \"\"\n    echo -e \"   ${0} ./LargestNumber.cpp\"\n    echo -e \"\"\n}\n\n\n\nif [ $# -lt 1 ] || [[ ! -f ${1} ]]; then\n    usage\n    exit 255\nfi\n\nDIR=`cd $(dirname ${1}) && pwd -P`\nFILE=${DIR}/$(basename ${1})\n\nURL=`grep Source ${FILE} | awk '{print $4}'`\n\nURL=$(echo $URL | sed -e 's/oj\\.leetcode\\.com/leetcode\\.com/g')\n\nget_question_slug ${URL}\nquery_problem ${URL} ${QUESTION_TITLE_SLUG}\n\n#echo \"$QUESTION_CONTENT\"\n#echo $QUESTION_DIFFICULTY\n#echo $QUESTION_TITLE\n#echo $QUESTION_ID\n#echo $QUESTION_FRONTEND_ID\n#echo $QUESTION_CATEGORY\n\n\nFILE=`echo ${FILE} | sed \"s/.*\\/algorithms/\\.\\/algorithms/\"`\n\necho \"|${QUESTION_FRONTEND_ID}|[${QUESTION_TITLE}](${URL}) | [C++](${FILE})|${QUESTION_DIFFICULTY}|\"\n\n"
  },
  {
    "path": "scripts/workflow.sh",
    "content": "#!/bin/bash\nset -e\n\npushd `dirname $0` > /dev/null\nSCRIPT_PATH=`pwd -P`\npopd > /dev/null\nSCRIPT_FILE=`basename $0`\n\nCOLOR_INFO='\\033[0;36m'\nCOLOR_NONE='\\033[0m'\n\nsource ${SCRIPT_PATH}/lib/query_problem.sh\n\nfunction usage()\n{\n\n    echo -e \"Usage: ${0} [url]\"\n    echo -e \"\"\n    echo -e \"Example:\"\n    echo -e \"\"\n    echo -e \"   Running workflow for a problem\"\n    echo -e \"   ${0} https://leetcode.com/problems/largest-number/\"\n    echo -e \"\"\n}\n\nfunction git_commit(){\n    TITLE=$1\n    FILE1=$2\n    FILE2=$3\n    git commit -m \"New Problem Solution - \\\"${TITLE}\\\"\"  \"${FILE1}\" \"${FILE2}\"\n}\n\nif [ $# -lt 1 ] || [[ \"${1}\" != ${LEETCODE_NEW_URL}* ]] && [[ \"${1}\" != ${LEETCODE_OLD_URL}* ]]; then\n    usage\n    exit 255\nfi\n\nif [[ \"${1}\" == ${LEETCODE_OLD_URL}* ]]; then\n    LEETCODE_URL=${LEETCODE_OLD_URL}\nfi\n\nplatform=`detect_os`\nleetcode_url=$1\n\nget_question_slug ${leetcode_url}\ndir_name=`echo ${QUESTION_TITLE_SLUG} | awk -F '-' '{for (i=1; i<=NF; i++) printf(\"%s\", toupper(substr($i,1,1)) substr($i,2)) }'`\ndir_name=`echo ${dir_name:0:1} | tr '[A-Z]' '[a-z]'`${dir_name:1}\n\nmkdir -p ${dir_name}\necho \"Step 1 : Created \\\"${dir_name}\\\" directory!\"\ncd ${dir_name}\n\nfile=`${SCRIPT_PATH}/comments.sh ${leetcode_url} | grep updated | awk '{print $1}'`\nWORKING_DIR=`pwd`\nSRC=\"${dir_name}/${file}\"\nSRC_FILE=\"${WORKING_DIR}/${file}\"\nREADME_FILE=\"${SCRIPT_PATH}/../README.md\"\n\necho \"Step 2 : Created \\\"${SRC}\\\" source file!\"\n\necho \"Step 3 : Run \\\"git add ${SRC}\\\"!\"\ngit add ${SRC_FILE}\n\nvi \"${SRC_FILE}\"\necho \"Step 4 : Edited the \\\"${SRC}\\\"!\"\nreadme=`${SCRIPT_PATH}/readme.sh ${file}`\nreadme=`echo \"${readme}\" | head -n 1`\n\nif [[ \"$platform\" == \"macos\" ]]; then\n    echo $readme | pbcopy\nelse\n    echo $readme\n    read -n 1 -s -r -p  \"Please copy the line above & press any key continue to edit README.md\"\nfi\necho \"Step 5 : Copied the readme text to Clipboard!\"\nvi ${README_FILE}\n\necho \"Step 6 : Edited the \\\"README.md\\\"!\"\n\nQUESTION_FRONTEND_ID=`echo \"${readme}\" | awk -F '|' '{print $2}'`\nQUESTION_DIFFICULTY=`echo \"${readme}\" | awk -F '|' '{print $5}'`\nQUESTION_TITLE=`echo \"${readme}\" | awk -F '|' '{print $3}' | sed 's/\\[/\\]/' |awk -F ']' '{print $2}'`\ncommit=\"git commit -m \\\"New Problem Solution - \\\\\\\"${QUESTION_FRONTEND_ID}. ${QUESTION_TITLE}\\\\\\\"\\\"\"\n\necho \"Step 7 : It's ready to commit to git repository ...\"\necho \"\"\necho \"      ${commit} \\\\\"\necho \"          ${SRC_FILE} \\\\\"\necho \"          ${README_FILE}\"\necho \"\"\n\n#git status\n\ncommit=\"${commit} \\\"${WORKING_DIR}/${file}\\\" \\\"${SCRIPT_PATH}/../README.md\\\"\"\n\nwhile true; do\n    read -p \"Do you wish to commit them (y/n) ? \" yn\n    case $yn in\n        [Yy]* ) git_commit \"${QUESTION_FRONTEND_ID}. ${QUESTION_TITLE}\" \"${SRC_FILE}\" \"${README_FILE}\" ; break;;\n        [Nn]* ) exit;;\n        * ) echo \"Please answer yes or no.\";;\n    esac\ndone\n\necho \"Done!\""
  },
  {
    "path": "shell/README.md",
    "content": "###LeetCode Shell\n\n\n| # | Title | Solution | Difficulty |\n|---| ----- | -------- | ---------- |\n|4|[Tenth Line](https://leetcode.com/problems/tenth-line/)| [Bash](./TenthLine.sh)|Easy|\n|3|[Transpose File](https://leetcode.com/problems/transpose-file/)| [Bash](./TransposeFile.sh)|Medium|\n|2|[Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/)| [Bash](./ValidPhoneNumbers.sh)|Easy|\n|1|[Word Frequency](https://leetcode.com/problems/word-frequency/)| [Bash](./WordFrequency.sh)|Medium|\n"
  },
  {
    "path": "shell/TenthLine.sh",
    "content": "# Source : https://leetcode.com/problems/tenth-line/\n# Author : Hao Chen\n# Date   : 2015-03-31\n\n################################################################################## \n# \n# How would you print just the 10th line of a file?\n# \n# For example, assume that file.txt has the following content:\n# \n# Line 1\n# Line 2\n# Line 3\n# Line 4\n# Line 5\n# Line 6\n# Line 7\n# Line 8\n# Line 9\n# Line 10\n# \n# Your script should output the tenth line, which is:\n# \n# Line 10\n# \n# [show hint]\n# Hint:\n# 1. If the file contains less than 10 lines, what should you output?\n# 2. There's at least three different solutions. Try to explore all possibilities.\n##################################################################################\n\n#!/bin/sh\n\n\n# Read from the file file.txt and output the tenth line to stdout.\n\n# Solution One\nawk 'NR==10{print $0}' file.txt\n\n# Solution Two\nsed -n '10p' file.txt\n\n"
  },
  {
    "path": "shell/TransposeFile.sh",
    "content": "# Source : https://leetcode.com/problems/transpose-file/\n# Author : Hao Chen\n# Date   : 2015-03-31\n\n################################################################################## \n# \n# Given a text file file.txt, transpose its content.\n# \n# You may assume that each row has the same number of columns and each field is separated by the ' ' character.\n# \n# For example, if file.txt has the following content:\n# \n# name age\n# alice 21\n# ryan 30\n# \n# Output the following:\n# \n# name alice ryan\n# age 21 30\n##################################################################################\n\n#!/bin/sh\n\n# Read from the file file.txt and print its transposed content to stdout.\nawk '\n{\n    for (i = 1; i <= NF; i++) {\n        if (NR == 1){\n            s[i]=$i;\n        }else{\n            s[i] = s[i] \" \" $i;\n        }\n    }\n}\nEND {\n    for (i = 1; s[i] != \"\"; i++) {\n        print s[i];\n    }\n}' file.txt\n\n\n\n"
  },
  {
    "path": "shell/ValidPhoneNumbers.sh",
    "content": "# Source : https://leetcode.com/problems/valid-phone-numbers/\n# Author : Hao Chen\n# Date   : 2015-03-31\n\n################################################################################## \n# \n# Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.\n# \n# You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)\n# \n# You may also assume each line in the text file must not contain leading or trailing white spaces.\n# \n# For example, assume that file.txt has the following content:\n# \n# 987-123-4567\n# 123 456 7890\n# (123) 456-7890\n# \n# Your script should output the following valid phone numbers:\n# \n# 987-123-4567\n# (123) 456-7890\n##################################################################################\n\n#!/bin/sh\n\n\n# Read from the file file.txt and output all valid phone numbers to stdout.\ngrep -P '^(\\d{3}-|\\(\\d{3}\\) )\\d{3}-\\d{4}$' file.txt\n\n"
  },
  {
    "path": "shell/WordFrequency.sh",
    "content": "# Source : https://leetcode.com/problems/word-frequency/\n# Author : Hao Chen\n# Date   : 2015-03-31\n\n################################################################################## \n# \n# Write a bash script to calculate the frequency of each word in a text file words.txt.\n# \n# For simplicity sake, you may assume:\n# \n# words.txt contains only lowercase characters and space ' ' characters.\n# Each word must consist of lowercase characters only.\n# Words are separated by one or more whitespace characters.\n# \n# For example, assume that words.txt has the following content:\n# the day is sunny the the\n# the sunny is is\n# \n# Your script should output the following, sorted by descending frequency:\n# \n# the 4\n# is 3\n# sunny 2\n# day 1\n# \n# Note:\n# Don't worry about handling ties, it is guaranteed that each word's frequency count is unique.\n# \n# [show hint]\n# Hint:\n# Could you write it in one-line using Unix pipes?\n##################################################################################\n\n#!/bin/sh\n\n# Read from the file words.txt and output the word frequency list to stdout.\ncat words.txt | tr [:space:] \"\\n\" | sed '/^$/d' | tr '[:upper:]' '[:lower:]'|sort|uniq -c|sort -nr | awk '{ print $2,$1}'\n\n"
  }
]