├── .gitignore ├── algorithms ├── java │ ├── junit-4.7.jar │ ├── src │ │ ├── maximumDepthOfBinaryTree │ │ │ ├── TreeNode.java │ │ │ ├── maximumDepthOfBinaryTreeTest.java │ │ │ └── maximumDepthOfBinaryTree.java │ │ ├── lowestCommonAncestorOfABinaryTree │ │ │ ├── TreeNode.java │ │ │ └── lowestCommonAncestorOfABinaryTreeTest.java │ │ ├── binaryTreeBFSTraversal │ │ │ ├── TreeNode.java │ │ │ └── binaryTreeBFSTraversal.java │ │ ├── inorderSuccessorInBST │ │ │ ├── TreeNode.java │ │ │ └── inorderSuccessorInBSTTest.java │ │ ├── binaryTreeMaximumPathSum │ │ │ └── TreeNode.java │ │ ├── binaryTreePreorderTraversal │ │ │ ├── TreeNode.java │ │ │ └── binaryTreePreorderTraversal.java │ │ ├── binaryTreeLevelOrderTraversal │ │ │ └── TreeNode.java │ │ ├── searchRangeInBinarySearchTree │ │ │ ├── TreeNode.java │ │ │ └── searchRangeInBinarySearchTreeTest.java │ │ ├── validateBinarySearchTree │ │ │ └── TreeNode.java │ │ ├── balancedBinaryTree │ │ │ ├── TreeNode.java │ │ │ └── balancedBinaryTreeTest.java │ │ ├── binarySearchTreeIterator │ │ │ ├── TreeNode.java │ │ │ └── binarySearchTreeIteratorTest.java │ │ ├── firstBadVersion │ │ │ ├── VersionControl.java │ │ │ ├── firstBadVersionTest.java │ │ │ └── firstBadVersion.java │ │ ├── validAnagram │ │ │ ├── TestValidAnagram.java │ │ │ └── ValidAnagram.java │ │ ├── countAndSay │ │ │ └── TestCountAndSay.java │ │ ├── powXn │ │ │ └── TestPowXn.java │ │ ├── minStack │ │ │ └── TestMinStack.java │ │ ├── validPalindrome │ │ │ └── TestValidPalindrome.java │ │ ├── reverseWordsInAString │ │ │ ├── TestReverseWordsInAString.java │ │ │ └── ReverseWordsInAString.java │ │ ├── lengthOfLastWord │ │ │ ├── TestLengthOfLastWord.java │ │ │ └── LengthOfLastWord.java │ │ ├── myStack │ │ │ └── TestMyStack.java │ │ ├── palindromeNumber │ │ │ ├── TestPalindromeNumber.java │ │ │ └── PalindromeNumber.java │ │ ├── searchA2DMatrixII │ │ │ └── Test_240.java │ │ ├── myQueue │ │ │ └── TestMyQueue.java │ │ ├── dynamicProgramming │ │ │ ├── climbStairs │ │ │ │ ├── climbStairsTest.java │ │ │ │ └── climbStairs.java │ │ │ ├── uniquePaths │ │ │ │ ├── uniquePathsTest.java │ │ │ │ └── uniquePathsIITest.java │ │ │ ├── minimumPathSum │ │ │ │ ├── minimumPathSumTest.java │ │ │ │ └── minimumPathSum.java │ │ │ └── triangle │ │ │ │ └── triangleTest.java │ │ ├── strStr │ │ │ ├── strStrTest.java │ │ │ ├── TestStrStrKmp.java │ │ │ └── strStr.java │ │ ├── rotateArray │ │ │ └── TestRotateArray.java │ │ ├── reverseLinkedList │ │ │ ├── TestReverseLinkedList.java │ │ │ ├── ListNode.java │ │ │ └── ReverseLinkedList.java │ │ ├── searchForRange │ │ │ └── searchForRangeTest.java │ │ ├── findPeakElement │ │ │ └── findPeakElementTest.java │ │ ├── reverseLinkedListII │ │ │ ├── TestReverseLinkedListII.java │ │ │ ├── ListNode.java │ │ │ └── ReverseLinkedListII.java │ │ ├── searchInsertPosition │ │ │ └── searchInsertPositionTest.java │ │ ├── search2DMatrix │ │ │ └── search2DMatrixTest.java │ │ ├── findMinimumInRotatedSortedArray │ │ │ ├── findMinimumInRotatedSortedArrayTest.java │ │ │ └── findMinimumInRotatedSortedArray.java │ │ ├── removeDuplicatesFromSortedArray │ │ │ ├── TestRemoveDuplicates.java │ │ │ └── RemoveDuplicatesFromSortedArray.java │ │ ├── searchInRotatedSortedArray │ │ │ └── searchInRotatedSortedArrayTest.java │ │ ├── searchInABigSortedArray │ │ │ └── searchInABigSortedArrayTest.java │ │ └── lruCache │ │ │ ├── LRUCacheTest.java │ │ │ └── LRUCache.java │ └── algorithms-java.iml ├── python │ ├── SquaresOfSortedArray │ │ └── sortedSquares.py │ ├── HouseRobber │ │ └── rob.py │ ├── LargestNumberAtLeastTwiceOfOthers │ │ └── dominantIndex.py │ ├── MinCostClimbingStairs │ │ └── minCostClimbingStairs.py │ ├── ShortestUnsortedContinuousSubarray │ │ └── findUnsortedSubarray.py │ ├── K-diffPairsInAnArray │ │ └── findPairs.py │ ├── LargestPerimeterTriangle │ │ └── largestPerimeter.py │ ├── UniqueBinarySearchTrees │ │ └── numTrees.py │ ├── LowestCommonAncestorOfABinaryTree │ │ └── lowestCommonAncestor.py │ ├── RevealCardsInIncreasingOrder │ │ └── deckRevealedIncreasing.py │ ├── BinaryTreeTilt │ │ └── findTilt.py │ ├── DifferentWaysToAddParentheses │ │ └── diffWaysToCompute.py │ ├── RemoveNthNodeFromEndOfList │ │ └── removeNthFromEnd.py │ ├── ConstructBinaryTreeFromPreorderAndInorderTraversal │ │ └── buildTree.py │ ├── Subsets │ │ └── subsets.py │ ├── ConstructBinaryTreeFromInorderAndPostorderTraversal │ │ └── buildTree.py │ ├── DiameterOfBinaryTree │ │ └── diameterOfBinaryTree.py │ ├── 1-bitAnd2-bitCharacters │ │ └── isOneBitCharacter.py │ ├── FlattenBinaryTreeToLinkedList │ │ └── flatten.py │ ├── LongestContinuousIncreasingSubsequence │ │ └── findLengthOfLCIS.py │ ├── CountCompleteTreeNodes │ │ └── countNodes.py │ ├── Non-decreasingArray │ │ └── checkPossibility.py │ ├── PopulatingNextRightPointersInEachNode │ │ └── connect.py │ ├── PartitionList │ │ └── partition.py │ ├── PopulatingNextRightPointersInEachNodeII │ │ └── connect.py │ ├── LinkedListCycleII │ │ └── detectCycle.py │ ├── FindTheDuplicateNumber │ │ └── findDuplicate.py │ ├── LowestCommonAncestorOfABinarySearchTree │ │ └── lowestCommonAncestor.py │ ├── PositionsOfLargeGroups │ │ └── largeGroupPositions.py │ ├── LongestTurbulentSubarray │ │ └── maxTurbulenceSize.py │ ├── ReverseLinkedListII │ │ └── reverseBetween.py │ ├── FindDuplicateSubtrees │ │ └── findDuplicateSubtrees.py │ ├── ThirdMaximumNumber │ │ └── thirdMax.py │ ├── AddOneRowToTree │ │ └── addOneRow.py │ ├── MaximumProductOfThreeNumbers │ │ └── maximumProduct.py │ ├── ContainsDuplicateIII │ │ └── containsNearbyAlmostDuplicate.py │ ├── SumOfLeftLeaves │ │ └── sumOfLeftLeaves.py │ ├── ImageSmoother │ │ └── imageSmoother.py │ ├── RemoveDuplicatesFromSortedListII │ │ └── deleteDuplicates.py │ ├── InsertionSortList │ │ └── insertionSortList.py │ ├── LongestUnivaluePath │ │ └── longestUnivaluePath.py │ ├── FlipBinaryTreeToMatchPreorderTraversal │ │ └── flipMatchVoyage.py │ ├── MaximizeDistanceToClosestPerson │ │ └── maxDistToClosest.py │ ├── MaximumWidthOfBinaryTree │ │ └── widthOfBinaryTree.py │ ├── ConvertBSTtoGreaterTree │ │ └── convertBST.py │ ├── PathSumIII │ │ └── pathSum.py │ ├── BinaryTreeZigzagLevelOrderTraversal │ │ └── zigzagLevelOrder.py │ ├── SubtreeOfAnotherTree │ │ └── isSubtree.py │ ├── CheckCompletenessOfABinaryTree │ │ └── isCompleteTree.py │ ├── FibonacciNumber │ │ └── fib.py │ ├── MaximumAverageSubarrayI │ │ └── findMaxAverage.py │ ├── ContainsDuplicateII │ │ └── containsNearbyDuplicate.py │ ├── KthSmallestElementInABST │ │ └── kthSmallest.py │ ├── XOfAKindInADeckOfCards │ │ └── hasGroupsSizeX.py │ ├── ValidMountainArray │ │ └── validMountainArray.py │ ├── PancakeSorting │ │ └── pancakeSort.py │ ├── ReorderList │ │ └── reorderList.py │ ├── UniqueBinarySearchTreesII │ │ └── generateTrees.py │ ├── PrintBinaryTree │ │ └── printTree.py │ ├── SecondMinimumNodeInABinaryTree │ │ └── findSecondMinimumValue.py │ ├── NumberOfIslands │ │ └── numIslands.py │ ├── PathSumII │ │ └── pathSum.py │ ├── SerializeAndDeserializeBST │ │ └── serialize.py │ ├── SumRootToLeafNumbers │ │ └── sumNumbers.py │ ├── ValidateBinarySearchTree │ │ └── isValidBST.py │ ├── HappyNumber │ │ └── isHappy.py │ ├── RedundantConnection │ │ └── findRedundantConnection.py │ ├── BinaryTreePostorderTraversal │ │ └── postorderTraversal.py │ ├── SortList │ │ └── sortList.py │ ├── BinarySearchTreeIterator │ │ └── BSTIterator.py │ ├── HouseRobberIII │ │ └── rob.py │ ├── DeleteNodeInABST │ │ └── deleteNode.py │ ├── SearchA2DMatrixII │ │ └── searchMatrix.py │ └── CopyListWithRandomPointer │ │ └── copyRandomList.py └── cpp │ ├── sentenceScreenFitting │ ├── sentenceScreenFitting.h │ └── main.cpp │ ├── reverseString │ └── ReverseString.cpp │ ├── courseSchedule │ └── non-recursive │ │ └── main.cpp │ ├── containsDuplicate │ ├── ContainsDuplicate.cpp │ ├── ContainsDuplicate.II.cpp │ └── ContainsDuplicate.III.cpp │ ├── numberOf1Bits │ └── numberOf1Bits.cpp │ ├── climbStairs │ └── climbStairs.cpp │ ├── singleNumber │ └── singleNumber.cpp │ ├── h-Index │ └── h-Index.II.cpp │ ├── findTheDifference │ └── FindTheDifference.cpp │ ├── reverseBits │ └── reverseBits.cpp │ ├── removeDuplicatesFromSortedArray │ └── removeDuplicatesFromSortedArray.cpp │ ├── deleteNodeInALinkedList │ └── DeleteNodeInALinkedList.cpp │ ├── removeElement │ └── removeElement.cpp │ ├── sumOfTwoIntegers │ └── SumOfTwoIntegers.cpp │ ├── powerOfFour │ └── PowerOfFour.cpp │ ├── integerToRoman │ └── integerToRoman.cpp │ ├── uglyNumber │ └── UglyNumber.cpp │ ├── longestCommonPrefix │ └── longestCommonPrefix.cpp │ ├── pascalTriangle │ └── pascalTriangle.II.cpp │ ├── eliminationGame │ └── EliminationGame.cpp │ ├── jumpGame │ └── jumpGame.cpp │ ├── minimumDepthOfBinaryTree │ └── minimumDepthOfBinaryTree.cpp │ ├── removeLinkedListElements │ └── RemoveLinkedListElements.cpp │ ├── powerOfTwo │ └── PowerOfTwo.cpp │ ├── plusOne │ └── plusOne.cpp │ ├── validPalindrome │ └── validPalindrome.cpp │ ├── maximumAverageSubarray │ └── MaximumAverageSubarray.I.cpp │ ├── fibonacciNumber │ └── FibonacciNumber.cpp │ ├── twoSum │ ├── twoSum.III.cpp │ └── twoSum.II.cpp │ ├── ransomNote │ └── RansomNote.cpp │ ├── addBinary │ └── addBinary.cpp │ ├── sortArrayByParity │ ├── SortArrayByParity.cpp │ └── SortArrayByParity.II.cpp │ ├── productOfArrayExceptSelf │ └── ProductOfArrayExceptSelf.cpp │ ├── jewelsAndStones │ └── JewelsAndStones.cpp │ ├── maximumDepthOfBinaryTree │ └── maximumDepthOfBinaryTree.cpp │ ├── longestPalindrome │ └── LongestPalindrome.cpp │ ├── sqrt │ └── sqrt.cpp │ ├── reverseLinkedList │ └── reverseLinkedList.cpp │ ├── rotateList │ └── rotateList.cpp │ ├── thirdMaximumNumber │ └── ThirdMaximumNumber.cpp │ ├── validParentheses │ └── validParentheses.cpp │ ├── largestNumber │ └── largestNumber.cpp │ ├── lengthOfLastWord │ └── lengthOfLastWord.cpp │ ├── searchInsertPosition │ └── searchInsertPosition.cpp │ ├── gasStation │ └── gasStation.cpp │ ├── removeNthNodeFromEndOfList │ └── removeNthNodeFromEndOfList.cpp │ ├── palindromeLinkedList │ └── PalindromeLinkedList.cpp │ ├── integerBreak │ └── IntegerBreak.cpp │ ├── palindromicSubstrings │ └── PalindromicSubstrings.cpp │ ├── addStrings │ └── AddStrings.cpp │ ├── convertSortedArrayToBinarySearchTree │ └── convertSortedArrayToBinarySearchTree.cpp │ ├── generateParentheses │ └── generateParentheses.cpp │ ├── convertANumberToHexadecimal │ └── ConvertANumberToHexadecimal.cpp │ ├── isSubsequence │ └── IsSubsequence.cpp │ ├── rangeSumQuery-Immutable │ └── rangeSumQuery-Immutable.cpp │ ├── zigZagConversion │ └── zigZagConversion.cpp │ ├── firstBadVersion │ └── FirstBadVersion.cpp │ └── isomorphicStrings │ └── IsomorphicStrings.cpp ├── database ├── README.md └── TripsAndUsers.sql ├── .gitconfig ├── shell ├── README.md ├── TenthLine.sh ├── TransposeFile.sh ├── ValidPhoneNumbers.sh └── WordFrequency.sh └── scripts └── readme.sh /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | algorithms-java/out 3 | *.class 4 | -------------------------------------------------------------------------------- /algorithms/java/junit-4.7.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awesome-interview/leetcode/master/algorithms/java/junit-4.7.jar -------------------------------------------------------------------------------- /algorithms/python/SquaresOfSortedArray/sortedSquares.py: -------------------------------------------------------------------------------- 1 | def sortedSquares(self, A): 2 | return list(sorted([a ** 2 for a in A])) -------------------------------------------------------------------------------- /algorithms/python/HouseRobber/rob.py: -------------------------------------------------------------------------------- 1 | def rob(self, nums): 2 | temp = [0, 0] 3 | for n in nums: 4 | temp[0], temp[1] = max(temp), n + temp[0] 5 | 6 | return max(temp) -------------------------------------------------------------------------------- /algorithms/java/src/maximumDepthOfBinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package maximumDepthOfBinaryTree; 2 | 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | TreeNode(int x) { val = x; } 8 | } 9 | -------------------------------------------------------------------------------- /database/README.md: -------------------------------------------------------------------------------- 1 | ### LeetCode Database 2 | 3 | 4 | | # | Title | Solution | Difficulty | 5 | |---| ----- | -------- | ---------- | 6 | |1|[Trips and Users](https://leetcode.com/problems/trips-and-users/)| [MySQL](./TripsAndUsers.sql)|Hard| 7 | -------------------------------------------------------------------------------- /algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py: -------------------------------------------------------------------------------- 1 | def dominantIndex(self, nums): 2 | i = nums.index(max(nums)) 3 | l = nums[i] 4 | del nums[i] 5 | if not nums: return 0 6 | return i if l >= 2 * max(nums) else -1 -------------------------------------------------------------------------------- /algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py: -------------------------------------------------------------------------------- 1 | def minCostClimbingStairs(self, cost): 2 | temp = [0, cost[0]] 3 | for i in range(1, len(cost)): 4 | temp[0], temp[1] = temp[1], min(temp) + cost[i] 5 | return min(temp) -------------------------------------------------------------------------------- /algorithms/java/src/lowestCommonAncestorOfABinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package lowestCommonAncestorOfABinaryTree; 2 | 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | TreeNode(int x) { val = x; } 8 | } 9 | -------------------------------------------------------------------------------- /algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py: -------------------------------------------------------------------------------- 1 | def findUnsortedSubarray(self, nums): 2 | same = [a == b for a, b in zip(nums, sorted(nums))] 3 | return 0 if all(same) else len(nums) - same.index(False) - same[::-1].index(False) -------------------------------------------------------------------------------- /algorithms/python/K-diffPairsInAnArray/findPairs.py: -------------------------------------------------------------------------------- 1 | def findPairs(self, nums, k): 2 | if k > 0: 3 | return len(set(nums) & set(a + k for a in nums)) 4 | elif k == 0: 5 | return sum(v > 1 for v in collections.Counter(nums).values()) 6 | return 0 -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreeBFSTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeBFSTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/java/src/inorderSuccessorInBST/TreeNode.java: -------------------------------------------------------------------------------- 1 | package inorderSuccessorInBST; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/python/LargestPerimeterTriangle/largestPerimeter.py: -------------------------------------------------------------------------------- 1 | def largestPerimeter(self, A): 2 | A.sort() 3 | n = len(A) 4 | for i in range(1, len(A) - 1): 5 | if A[n - i - 2] + A[n - i - 1] > A[n - i]: 6 | return A[n - i - 2] + A[n - i - 1] + A[n - i] 7 | return 0 -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreeMaximumPathSum/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeMaximumPathSum; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/python/UniqueBinarySearchTrees/numTrees.py: -------------------------------------------------------------------------------- 1 | def numTrees(self, n): 2 | if n == 1: return 1 3 | res = [1, 1] 4 | for i in range(2, n + 1): 5 | val = 0 6 | for j in range(i): 7 | val += res[j] * res[i - j - 1] 8 | res.append(val) 9 | return res[n] -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreePreorderTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreePreorderTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreeLevelOrderTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeLevelOrderTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/java/src/searchRangeInBinarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package searchRangeInBinarySearchTree; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/java/src/validateBinarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package validateBinarySearchTree; 2 | 3 | public class TreeNode { 4 | public int val; 5 | public TreeNode left, right; 6 | public TreeNode(int val) { 7 | this.val = val; 8 | this.left = this.right = null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /algorithms/python/LowestCommonAncestorOfABinaryTree/lowestCommonAncestor.py: -------------------------------------------------------------------------------- 1 | def lowestCommonAncestor(self, root, p, q): 2 | if root in (None, p, q): return root 3 | left = self.lowestCommonAncestor(root.left, p, q) 4 | right = self.lowestCommonAncestor(root.right, p, q) 5 | return root if left and right else left or right -------------------------------------------------------------------------------- /algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py: -------------------------------------------------------------------------------- 1 | def deckRevealedIncreasing(self, deck): 2 | deck.sort() 3 | res = [0] * len(deck) 4 | index = list(range(len(deck))) 5 | 6 | for i in range(len(deck)): 7 | res[index.pop(0)] = deck[i] 8 | if index: index.append(index.pop(0)) 9 | return res -------------------------------------------------------------------------------- /algorithms/java/src/balancedBinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package balancedBinaryTree; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | public int val; 8 | public TreeNode left, right; 9 | public TreeNode(int val) { 10 | this.val = val; 11 | this.left = this.right = null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /algorithms/python/BinaryTreeTilt/findTilt.py: -------------------------------------------------------------------------------- 1 | def findTilt(self, root): 2 | self.res = 0 3 | def helper(root): 4 | if not root: return 0 5 | left = helper(root.left) 6 | right = helper(root.right) 7 | self.res += abs(left - right) 8 | return root.val + left + right 9 | helper(root) 10 | return self.res -------------------------------------------------------------------------------- /algorithms/python/DifferentWaysToAddParentheses/diffWaysToCompute.py: -------------------------------------------------------------------------------- 1 | def diffWaysToCompute(self, input): 2 | return [a + b if c == '+' else a - b if c == '-' else a * b \ 3 | for i, c in enumerate(input) if c in '+-*' \ 4 | for a in self.diffWaysToCompute(input[:i]) \ 5 | for b in self.diffWaysToCompute(input[i+1:])] or [int(input)] -------------------------------------------------------------------------------- /algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py: -------------------------------------------------------------------------------- 1 | def removeNthFromEnd(self, head, n): 2 | slow = fast = head 3 | for i in range(n): 4 | fast = fast.next 5 | if not fast: return head.next 6 | while fast.next: 7 | fast = fast.next 8 | slow = slow.next 9 | slow.next = slow.next.next 10 | return head -------------------------------------------------------------------------------- /algorithms/python/ConstructBinaryTreeFromPreorderAndInorderTraversal/buildTree.py: -------------------------------------------------------------------------------- 1 | def buildTree(self, preorder, inorder): 2 | if inorder: 3 | i = inorder.index(preorder.pop(0)) 4 | root = TreeNode(inorder[i]) 5 | root.left = self.buildTree(preorder, inorder[:i]) 6 | root.right = self.buildTree(preorder, inorder[i+1:]) 7 | return root -------------------------------------------------------------------------------- /algorithms/python/Subsets/subsets.py: -------------------------------------------------------------------------------- 1 | def subsets(self, nums): 2 | res = [] 3 | def backtracking(temp, start): 4 | res.append(temp[:]) 5 | for i in range(start, len(nums)): 6 | temp.append(nums[i]) 7 | backtracking(temp, i + 1) 8 | temp.pop() 9 | 10 | backtracking([], 0) 11 | return res 12 | -------------------------------------------------------------------------------- /algorithms/java/src/binarySearchTreeIterator/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binarySearchTreeIterator; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | public int val; 8 | public TreeNode left, right; 9 | public TreeNode(int val) { 10 | this.val = val; 11 | this.left = this.right = null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /algorithms/python/ConstructBinaryTreeFromInorderAndPostorderTraversal/buildTree.py: -------------------------------------------------------------------------------- 1 | def buildTree(self, inorder, postorder): 2 | if inorder: 3 | i = inorder.index(postorder.pop()) 4 | root = TreeNode(inorder[i]) 5 | root.right = self.buildTree(inorder[i+1:], postorder) 6 | root.left = self.buildTree(inorder[:i], postorder) 7 | return root -------------------------------------------------------------------------------- /algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | def diameterOfBinaryTree(self, root): 2 | self.res = 0 3 | def helper(root): 4 | if not root: return 0 5 | left, right = helper(root.left), helper(root.right) 6 | self.res = max(self.res, left + right) 7 | return 1 + max(left, right) 8 | helper(root) 9 | return self.res -------------------------------------------------------------------------------- /algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py: -------------------------------------------------------------------------------- 1 | def isOneBitCharacter(self, bits): 2 | i = 0 3 | while i < len(bits): 4 | if bits[i] == 0: 5 | i += 1 6 | if i >= len(bits): return True 7 | if bits[i] == 1: 8 | i += 2 9 | if i >= len(bits): return False 10 | if i == len(bits) - 1: return True -------------------------------------------------------------------------------- /algorithms/java/src/firstBadVersion/VersionControl.java: -------------------------------------------------------------------------------- 1 | package firstBadVersion; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class VersionControl { 7 | int firstBadVersion; 8 | boolean isBadVersion(int version) { 9 | if (version >= firstBadVersion) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/python/FlattenBinaryTreeToLinkedList/flatten.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def __init__(self): 3 | self.prev = None 4 | 5 | def flatten(self, root): 6 | if not root: return None 7 | self.flatten(root.right) 8 | self.flatten(root.left) 9 | root.right = self.prev 10 | root.left = None 11 | self.prev = root -------------------------------------------------------------------------------- /algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py: -------------------------------------------------------------------------------- 1 | def findLengthOfLCIS(self, nums): 2 | if not nums: return 0 3 | res = 1 4 | temp = 1 5 | for i in range(1, len(nums)): 6 | if nums[i] > nums[i - 1]: 7 | temp += 1 8 | else: 9 | res = max(temp, res) 10 | temp = 1 11 | return max(temp, res) -------------------------------------------------------------------------------- /database/TripsAndUsers.sql: -------------------------------------------------------------------------------- 1 | SELECT t.`Request_at` AS Day, 2 | ROUND(COUNT(CASE WHEN t.`Status` = 'cancelled_by_driver' OR t.`Status` = 'cancelled_by_client' THEN 1 END) / COUNT(*), 2) AS "Cancellation Rate" 3 | FROM Trips t 4 | INNER JOIN Users u 5 | ON t.Client_Id = u.Users_Id 6 | WHERE u.Banned = 'No' 7 | AND t.Request_at >= '2013-10-01' 8 | AND t.Request_at <= '2013-10-03' 9 | GROUP BY t.Request_at -------------------------------------------------------------------------------- /algorithms/python/CountCompleteTreeNodes/countNodes.py: -------------------------------------------------------------------------------- 1 | def countNodes(self, root): 2 | if not root: return 0 3 | hl, hr = 0, 0 4 | l, r = root, root 5 | while l: 6 | hl += 1 7 | l = l.left 8 | while r: 9 | hr += 1 10 | r = r.right 11 | if hl == hr: return pow(2, hl) - 1 12 | return 1 + self.countNodes(root.left) + self.countNodes(root.right) -------------------------------------------------------------------------------- /algorithms/python/Non-decreasingArray/checkPossibility.py: -------------------------------------------------------------------------------- 1 | def checkPossibility(self, nums): 2 | count = 0 3 | for i in range(1, len(nums)): 4 | if nums[i] < nums[i - 1]: 5 | count += 1 6 | if i == 1 or nums[i - 2] <= nums[i]: nums[i - 1] = nums[i] 7 | else: nums[i] = nums[i - 1] 8 | 9 | if count >= 2: return False 10 | return True -------------------------------------------------------------------------------- /algorithms/python/PopulatingNextRightPointersInEachNode/connect.py: -------------------------------------------------------------------------------- 1 | def connect(self, root): 2 | if not root: return 3 | stack = [[root]] 4 | while True: 5 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 6 | if not children: break 7 | stack.append(children) 8 | for i in range(len(children) - 1): 9 | children[i].next = children[i+1] -------------------------------------------------------------------------------- /algorithms/python/PartitionList/partition.py: -------------------------------------------------------------------------------- 1 | def partition(self, head, x): 2 | h1 = l1 = ListNode(0) 3 | h2 = l2 = ListNode(0) 4 | while head: 5 | if head.val < x: 6 | l1.next = head 7 | l1 = l1.next 8 | else: 9 | l2.next = head 10 | l2 = l2.next 11 | head = head.next 12 | l2.next = None 13 | l1.next = h2.next 14 | return h1.next -------------------------------------------------------------------------------- /algorithms/python/PopulatingNextRightPointersInEachNodeII/connect.py: -------------------------------------------------------------------------------- 1 | def connect(self, root): 2 | if not root: return root 3 | stack = [[root]] 4 | while True: 5 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 6 | if not children: break 7 | stack.append(children) 8 | for i in range(len(children) - 1): 9 | children[i].next = children[i + 1] -------------------------------------------------------------------------------- /algorithms/python/LinkedListCycleII/detectCycle.py: -------------------------------------------------------------------------------- 1 | def detectCycle(self, head): 2 | slow, fast = head, head 3 | while fast and fast.next: 4 | slow = slow.next 5 | fast = fast.next.next 6 | if slow == fast: break 7 | 8 | if not fast or not fast.next: return None 9 | slow = head 10 | while slow != fast: 11 | slow = slow.next 12 | fast = fast.next 13 | return slow -------------------------------------------------------------------------------- /algorithms/python/FindTheDuplicateNumber/findDuplicate.py: -------------------------------------------------------------------------------- 1 | # the same as linked list cycle problem 2 | def findDuplicate(self, nums): 3 | if len(nums) <= 1: return -1 4 | slow, fast = nums[0], nums[nums[0]] 5 | while slow != fast: 6 | slow = nums[slow] 7 | fast = nums[nums[fast]] 8 | 9 | fast = 0 10 | while slow != fast: 11 | slow = nums[slow] 12 | fast = nums[fast] 13 | return slow -------------------------------------------------------------------------------- /algorithms/python/LowestCommonAncestorOfABinarySearchTree/lowestCommonAncestor.py: -------------------------------------------------------------------------------- 1 | # straight forward recursive solution 2 | 3 | def lowestCommonAncestor(self, root, p, q): 4 | if not root: return None 5 | if root.val > p.val and root.val > q.val: 6 | return self.lowestCommonAncestor(root.left, p, q) 7 | elif root.val < p.val and root.val < q.val: 8 | return self.lowestCommonAncestor(root.right, p, q) 9 | return root -------------------------------------------------------------------------------- /algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py: -------------------------------------------------------------------------------- 1 | def largeGroupPositions(self, S): 2 | res = [] 3 | i = 0 4 | while i < len(S) - 2: 5 | if S[i] == S[i + 1] and S[i] == S[i + 2]: 6 | val = S[i] 7 | index = i 8 | while i < len(S) and S[i] == val: 9 | i += 1 10 | res.append([index, i - 1]) 11 | i -= 1 12 | i += 1 13 | return res -------------------------------------------------------------------------------- /algorithms/python/LongestTurbulentSubarray/maxTurbulenceSize.py: -------------------------------------------------------------------------------- 1 | def maxTurbulenceSize(self, A): 2 | res = inc = dec = 1 3 | for i in range(1, len(A)): 4 | if A[i] > A[i - 1]: 5 | inc = dec + 1 6 | dec = 1 7 | elif A[i] < A[i - 1]: 8 | dec = inc + 1 9 | inc = 1 10 | else: 11 | inc = 1 12 | dec = 1 13 | res = max(res, max(inc, dec)) 14 | return res -------------------------------------------------------------------------------- /algorithms/java/src/validAnagram/TestValidAnagram.java: -------------------------------------------------------------------------------- 1 | package validAnagram; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 242. Valid Anagram 8 | */ 9 | public class TestValidAnagram { 10 | @Test 11 | public void test() { 12 | ValidAnagram solution = new ValidAnagram(); 13 | Assert.assertTrue(solution.isAnagram("anagram", "nagaram")); 14 | Assert.assertTrue(!solution.isAnagram("rat", "car")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /algorithms/python/ReverseLinkedListII/reverseBetween.py: -------------------------------------------------------------------------------- 1 | def reverseBetween(self, head, m, n): 2 | if not head or n == m: return head 3 | p = dummy = ListNode(0) 4 | dummy.next = head 5 | for _ in range(m - 1): 6 | p = p.next 7 | tail = p.next 8 | 9 | for _ in range(n - m): 10 | temp = p.next 11 | p.next = tail.next 12 | tail.next = tail.next.next 13 | p.next.next = temp 14 | return dummy.next -------------------------------------------------------------------------------- /algorithms/python/FindDuplicateSubtrees/findDuplicateSubtrees.py: -------------------------------------------------------------------------------- 1 | def findDuplicateSubtrees(self, root): 2 | nodes = collections.defaultdict(list) 3 | 4 | def helper(root): 5 | if not root: return 'None' 6 | struct = '%s,%s,%s' % (str(root.val), helper(root.left), helper(root.right)) 7 | nodes[struct].append(root) 8 | return struct 9 | 10 | helper(root) 11 | return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1] -------------------------------------------------------------------------------- /algorithms/python/ThirdMaximumNumber/thirdMax.py: -------------------------------------------------------------------------------- 1 | def thirdMax(self, nums): 2 | if len(set(nums)) < 3: return max(nums) 3 | first = second = third = float('-inf') 4 | for n in nums: 5 | if n > first: 6 | third = second 7 | second = first 8 | first = n 9 | elif second < n < first: 10 | third = second 11 | second = n 12 | elif third < n < second: 13 | third = n 14 | return third -------------------------------------------------------------------------------- /.gitconfig: -------------------------------------------------------------------------------- 1 | [alias] 2 | 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 3 | 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 4 | lg = !"git lg1" 5 | -------------------------------------------------------------------------------- /algorithms/python/AddOneRowToTree/addOneRow.py: -------------------------------------------------------------------------------- 1 | # get the nodes at (d - 1) layer: 2 | 3 | def addOneRow(self, root, v, d): 4 | dummy, dummy.left = TreeNode(v), root 5 | row = [dummy] 6 | for _ in range(d - 1): 7 | row = [kid for node in row for kid in (node.left, node.right) if kid] 8 | 9 | for node in row: 10 | node.left, node.left.left = TreeNode(v), node.left 11 | node.right, node.right.right = TreeNode(v), node.right 12 | return dummy.left -------------------------------------------------------------------------------- /algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py: -------------------------------------------------------------------------------- 1 | # simply find the three largest and two smallest 2 | # Method 1: sort 3 | def maximumProduct(self, nums): 4 | nums.sort() 5 | return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) 6 | 7 | # Method 2: using heapq, O(n) time 8 | def maximumProduct(self, nums): 9 | import heapq 10 | a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums) 11 | return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1]) -------------------------------------------------------------------------------- /algorithms/python/ContainsDuplicateIII/containsNearbyAlmostDuplicate.py: -------------------------------------------------------------------------------- 1 | def containsNearbyAlmostDuplicate(self, nums, k, t): 2 | if k < 1 or t < 0: return False 3 | d = {} 4 | w = t + 1 5 | for i, n in enumerate(nums): 6 | m = n // w 7 | if m in d: return True 8 | if m - 1 in d and abs(d[m-1] - n) <= t: return True 9 | if m + 1 in d and abs(d[m+1] - n) <= t: return True 10 | d[m] = n 11 | if i >= k: del d[nums[i - k] // w] 12 | return False -------------------------------------------------------------------------------- /algorithms/python/SumOfLeftLeaves/sumOfLeftLeaves.py: -------------------------------------------------------------------------------- 1 | """ 2 | straight forward recursive solution: 3 | if left node is leave, add the value and the the right subtree 4 | if not, then recursively call left and right subtree 5 | """ 6 | def sumOfLeftLeaves(self, root): 7 | if not root: return 0 8 | if root.left and not root.left.left and not root.left.right: 9 | return root.left.val + self.sumOfLeftLeaves(root.right) 10 | return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) -------------------------------------------------------------------------------- /algorithms/java/src/countAndSay/TestCountAndSay.java: -------------------------------------------------------------------------------- 1 | package countAndSay; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 38. Count and Say 7 | */ 8 | public class TestCountAndSay { 9 | @Test 10 | public void test() { 11 | CountAndSay solution = new CountAndSay(); 12 | String next5 = solution.countAndSay(5); 13 | Assert.assertTrue(next5.equals("111221")); 14 | String next6 = solution.countAndSay(6); 15 | Assert.assertTrue(next6.equals("312211")); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /algorithms/python/ImageSmoother/imageSmoother.py: -------------------------------------------------------------------------------- 1 | def imageSmoother(self, M): 2 | from copy import deepcopy 3 | 4 | if not M or not M[0]: return [[]] 5 | row, col = len(M), len(M[0]) 6 | res = deepcopy(M) 7 | for x in range(row): 8 | for y in range(col): 9 | temp = [M[i][j] for i in [x - 1, x, x + 1] for j in [y - 1, y, y + 1] if \ 10 | 0 <= i < row and 0 <= j < col] 11 | res[x][y] = sum(temp) // len(temp) 12 | 13 | return res -------------------------------------------------------------------------------- /algorithms/python/RemoveDuplicatesFromSortedListII/deleteDuplicates.py: -------------------------------------------------------------------------------- 1 | def deleteDuplicates(self, head): 2 | dummy = prev = ListNode(0) 3 | dummy.next = head 4 | while head and head.next: 5 | if head.val == head.next.val: 6 | while head and head.next and head.val == head.next.val: 7 | head = head.next 8 | head = head.next 9 | prev.next = head 10 | else: 11 | prev = prev.next 12 | head = head.next 13 | return dummy.next -------------------------------------------------------------------------------- /algorithms/python/InsertionSortList/insertionSortList.py: -------------------------------------------------------------------------------- 1 | def insertionSortList(self, head): 2 | if not head: return head 3 | 4 | dummy = ListNode(0) 5 | curr = head 6 | prev = dummy 7 | 8 | while curr: 9 | next = curr.next 10 | while prev.next and prev.next.val < curr.val: 11 | prev = prev.next 12 | 13 | curr.next = prev.next 14 | prev.next = curr 15 | prev = dummy 16 | 17 | curr = next 18 | 19 | return dummy.next -------------------------------------------------------------------------------- /algorithms/python/LongestUnivaluePath/longestUnivaluePath.py: -------------------------------------------------------------------------------- 1 | def longestUnivaluePath(self, root): 2 | self.longest = 0 3 | def helper(root): 4 | if not root: return 0 5 | l, r = helper(root.left), helper(root.right) 6 | left = (l + 1) if root.left and root.left.val == root.val else 0 7 | right = (r + 1) if root.right and root.right.val == root.val else 0 8 | self.longest = max(self.longest, left + right) 9 | return max(left, right) 10 | helper(root) 11 | return self.longest -------------------------------------------------------------------------------- /algorithms/java/src/powXn/TestPowXn.java: -------------------------------------------------------------------------------- 1 | package powXn; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 50. Pow(x, n) 8 | */ 9 | public class TestPowXn { 10 | @Test 11 | public void test() { 12 | PowXn solution = new PowXn(); 13 | Assert.assertTrue(solution.myPow01(3, 9) == 19683); 14 | Assert.assertTrue(solution.myPow02(3, 9) == 19683); 15 | Assert.assertTrue(solution.myPow01(2.10000, -3)-0.10798<0.0001); 16 | Assert.assertTrue(solution.myPow02(2.10000, -3)-0.10798<0.0001); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/python/FlipBinaryTreeToMatchPreorderTraversal/flipMatchVoyage.py: -------------------------------------------------------------------------------- 1 | def flipMatchVoyage(self, root, voyage): 2 | res = [] 3 | self.i = 0 4 | def dfs(root): 5 | if not root: return True 6 | if root.val != voyage[self.i]: return False 7 | self.i += 1 8 | if root.left and root.left.val != voyage[self.i]: 9 | res.append(root.val) 10 | root.left, root.right = root.right, root.left 11 | return dfs(root.left) and dfs(root.right) 12 | return res if dfs(root) else [-1] -------------------------------------------------------------------------------- /algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py: -------------------------------------------------------------------------------- 1 | def maxDistToClosest(self, seats): 2 | first = seats.index(1) 3 | last = 0 4 | for i in range(len(seats) - 1, -1, -1): 5 | if seats[i]: 6 | last = i 7 | break 8 | res = 0 9 | temp = 0 10 | for i in range(first, last + 1): 11 | if seats[i] == 1: 12 | res = max(temp, res) 13 | temp = 0 14 | else: 15 | temp += 1 16 | return max(first, len(seats) - last - 1, (res + 1) // 2) -------------------------------------------------------------------------------- /algorithms/java/src/minStack/TestMinStack.java: -------------------------------------------------------------------------------- 1 | package minStack; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 155. Min Stack 8 | */ 9 | public class TestMinStack { 10 | @Test 11 | public void test() { 12 | MinStack minStack = new MinStack(); 13 | minStack.push(3); 14 | minStack.push(4); 15 | minStack.push(1); 16 | minStack.push(2); 17 | Assert.assertTrue(minStack.getMin() == 1); 18 | minStack.pop(); 19 | minStack.pop(); 20 | Assert.assertTrue(minStack.getMin() == 3); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/java/src/validPalindrome/TestValidPalindrome.java: -------------------------------------------------------------------------------- 1 | package validPalindrome; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 125. Valid Palindrome 7 | */ 8 | public class TestValidPalindrome { 9 | @Test 10 | public void test() { 11 | ValidPalindrome solution = new ValidPalindrome(); 12 | String str1 = "A man, a plan, a canal: Panama"; 13 | Assert.assertTrue(solution.isPalindrome(str1)); 14 | String str2 = "race a car"; 15 | Assert.assertTrue(!solution.isPalindrome(str2)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /shell/README.md: -------------------------------------------------------------------------------- 1 | ###LeetCode Shell 2 | 3 | 4 | | # | Title | Solution | Difficulty | 5 | |---| ----- | -------- | ---------- | 6 | |4|[Tenth Line](https://leetcode.com/problems/tenth-line/)| [Bash](./TenthLine.sh)|Easy| 7 | |3|[Transpose File](https://leetcode.com/problems/transpose-file/)| [Bash](./TransposeFile.sh)|Medium| 8 | |2|[Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/)| [Bash](./ValidPhoneNumbers.sh)|Easy| 9 | |1|[Word Frequency](https://leetcode.com/problems/word-frequency/)| [Bash](./WordFrequency.sh)|Medium| 10 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseWordsInAString/TestReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | package reverseWordsInAString; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 151. Reverse Words in a String 8 | */ 9 | public class TestReverseWordsInAString { 10 | @Test 11 | public void test() { 12 | ReverseWordsInAString solution = new ReverseWordsInAString(); 13 | String str = " the sky is blue "; 14 | String result = solution.reverseWords(str); 15 | Assert.assertTrue(result.equals("blue is sky the")); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /algorithms/python/MaximumWidthOfBinaryTree/widthOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | def widthOfBinaryTree(self, root): 2 | if not root: return 0 3 | stack = [[(root, 0)]] 4 | res = 1 5 | while True: 6 | children = [] 7 | for node, value in stack[-1]: 8 | if node.left: children.append((node.left, value * 2)) 9 | if node.right: children.append((node.right, value * 2 + 1)) 10 | if not children: break 11 | stack.append(children) 12 | res = max(res, children[-1][1] - children[0][1] + 1) 13 | return res -------------------------------------------------------------------------------- /algorithms/java/src/lengthOfLastWord/TestLengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package lengthOfLastWord; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 58. Length of Last Word 8 | */ 9 | public class TestLengthOfLastWord { 10 | @Test 11 | public void test() { 12 | LengthOfLastWord solution = new LengthOfLastWord(); 13 | String str1 = "Hello World"; 14 | Assert.assertTrue(solution.lengthOfLastWord(str1) == 5); 15 | String str2 = "Thank you very much "; 16 | Assert.assertTrue(solution.lengthOfLastWord(str2) == 4); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/python/ConvertBSTtoGreaterTree/convertBST.py: -------------------------------------------------------------------------------- 1 | """ 2 | since this is a BST, we can do a inorder traversal (inversed, from right to left), 3 | during this process, track the sum and update the node.val 4 | """ 5 | 6 | class Solution: 7 | def convertBST(self, root): 8 | self.total = 0 9 | 10 | def helper(node): 11 | if not node: return 12 | helper(node.right) 13 | node.val += self.total 14 | self.total = node.val 15 | helper(node.left) 16 | 17 | helper(root) 18 | return root -------------------------------------------------------------------------------- /algorithms/python/PathSumIII/pathSum.py: -------------------------------------------------------------------------------- 1 | def pathSum(self, root, target): 2 | self.result = 0 3 | cache = {0:1} 4 | 5 | def dfs(root, currPathSum): 6 | if not root: return 7 | 8 | currPathSum += root.val 9 | oldPathSum = currPathSum - target 10 | 11 | self.result += cache.get(oldPathSum, 0) 12 | cache[currPathSum] = cache.get(currPathSum, 0) + 1 13 | 14 | 15 | dfs(root.left, currPathSum) 16 | dfs(root.right, currPathSum) 17 | 18 | cache[currPathSum] -= 1 19 | 20 | dfs(root, 0) 21 | return self.result -------------------------------------------------------------------------------- /algorithms/python/BinaryTreeZigzagLevelOrderTraversal/zigzagLevelOrder.py: -------------------------------------------------------------------------------- 1 | """ 2 | simple bfs 3 | """ 4 | 5 | def zigzagLevelOrder(self, root): 6 | if not root: return [] 7 | stack = [[root]] 8 | res = [[root.val]] 9 | level = 0 10 | while True: 11 | level += 1 12 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 13 | if not children: break 14 | temp = [node.val for node in children] 15 | if level % 2 == 1: temp.reverse() 16 | res.append(temp) 17 | stack.append(children) 18 | return res -------------------------------------------------------------------------------- /algorithms/python/SubtreeOfAnotherTree/isSubtree.py: -------------------------------------------------------------------------------- 1 | def isSubtree(self, s, t): 2 | stack = [s] 3 | while stack: 4 | node = stack.pop(0) 5 | if node.val == t.val: 6 | if self.check(node, t): return True 7 | stack += [child for child in [node.left, node.right] if child] 8 | return False 9 | 10 | def check(self, first, second): 11 | if not first and not second: 12 | return True 13 | if first and second: 14 | return first.val == second.val and self.check(first.left, second.left) and self.check(first.right, second.right) 15 | return False -------------------------------------------------------------------------------- /algorithms/java/src/myStack/TestMyStack.java: -------------------------------------------------------------------------------- 1 | package myStack; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 225. Implement Stack using Queues 7 | */ 8 | public class TestMyStack { 9 | @Test 10 | public void test(){ 11 | MyStack stack=new MyStack(); 12 | stack.push(1); 13 | stack.push(2); 14 | stack.push(3); 15 | stack.push(4); 16 | Assert.assertTrue(stack.empty()==false); 17 | Assert.assertTrue(stack.pop()==4); 18 | Assert.assertTrue(stack.pop()==3); 19 | Assert.assertTrue(stack.top()==2); 20 | stack.push(5); 21 | Assert.assertTrue(stack.top()==5); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /algorithms/java/src/palindromeNumber/TestPalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package palindromeNumber; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 9. Palindrome Number 8 | */ 9 | public class TestPalindromeNumber { 10 | @Test 11 | public void test() { 12 | PalindromeNumber solution = new PalindromeNumber(); 13 | boolean flag1 = solution.isPalindrome(1234567); 14 | Assert.assertTrue(!flag1); 15 | boolean flag2 = solution.isPalindrome(1234321); 16 | Assert.assertTrue(flag2); 17 | boolean flag3 = solution.isPalindrome(12344321); 18 | Assert.assertTrue(flag3); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py: -------------------------------------------------------------------------------- 1 | def isCompleteTree(self, root): 2 | stack = [[(root, 0)]] 3 | layer = 0 4 | while True: 5 | children = [] 6 | for node, value in stack[-1]: 7 | if node.left: children.append((node.left, 2 * value)) 8 | if node.right: children.append((node.right, 2 * value + 1)) 9 | if node.right and not node.left: return False 10 | if not children: break 11 | if len(stack[-1]) != pow(2, layer): return False 12 | stack.append(children) 13 | layer += 1 14 | return len(stack[-1]) == stack[-1][-1][1] + 1 -------------------------------------------------------------------------------- /algorithms/java/src/searchA2DMatrixII/Test_240.java: -------------------------------------------------------------------------------- 1 | package searchA2DMatrixII; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 240. Search a 2D Matrix II 7 | */ 8 | public class Test_240 { 9 | @Test 10 | public void test() { 11 | SearchA2DMatrixII solution = new SearchA2DMatrixII(); 12 | int[][] matrix = {{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, 13 | {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}; 14 | int target = 5; 15 | Assert.assertTrue(solution.searchMatrix(matrix, target)); 16 | target = 20; 17 | Assert.assertTrue(!solution.searchMatrix(matrix, target)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /algorithms/java/src/myQueue/TestMyQueue.java: -------------------------------------------------------------------------------- 1 | package myQueue; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 232. Implement Queue using Stacks 7 | */ 8 | public class TestMyQueue { 9 | @Test 10 | public void test(){ 11 | MyQueue queue=new MyQueue(); 12 | Assert.assertTrue(queue.empty()); 13 | queue.push(1); 14 | queue.push(2); 15 | queue.push(3); 16 | queue.push(4); 17 | Assert.assertTrue(queue.pop()==1); 18 | Assert.assertTrue(queue.pop()==2); 19 | queue.push(5); 20 | Assert.assertTrue(queue.peek()==3); 21 | Assert.assertTrue(!queue.empty()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /algorithms/python/FibonacciNumber/fib.py: -------------------------------------------------------------------------------- 1 | """ 2 | Method 1: iterative: 3 | """ 4 | def fib1(self, N): 5 | if N <= 1: return N 6 | a, b = 0, 1 7 | for _ in range(2, N + 1): 8 | a, b = b, a + b 9 | return b 10 | 11 | """ 12 | Method 2: recursive without memorization: 13 | """ 14 | def fib2(self, N): 15 | if N <= 1: return N 16 | return self.fib(N - 1) + self.fib(N - 2) 17 | 18 | """ 19 | Method 3: recursive with memorization 20 | """ 21 | def fib3(self, N): 22 | memo = {0:0, 1:1} 23 | def helper(n): 24 | if n not in memo: 25 | memo[n] = helper(n - 1) + helper(n - 2) 26 | return memo[n] 27 | return helper(N) -------------------------------------------------------------------------------- /algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py: -------------------------------------------------------------------------------- 1 | # Method 1: sliding window 2 | 3 | def findMaxAverage(self, nums, k): 4 | total = 0 5 | temp = float('-inf') 6 | for i, n in enumerate(nums): 7 | total += n 8 | if i >= k: total -= nums[i- k] 9 | if i >= k - 1: 10 | temp = max(temp, total) 11 | return temp / k 12 | 13 | 14 | 15 | # Method 2: prefix sum 16 | def findMaxAverage(self, nums, k): 17 | temp = [0] 18 | for n in nums: 19 | temp.append(temp[-1] + n) 20 | 21 | res = max(temp[i + k] - temp[i] for i in range(len(nums) - k + 1)) 22 | return res / k -------------------------------------------------------------------------------- /algorithms/python/ContainsDuplicateII/containsNearbyDuplicate.py: -------------------------------------------------------------------------------- 1 | # Method 1: using set 2 | 3 | def containsNearbyDuplicate(self, nums, k): 4 | if len(nums) <= k + 1: return len(nums) != len(set(nums)) 5 | if k == 0: return False 6 | s = set(nums[:k]) 7 | for i in range(k, len(nums)): 8 | if nums[i] in s: return True 9 | else: 10 | s.remove(nums[i - k]) 11 | s.add(nums[i]) 12 | return False 13 | 14 | # Method 2: using dictionary 15 | def containsNearbyDuplicate(self, nums, k): 16 | d = {} 17 | for i, n in enumerate(nums): 18 | if n in d and i - d[v] <= k: 19 | return True 20 | d[n] = i 21 | return False -------------------------------------------------------------------------------- /algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.h: -------------------------------------------------------------------------------- 1 | // 2 | // OJ#418.h 3 | // LeeteCodeOJ#418 4 | // 5 | // Created by Wang Yi on 25/10/16. 6 | // Copyright (c) 2016 Wang Yi. All rights reserved. 7 | // 8 | 9 | #ifndef __LeeteCodeOJ_418__OJ_418__ 10 | #define __LeeteCodeOJ_418__OJ_418__ 11 | 12 | #define M 10 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | using std::vector; 19 | using std::string; 20 | 21 | int SentenceScreenFitting(char stc[][M], int row, int col, size_t l); 22 | 23 | class Solution { 24 | public: 25 | int wordsTyping(vector& sentence, int rows, int cols); 26 | }; 27 | 28 | #endif /* defined(__LeeteCodeOJ_418__OJ_418__) */ 29 | -------------------------------------------------------------------------------- /algorithms/java/src/dynamicProgramming/climbStairs/climbStairsTest.java: -------------------------------------------------------------------------------- 1 | package dynamicProgramming.climbStairs; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 12/10/15. 9 | */ 10 | public class climbStairsTest { 11 | 12 | @Test 13 | public void testClimbStairs() throws Exception { 14 | int[] inputs = {1,2,3,4}; 15 | 16 | int[] results = {1,2,3,5}; 17 | 18 | for (int i = 0; i < results.length; i++) { 19 | climbStairs c = new climbStairs(); 20 | int r = c.climbStairs(inputs[i]); 21 | System.out.println(r); 22 | assertEquals(results[i], r); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /algorithms/python/KthSmallestElementInABST/kthSmallest.py: -------------------------------------------------------------------------------- 1 | # Method 1: recursive in-order traversal 2 | def kthSmallest1(self, root, k): 3 | inorder = [] 4 | def helper(root): 5 | if root: 6 | helper(root.left) 7 | inorder.append(root.val) 8 | helper(root.right) 9 | 10 | helper(root) 11 | return inorder[k-1] 12 | 13 | # Method 2: iterative in-order traversal 14 | def kthSmallest2(self, root, k): 15 | stack = [] 16 | while root or stack: 17 | while root: 18 | stack.append(root) 19 | root = root.left 20 | root = stack.pop() 21 | k -= 1 22 | if k == 0: return root.val 23 | root = root.right -------------------------------------------------------------------------------- /algorithms/java/src/strStr/strStrTest.java: -------------------------------------------------------------------------------- 1 | package strStr; 2 | 3 | import com.sun.org.apache.xpath.internal.operations.Equals; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 2/10/15. 9 | */ 10 | public class strStrTest { 11 | 12 | @org.junit.Test 13 | public void testStrStr() throws Exception { 14 | strStr strStr = new strStr(); 15 | String[][] inputs = { 16 | {"I am the haystack!","haystack!"}, 17 | {"I am the haystack!","haytack"}, 18 | }; 19 | int[] outputs = {9, -1}; 20 | for (int i = 0; i < inputs.length; i++) { 21 | assertEquals(outputs[i], strStr.strStr(inputs[i][0], inputs[i][1])); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /algorithms/python/XOfAKindInADeckOfCards/hasGroupsSizeX.py: -------------------------------------------------------------------------------- 1 | # Method 1: find the greatest common divisor using iteration 2 | 3 | def hasGroupsSizeX(self, deck): 4 | if len(deck) < 2: return False 5 | vals = collections.Counter(deck).values() 6 | for n in range(2, max(vals) + 1): 7 | if all(v % n == 0 for v in vals): return True 8 | return False 9 | 10 | # Method 2: find the greatest common divisor using reduce 11 | # Time complexity: O(n) 12 | def hasGroupsSizeX(self, deck): 13 | from functools import reduce 14 | if len(deck) < 2: return False 15 | vals = collections.Counter(deck).values() 16 | def gcd(a, b): 17 | while b: a, b = b, a % b 18 | return a 19 | return reduce(gcd, vals) -------------------------------------------------------------------------------- /algorithms/java/algorithms-java.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /algorithms/python/ValidMountainArray/validMountainArray.py: -------------------------------------------------------------------------------- 1 | # Method 1: using index find the max first, and then process 2 | 3 | def validMountainArray(self, A): 4 | if len(A) < 3: return False 5 | index = A.index(max(A)) 6 | if index == 0 or index == len(A) -1: return False 7 | for i in range(1, len(A)): 8 | if i <= index: 9 | if A[i] <= A[i - 1]: return False 10 | else: 11 | if A[i] >= A[i - 1]: return False 12 | return True 13 | 14 | 15 | # Method 2: one pass, using two pointers trace from the begining and end 16 | def validMountainArray(self, A): 17 | i, j = 0, len(A) - 1 18 | while i < len(A) - 1 and A[i] < A[i + 1]: i += 1 19 | while j > 0 and A[j - 1] > A[j]: j -= 1 20 | return 0 < i == j < len(A) - 1 -------------------------------------------------------------------------------- /algorithms/python/PancakeSorting/pancakeSort.py: -------------------------------------------------------------------------------- 1 | """ 2 | basic idea: find the index of smallest element in A, filp the list from that index, this makes the smallest element 3 | comes to the first, then filp the whole list, to make smallest element goes to the tail. And then delete that element. 4 | 5 | Do 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 6 | """ 7 | 8 | def pancakeSort(self, A): 9 | res = [] 10 | n = len(A) 11 | while A: 12 | smallest = A.index(min(A)) 13 | res.append(smallest + 1) 14 | res.append(len(A)) 15 | A = list(reversed(A[:smallest + 1])) + A[smallest + 1:] 16 | A.reverse() 17 | del A[-1] 18 | res.append(n) 19 | return res -------------------------------------------------------------------------------- /algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsTest.java: -------------------------------------------------------------------------------- 1 | package dynamicProgramming.uniquePaths; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 11/10/15. 9 | */ 10 | public class uniquePathsTest { 11 | 12 | @Test 13 | public void testUniquePaths() throws Exception { 14 | int[][] inputs = { 15 | {2,2}, 16 | {3,7}, 17 | }; 18 | int[] results = {2,28}; 19 | for (int i = 0; i < inputs.length; i++) { 20 | uniquePaths u = new uniquePaths(); 21 | int r = u.uniquePaths(inputs[i][0], inputs[i][1]); 22 | System.out.println(r); 23 | assertEquals(results[i], r); 24 | } 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /algorithms/java/src/firstBadVersion/firstBadVersionTest.java: -------------------------------------------------------------------------------- 1 | package firstBadVersion; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 5/10/15. 9 | */ 10 | public class firstBadVersionTest { 11 | 12 | @Test 13 | public void testFirstBadVersion() throws Exception { 14 | int[] inputs = {1,22,34,40,5232,6342342,71231}; 15 | int[] targets = {1, 10, 20, 25, 323, 45454, 23232}; 16 | 17 | firstBadVersion f = new firstBadVersion(); 18 | for (int i = 0; i < targets.length; i++) { 19 | f.firstBadVersion = targets[i]; 20 | int r = f.firstBadVersion(inputs[i]); 21 | System.out.println(r); 22 | assertEquals(targets[i], r); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /algorithms/python/ReorderList/reorderList.py: -------------------------------------------------------------------------------- 1 | def reorderList(self, head): 2 | if not head or not head.next: return 3 | 4 | # Step 1: find the middle node 5 | middle = None 6 | slow, fast = head, head 7 | while fast and fast.next: 8 | middle = slow 9 | slow = slow.next 10 | fast = fast.next.next 11 | middle.next = None 12 | 13 | # Step 2: reverse the second half 14 | prev = None 15 | while slow: 16 | nextNode = slow.next 17 | slow.next = prev 18 | prev, slow = slow, nextNode 19 | 20 | # Step 3: merge two lists 21 | while head and prev: 22 | first, second = head.next, prev.next 23 | head.next = prev 24 | if first: prev.next = first 25 | head, prev = first, second -------------------------------------------------------------------------------- /algorithms/java/src/rotateArray/TestRotateArray.java: -------------------------------------------------------------------------------- 1 | package rotateArray; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | /** 9 | * Test for 189. Rotate Array 10 | * 11 | */ 12 | public class TestRotateArray { 13 | @Test 14 | public void test() { 15 | RotateArray solution = new RotateArray(); 16 | int[] array1 = {1, 2, 3, 4, 5, 6, 7}; 17 | int k1 = 24; 18 | solution.rotate(array1, k1); 19 | int[] expectArray1 = {5, 6, 7, 1, 2, 3, 4}; 20 | Assert.assertTrue(Arrays.equals(array1, expectArray1)); 21 | int[] array2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 22 | int k2 = 4; 23 | solution.rotate(array2, k2); 24 | int[] expectArray2 = {6, 7, 8, 9, 1, 2, 3, 4, 5}; 25 | Assert.assertTrue(Arrays.equals(array2, expectArray2)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/python/UniqueBinarySearchTreesII/generateTrees.py: -------------------------------------------------------------------------------- 1 | def generateTrees(self, n): 2 | if n == 0: return [] 3 | 4 | def helper(start, end): 5 | ls = [] 6 | if start > end: 7 | ls.append(None) 8 | return ls 9 | if start == end: 10 | ls.append(TreeNode(start)) 11 | return ls 12 | 13 | for i in range(start, end + 1): 14 | left = helper(start, i - 1) 15 | right = helper(i + 1, end) 16 | for lnode in left: 17 | for rnode in right: 18 | root = TreeNode(i) 19 | root.left = lnode 20 | root.right = rnode 21 | ls.append(root) 22 | return ls 23 | 24 | return helper(1, n) -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedList/TestReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package reverseLinkedList; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 206. Reverse Linked List 8 | */ 9 | public class TestReverseLinkedList { 10 | @Test 11 | public void test(){ 12 | ReverseLinkedList solution=new ReverseLinkedList(); 13 | int[] array1={1,2,3,4,5,6}; 14 | ListNode head1=ListNode.arrayToList(array1); 15 | ListNode newHead1=solution.reverseList(head1); 16 | Assert.assertTrue(ListNode.listToString(newHead1).equals("6,5,4,3,2,1")); 17 | int[] array2={6,5,4,3,2,1}; 18 | ListNode head2=ListNode.arrayToList(array2); 19 | ListNode newHead2=solution.reverseListRecursion(head2); 20 | Assert.assertTrue(ListNode.listToString(newHead2).equals("1,2,3,4,5,6")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/cpp/reverseString/ReverseString.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-string/ 2 | // Author : Hao Chen 3 | // Date : 2016-05-29 4 | 5 | /*************************************************************************************** 6 | * 7 | * Write a function that takes a string as input and returns the string reversed. 8 | * 9 | * Example: 10 | * Given s = "hello", return "olleh". 11 | ***************************************************************************************/ 12 | 13 | class Solution { 14 | public: 15 | string reverseString(string s) { 16 | int len = s.size(); 17 | for (int i=0; i 10 | #include 11 | #include 12 | 13 | #include "course_schedule.cpp" 14 | 15 | using std::make_pair; 16 | 17 | int main(int argc, const char * argv[]) { 18 | // insert code here... 19 | Solution sl; 20 | int numCourses = 4; 21 | vector prerequisites; 22 | prerequisites.push_back(make_pair(0,1)); 23 | prerequisites.push_back(make_pair(3,1)); 24 | prerequisites.push_back(make_pair(1,3)); 25 | prerequisites.push_back(make_pair(3,2)); 26 | 27 | 28 | std::cout << sl.canFinish(numCourses, prerequisites); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsIITest.java: -------------------------------------------------------------------------------- 1 | package dynamicProgramming.uniquePaths; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 11/10/15. 9 | */ 10 | public class uniquePathsIITest { 11 | 12 | @Test 13 | public void testUniquePathsWithObstacles() throws Exception { 14 | int[][][] inputs = { 15 | { 16 | {0,0,0}, 17 | {0,1,0}, 18 | {0,0,0}, 19 | } 20 | }; 21 | int[] results = {2}; 22 | for (int i = 0; i < inputs.length; i++) { 23 | uniquePathsII u = new uniquePathsII(); 24 | int r = u.uniquePathsWithObstacles(inputs[i]); 25 | System.out.println(r); 26 | assertEquals(results[i], r); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedListII/TestReverseLinkedListII.java: -------------------------------------------------------------------------------- 1 | package reverseLinkedListII; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 92. Reverse Linked List II 8 | */ 9 | public class TestReverseLinkedListII { 10 | @Test 11 | public void test() { 12 | ReverseLinkedListII solution = new ReverseLinkedListII(); 13 | int[] array1 = {1, 2, 3, 4, 5, 6, 7}; 14 | ListNode head1 = ListNode.arrayToList(array1); 15 | ListNode newHead1 = solution.reverseBetween(head1, 3, 5); 16 | Assert.assertTrue(ListNode.listToString(newHead1).equals( 17 | "1,2,5,4,3,6,7")); 18 | int[] array2 = {7, 6, 5, 4, 3, 2, 1}; 19 | ListNode head2 = ListNode.arrayToList(array2); 20 | ListNode newHead2 = solution.reverseBetween(head2, 1, 7); 21 | Assert.assertTrue(ListNode.listToString(newHead2).equals( 22 | "1,2,3,4,5,6,7")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/python/NumberOfIslands/numIslands.py: -------------------------------------------------------------------------------- 1 | def numIslands(self, grid): 2 | if not grid or not grid[0]: return 0 3 | row, col = len(grid), len(grid[0]) 4 | self.visited = [[False for _ in range(col)] for _ in range(row)] 5 | 6 | def floodfill(i, j): 7 | if grid[i][j] == '1' and self.visited[i][j] == False: 8 | self.visited[i][j] = True 9 | if i > 0: 10 | floodfill(i - 1, j) 11 | if i < row - 1: 12 | floodfill(i + 1, j) 13 | if j > 0: 14 | floodfill(i, j - 1) 15 | if j < col - 1: 16 | floodfill(i, j + 1) 17 | 18 | res = 0 19 | for i in range(row): 20 | for j in range(col): 21 | if grid[i][j] == '1' and self.visited[i][j] == False: 22 | res += 1 23 | floodfill(i, j) 24 | return res -------------------------------------------------------------------------------- /algorithms/java/src/searchInsertPosition/searchInsertPositionTest.java: -------------------------------------------------------------------------------- 1 | package searchInsertPosition; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 3/10/15. 9 | */ 10 | public class searchInsertPositionTest { 11 | 12 | @Test 13 | public void testSearchInsert() throws Exception { 14 | int [][] inputs = { 15 | {1,3,5,6}, 16 | {1,3,5,6}, 17 | {1,3,5,6}, 18 | {1,3,5,6}, 19 | }; 20 | int[] targets = {5,2,7,0}; 21 | int[] results = {2,1,4,0}; 22 | searchInsertPosition s = new searchInsertPosition(); 23 | for (int i = 0; i < inputs.length; i++) { 24 | int r = s.searchInsert(inputs[i], targets[i]); 25 | System.out.println(r); 26 | assertEquals(results[i], r); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /algorithms/python/PathSumII/pathSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Method 1 3 | """ 4 | def pathSum(self, root, sum): 5 | if not root: return [] 6 | res = [] 7 | 8 | def dfs(root, sum, ls, res): 9 | if not root.left and not root.right and sum == root.val: 10 | ls.append(root.val) 11 | res.append(ls) 12 | if root.left: 13 | dfs(root.left, sum - root.val, ls + [root.val], res) 14 | if root.right: 15 | dfs(root.right, sum - root.val, ls + [root.val], res) 16 | 17 | dfs(root, sum, [], res) 18 | return res 19 | 20 | """ 21 | Method 2 22 | """ 23 | def pathSum(self, root, sum): 24 | if not root: return [] 25 | if not root.left and not root.right and root.val == sum: return [[root.val]] 26 | temp = self.pathSum(root.left, sum - root.val) + self.pathSum(root.right, sum - root.val) 27 | return [[root.val] + i for i in temp] -------------------------------------------------------------------------------- /algorithms/java/src/search2DMatrix/search2DMatrixTest.java: -------------------------------------------------------------------------------- 1 | package search2DMatrix; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 3/10/15. 9 | */ 10 | public class search2DMatrixTest { 11 | 12 | @Test 13 | public void testSearchMatrix() throws Exception { 14 | int[][][] inputes = { 15 | { 16 | {1,3,5,7}, 17 | {10,11,16,20}, 18 | {23,30,34,50}, 19 | }, 20 | }; 21 | int[] targets = {3}; 22 | boolean[] outputs = {true}; 23 | 24 | search2DMatrix s = new search2DMatrix(); 25 | for (int i = 0; i < targets.length; i++) { 26 | boolean r = s.searchMatrix(inputes[i], targets[i]); 27 | System.out.println(r); 28 | assertEquals(outputs[i], r); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /algorithms/python/SerializeAndDeserializeBST/serialize.py: -------------------------------------------------------------------------------- 1 | class Codec: 2 | 3 | def serialize(self, root): 4 | preorder = [] 5 | 6 | def helper(node): 7 | if node: 8 | preorder.append(node.val) 9 | helper(node.left) 10 | helper(node.right) 11 | helper(root) 12 | return ' '.join(map(str, preorder)) 13 | 14 | 15 | def deserialize(self, data): 16 | vals = collections.deque(int(val) for val in data.split()) 17 | 18 | def build(minval, maxval): 19 | if vals and minval < vals[0] < maxval: 20 | val = vals.popleft() 21 | node = TreeNode(val) 22 | node.left = build(minval, val) 23 | node.right = build(val, maxval) 24 | return node 25 | 26 | return build(float('-infinity'), float('infinity')) -------------------------------------------------------------------------------- /algorithms/cpp/containsDuplicate/ContainsDuplicate.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate/ 2 | // Author : Hao Chen 3 | // Date : 2015-06-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of integers, find if the array contains any duplicates. 8 | * Your function should return true if any value appears at least twice in the array, 9 | * and it should return false if every element is distinct. 10 | * 11 | **********************************************************************************/ 12 | 13 | 14 | class Solution { 15 | public: 16 | bool containsDuplicate(vector& nums) { 17 | unordered_map m; 18 | for (auto item : nums) { 19 | if (m.find(item) != m.end()) return true; 20 | m[item]=true; 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArrayTest.java: -------------------------------------------------------------------------------- 1 | package findMinimumInRotatedSortedArray; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 5/10/15. 9 | */ 10 | public class findMinimumInRotatedSortedArrayTest { 11 | 12 | @Test 13 | public void testFindMin() throws Exception { 14 | int[][] inputs = { 15 | {4,5,6,7,0,1,2}, 16 | {1,2,3}, 17 | {2,3,1}, 18 | {1,2,3,4}, 19 | {2,3,4,1} 20 | }; 21 | 22 | int [] results = {0,1,1,1,1}; 23 | 24 | findMinimumInRotatedSortedArray f = new findMinimumInRotatedSortedArray(); 25 | for (int i = 0; i < results.length; i++) { 26 | int r = f.findMin(inputs[i]); 27 | System.out.println(results[i]); 28 | assertEquals(results[i], r); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /algorithms/python/SumRootToLeafNumbers/sumNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Method 1: dfs 3 | """ 4 | def sumNumbers(self, root): 5 | if not root: return 0 6 | stack, res = [(root, root.val)], 0 7 | while stack: 8 | node, value = stack.pop() 9 | if not node.left and not node.right: 10 | res += value 11 | if node.right: 12 | stack.append((node.right, value * 10 + node.right.val)) 13 | if node.left: 14 | stack.append((node.left, value * 10 + node.left.val)) 15 | return res 16 | 17 | 18 | 19 | """ 20 | Method 2: recursive solution 21 | """ 22 | def sumNumbers(self, root): 23 | return self.helper(root, 0) 24 | 25 | def helper(self, node, s): 26 | if not node: return 0 27 | if not node.left and not node.right: return s * 10 + node.val 28 | return self.helper(node.left, s * 10 + node.val) + \ 29 | self.helper(node.right, s * 10 + node.val) -------------------------------------------------------------------------------- /algorithms/python/ValidateBinarySearchTree/isValidBST.py: -------------------------------------------------------------------------------- 1 | # method 1: using recursion 2 | 3 | def isValidBST1(self, root, lower = float('-inf'), upper = float('inf')): 4 | """ 5 | :type root: TreeNode 6 | :rtype: bool 7 | """ 8 | if not root: return True 9 | if root.val <= lower or root.val >= upper: return False 10 | return self.isValidBST(root.left, lower, min(upper, root.val)) \ 11 | and self.isValidBST(root.right, max(lower, root.val), upper) 12 | 13 | 14 | # method 2: a proper BST should have this porperty: inorder traversal is increasing 15 | def isValidBST2(self, root): 16 | inorder = [] 17 | def helper(root): 18 | if root: 19 | helper(root.left) 20 | inorder.append(root.val) 21 | helper(root.right) 22 | 23 | helper(root) 24 | for i in range(len(inorder) - 1): 25 | if inorder[i + 1] <= inorder[i]: return False 26 | return True -------------------------------------------------------------------------------- /algorithms/java/src/removeDuplicatesFromSortedArray/TestRemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | package removeDuplicatesFromSortedArray; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 26. Remove Duplicates from Sorted Array 8 | */ 9 | public class TestRemoveDuplicates { 10 | @Test 11 | public void test() { 12 | int[] nums1 = {0, 0, 0, 0, 0, 1, 2, 2, 3, 3, 4, 4}; 13 | RemoveDuplicatesFromSortedArray solution = new RemoveDuplicatesFromSortedArray(); 14 | int len1 = solution.removeDuplicates(nums1); 15 | Assert.assertTrue(len1 == 5); 16 | assertSorted(nums1, len1); 17 | int[] nums2 = {1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8}; 18 | int len2 = solution.removeDuplicates(nums2); 19 | Assert.assertTrue(len2 == 8); 20 | assertSorted(nums2, len2); 21 | } 22 | private void assertSorted(int[] array, int len) { 23 | for (int i = 0; i < len - 1; i++) { 24 | Assert.assertTrue(array[i] < array[i + 1]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/python/HappyNumber/isHappy.py: -------------------------------------------------------------------------------- 1 | # Method 1: straight forward solution, use a set to track if there is a cycle 2 | 3 | def isHappy1(self, n): 4 | if n <= 0: return False 5 | s = set() 6 | while n not in s: 7 | s.add(n) 8 | n = sum([int(i) ** 2 for i in str(n)]) 9 | if n == 1: return True 10 | return False 11 | 12 | # Method 2: using a slow and fast pointer to determine cycle (like in linked list) 13 | # No extra space needed 14 | def isHappy2(self, n): 15 | """ 16 | :type n: int 17 | :rtype: bool 18 | """ 19 | if n <= 0: return False 20 | def helper(n): 21 | res = 0 22 | while n: 23 | res += (n % 10) ** 2 24 | n = n // 10 25 | return res 26 | 27 | slow = fast = n 28 | while True: 29 | slow = helper(slow) 30 | fast = helper(helper(fast)) 31 | if slow == 1: return True 32 | if slow == fast: break 33 | return False -------------------------------------------------------------------------------- /algorithms/cpp/numberOf1Bits/numberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-1-bits/ 2 | // Author : Hao Chen 3 | // Date : 2015-03-30 4 | 5 | /********************************************************************************** 6 | * 7 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has 8 | * (also known as the Hamming weight). 9 | * 10 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, 11 | * so the function should return 3. 12 | * 13 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 14 | * 15 | **********************************************************************************/ 16 | 17 | class Solution { 18 | public: 19 | int hammingWeight(uint32_t n) { 20 | int cnt = 0; 21 | for(;n>0; n/=2){ 22 | if (n & 0x1) cnt++; 23 | } 24 | return cnt; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreeBFSTraversal/binaryTreeBFSTraversal.java: -------------------------------------------------------------------------------- 1 | package binaryTreeBFSTraversal; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Queue; 7 | 8 | /** 9 | * Created by leicao on 5/10/15. 10 | */ 11 | public class binaryTreeBFSTraversal { 12 | public List bfsTraversal(TreeNode root) { 13 | List results = new ArrayList(); 14 | if (root == null) { 15 | return results; 16 | } 17 | 18 | Queue q = new LinkedList(); 19 | 20 | q.offer(root); 21 | while (q.size() != 0) { 22 | TreeNode n = q.remove(); 23 | results.add(n.val); 24 | if (n.left != null) { 25 | q.offer(n.left); 26 | } 27 | if (n.right != null) { 28 | q.offer(n.right); 29 | } 30 | } 31 | 32 | return results; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /algorithms/python/RedundantConnection/findRedundantConnection.py: -------------------------------------------------------------------------------- 1 | """ 2 | simple union find with path compression: 3 | at first, each vertices are disjoint, there are N connected components at the begining, 4 | after add each edge, we unify those two connected components, if two vertices are already 5 | in the same connected component, then this edge will form a circle, just return this edge 6 | """ 7 | 8 | def findRedundantConnection(self, edges): 9 | id = list(range(len(edges) + 1)) 10 | 11 | def find(u): 12 | root = u 13 | while root != id[root]: root = id[root] 14 | 15 | # path compression: 16 | while u != root: 17 | next = id[u] 18 | id[u] = root 19 | u = next 20 | 21 | return root 22 | 23 | for u, v in edges: 24 | root1, root2 = find(u), find(v) 25 | if root1 == root2: return [u, v] 26 | 27 | # else, unify these two components: 28 | id[root1] = root2 -------------------------------------------------------------------------------- /algorithms/java/src/searchInRotatedSortedArray/searchInRotatedSortedArrayTest.java: -------------------------------------------------------------------------------- 1 | package searchInRotatedSortedArray; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 3/10/15. 9 | */ 10 | public class searchInRotatedSortedArrayTest { 11 | 12 | @Test 13 | public void testSearch() throws Exception { 14 | 15 | int[][] inputes = { 16 | {1}, 17 | {1}, 18 | {6,8,9,1,3,5}, 19 | {1,2}, 20 | {2,1}, 21 | {4,5,6,7,0,1,2}, 22 | {0,1,2,4,5,6,7}, 23 | }; 24 | int[] targets = {0,1,5,2,2,6,6}; 25 | int[] results = {-1,0,5,1,0,2,5}; 26 | 27 | searchInRotatedSortedArray s = new searchInRotatedSortedArray(); 28 | for (int i = 0; i < inputes.length; i++) { 29 | int r = s.search(inputes[i], targets[i]); 30 | System.out.println(r); 31 | assertEquals(results[i], r); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /algorithms/cpp/climbStairs/climbStairs.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/climbing-stairs/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-27 4 | 5 | /********************************************************************************** 6 | * 7 | * You are climbing a stair case. It takes n steps to reach to the top. 8 | * 9 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 10 | * 11 | * 12 | **********************************************************************************/ 13 | 14 | class Solution { 15 | public: 16 | 17 | int climbStairs(int n) { 18 | if (n<=3) return n; 19 | int a[2]={2,3}; 20 | for(int i=4; i<=n; i++){ 21 | int t = a[0] + a[1]; 22 | a[0] = a[1]; 23 | a[1] = t; 24 | } 25 | return a[1]; 26 | } 27 | //Time too long 28 | int climbStairs2(int n) { 29 | if (n<=3) return n; 30 | return climbStairs(n-1) + climbStairs(n-2); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /algorithms/cpp/containsDuplicate/ContainsDuplicate.II.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-ii/ 2 | // Author : Hao Chen 3 | // Date : 2015-06-12 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of integers and an integer k, find out whether there there are 8 | * two distinct indices i and j in the array such that nums[i] = nums[j] and 9 | * the difference between i and j is at most k. 10 | * 11 | * 12 | **********************************************************************************/ 13 | 14 | class Solution { 15 | public: 16 | bool containsNearbyDuplicate(vector& nums, int k) { 17 | unordered_map m; 18 | for (int i=0; i 16 | // This is classical interview question 17 | // As we know, the same number XOR together will be 0, 18 | // So, XOR all of numbers, the result is the number which only appears once. 19 | int singleNumber(int A[], int n) { 20 | int s = 0; 21 | for(int i=0; i& citations) { 18 | int n = citations.size(); 19 | int low = 0, high = n-1; 20 | 21 | while( low <= high ) { 22 | int mid = low + (high-low)/2; 23 | if (citations[mid] == n - mid) { 24 | return n - mid; 25 | }else if (citations[mid] > n-mid){ 26 | high = mid - 1; 27 | }else { 28 | low = mid + 1; 29 | } 30 | } 31 | return n-low; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /algorithms/python/BinarySearchTreeIterator/BSTIterator.py: -------------------------------------------------------------------------------- 1 | # straight forward solution: do a inorder traversal 2 | 3 | class BSTIterator(object): 4 | def __init__(self, root): 5 | self.inorder = [] 6 | def helper(root): 7 | if root: 8 | helper(root.left) 9 | self.inorder.append(root.val) 10 | helper(root.right) 11 | helper(root) 12 | 13 | def hasNext(self): 14 | return len(self.inorder) != 0 15 | 16 | def next(self): 17 | return self.inorder.pop(0) 18 | 19 | # Alternative solution: 20 | class BSTIterator(object): 21 | def __init__(self, root): 22 | self.stack = [] 23 | while root: 24 | self.stack.append(root) 25 | root = root.left 26 | 27 | 28 | def hasNext(self): 29 | return len(self.stack) != 0 30 | 31 | 32 | def next(self): 33 | node = self.stack.pop() 34 | x = node.right 35 | while x: 36 | self.stack.append(x) 37 | x = x.left 38 | return node.val 39 | -------------------------------------------------------------------------------- /shell/TransposeFile.sh: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/transpose-file/ 2 | # Author : Hao Chen 3 | # Date : 2015-03-31 4 | 5 | ################################################################################## 6 | # 7 | # Given a text file file.txt, transpose its content. 8 | # 9 | # You may assume that each row has the same number of columns and each field is separated by the ' ' character. 10 | # 11 | # For example, if file.txt has the following content: 12 | # 13 | # name age 14 | # alice 21 15 | # ryan 30 16 | # 17 | # Output the following: 18 | # 19 | # name alice ryan 20 | # age 21 30 21 | ################################################################################## 22 | 23 | #!/bin/sh 24 | 25 | # Read from the file file.txt and print its transposed content to stdout. 26 | awk ' 27 | { 28 | for (i = 1; i <= NF; i++) { 29 | if (NR == 1){ 30 | s[i]=$i; 31 | }else{ 32 | s[i] = s[i] " " $i; 33 | } 34 | } 35 | } 36 | END { 37 | for (i = 1; s[i] != ""; i++) { 38 | print s[i]; 39 | } 40 | }' file.txt 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /algorithms/cpp/findTheDifference/FindTheDifference.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-the-difference/ 2 | // Author : Hao Chen 3 | // Date : 2016-09-08 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given two strings s and t which consist of only lowercase letters. 8 | * 9 | * String t is generated by random shuffling string s and then add one more letter at a 10 | * random position. 11 | * 12 | * Find the letter that was added in t. 13 | * 14 | * Example: 15 | * 16 | * Input: 17 | * s = "abcd" 18 | * t = "abcde" 19 | * 20 | * Output: 21 | * e 22 | * 23 | * Explanation: 24 | * 'e' is the letter that was added. 25 | ***************************************************************************************/ 26 | 27 | class Solution { 28 | public: 29 | char findTheDifference(string s, string t) { 30 | unordered_map m; 31 | for(auto c : s) m[c]++; 32 | for(auto c : t) { 33 | m[c]--; 34 | if (m[c] < 0) return c; 35 | } 36 | return '\0'; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /algorithms/cpp/reverseBits/reverseBits.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-bits/ 2 | // Author : Hao Chen 3 | // Date : 2015-03-30 4 | 5 | /********************************************************************************** 6 | * 7 | * Reverse bits of a given 32 bits unsigned integer. 8 | * 9 | * For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 10 | * return 964176192 (represented in binary as 00111001011110000010100101000000). 11 | * 12 | * Follow up: 13 | * If this function is called many times, how would you optimize it? 14 | * 15 | * Related problem: Reverse Integer 16 | * 17 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 18 | * 19 | **********************************************************************************/ 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | uint32_t reverseBits(uint32_t n) { 26 | uint32_t ret=0; 27 | for(int i=0; i<32; i++) { 28 | ret = (ret*2) + (n & 0x1); 29 | n /=2 ; 30 | } 31 | return ret; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseWordsInAString/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-words-in-a-string/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an input string, reverse the string word by word. 8 | * 9 | * For example, 10 | * Given s = "the sky is blue", 11 | * return "blue is sky the". 12 | * 13 | * Update (2015-02-12): 14 | * For C programmers: Try to solve it in-place in O(1) space. 15 | * 16 | **********************************************************************************/ 17 | package reverseWordsInAString; 18 | 19 | public class ReverseWordsInAString { 20 | 21 | public String reverseWords(String s) { 22 | if (s == null || s.length() == 0) { 23 | return s; 24 | } 25 | s = s.trim(); 26 | String[] array = s.split("\\s+"); 27 | StringBuilder sb = new StringBuilder(); 28 | int len = array.length; 29 | for (int i = len - 1; i > 0; i--) { 30 | sb.append(array[i]).append(" "); 31 | } 32 | sb.append(array[0]); 33 | return sb.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-22 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a sorted array, remove the duplicates in place such that each element appear 8 | * only once and return the new length. 9 | * 10 | * Do not allocate extra space for another array, you must do this in place with constant memory. 11 | * 12 | * For example, 13 | * Given input array A = [1,1,2], 14 | * 15 | * Your function should return length = 2, and A is now [1,2]. 16 | * 17 | * 18 | **********************************************************************************/ 19 | 20 | class Solution { 21 | public: 22 | int removeDuplicates(int A[], int n) { 23 | 24 | if (n<=1) return n; 25 | 26 | int pos=0; 27 | for(int i=0; i 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "sentenceScreenFitting.h" 15 | #define N 100 16 | #define M 10 17 | 18 | using std::vector; 19 | 20 | int main(int argc, const char * argv[]) { 21 | int rows, cols, ret; 22 | // int i=0; 23 | // char stc[N][M]; 24 | vector sentence; 25 | std::string word; 26 | std::string line; 27 | std::stringstream numbers, split; 28 | 29 | std::getline(std::cin, line); 30 | numbers << line; 31 | numbers >> rows >> cols; 32 | std::getline(std::cin, line); 33 | split << line; 34 | 35 | while (split >> word){ 36 | sentence.push_back(word); 37 | // strcpy(stc[i++], word.c_str()); 38 | } 39 | 40 | Solution solution; 41 | ret = solution.wordsTyping(sentence, rows, cols); 42 | // ret = SentenceScreenFitting(stc, rows, cols, i); 43 | std::cout << ret << std::endl; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/python/HouseRobberIII/rob.py: -------------------------------------------------------------------------------- 1 | """ 2 | Answe inspired by the post from here: 3 | https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem 4 | """ 5 | # Method 1: dynamic programming solution: 6 | def rob1(self, root): 7 | lookup = {} 8 | def helper(root): 9 | if not root: return 0 10 | if root in lookup: return lookup[root] 11 | val = 0 12 | 13 | if root.left: 14 | val += helper(root.left.left) + helper(root.left.right) 15 | if root.right: 16 | val += helper(root.right.left) + helper(root.right.right) 17 | val = max(val + root.val, helper(root.left) + helper(root.right)) 18 | lookup[root] = val 19 | return val 20 | return helper(root) 21 | 22 | # Method 2: Greedy approach: 23 | def rob2(self, root): 24 | def helper(root): 25 | if not root: return [0, 0] 26 | left, right = helper(root.left), helper(root.right) 27 | not_robbed = max(left) + max(right) 28 | robbed = root.val + left[0] + right[0] 29 | return [not_robbed, robbed] 30 | return max(helper(root)) -------------------------------------------------------------------------------- /algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | // Author : Hao Chen 3 | // Date : 2015-07-17 4 | 5 | /********************************************************************************** 6 | * 7 | * Write a function to delete a node (except the tail) in a singly linked list, given 8 | * only access to that node. 9 | * 10 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with 11 | * value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 12 | * 13 | **********************************************************************************/ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | //becasue the deleted is not the tail. 26 | //So, we can move the content of next node to this one, and delete the next one 27 | void deleteNode(ListNode* node) { 28 | node->val = node->next->val; 29 | node->next = node->next->next; 30 | } 31 | }; 32 | 33 | 34 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedList/ListNode.java: -------------------------------------------------------------------------------- 1 | package reverseLinkedList; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | public ListNode(int x) { 7 | val = x; 8 | } 9 | @Override 10 | public String toString() { 11 | return "ListNode [val=" + val + "]"; 12 | } 13 | public ListNode(int val, ListNode next) { 14 | super(); 15 | this.val = val; 16 | this.next = next; 17 | } 18 | /** 19 | * This is an assistant function, use it, we can easily see the structure of list 20 | */ 21 | public static String listToString(ListNode head) { 22 | if (head == null) { 23 | return ""; 24 | } 25 | StringBuilder sb = new StringBuilder(); 26 | while (head.next != null) { 27 | sb.append(head.val).append(","); 28 | head = head.next; 29 | } 30 | sb.append(head.val); 31 | return sb.toString(); 32 | } 33 | 34 | /** 35 | * This is an assistant function, use it, we can create a linkedList by array. 36 | */ 37 | public static ListNode arrayToList(int[] array) { 38 | ListNode head = new ListNode(0); 39 | ListNode p = head; 40 | for (int i : array) { 41 | p.next = new ListNode(i); 42 | p = p.next; 43 | } 44 | return head.next; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedListII/ListNode.java: -------------------------------------------------------------------------------- 1 | package reverseLinkedListII; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | public ListNode(int x) { 7 | val = x; 8 | } 9 | @Override 10 | public String toString() { 11 | return "ListNode [val=" + val + "]"; 12 | } 13 | public ListNode(int val, ListNode next) { 14 | super(); 15 | this.val = val; 16 | this.next = next; 17 | } 18 | /** 19 | * This is an assistant function, use it, we can easily see the structure of list 20 | */ 21 | public static String listToString(ListNode head) { 22 | if (head == null) { 23 | return ""; 24 | } 25 | StringBuilder sb = new StringBuilder(); 26 | while (head.next != null) { 27 | sb.append(head.val).append(","); 28 | head = head.next; 29 | } 30 | sb.append(head.val); 31 | return sb.toString(); 32 | } 33 | 34 | /** 35 | * This is an assistant function, use it, we can create a linkedList by array. 36 | */ 37 | public static ListNode arrayToList(int[] array) { 38 | ListNode head = new ListNode(0); 39 | ListNode p = head; 40 | for (int i : array) { 41 | p.next = new ListNode(i); 42 | p = p.next; 43 | } 44 | return head.next; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /algorithms/java/src/searchInABigSortedArray/searchInABigSortedArrayTest.java: -------------------------------------------------------------------------------- 1 | package searchInABigSortedArray; 2 | 3 | import org.junit.Test; 4 | import searchInsertPosition.searchInsertPosition; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | /** 9 | * Created by leicao on 5/10/15. 10 | */ 11 | public class searchInABigSortedArrayTest { 12 | 13 | @Test 14 | public void testSearchBigSortedArray() throws Exception { 15 | int [][] inputs = { 16 | {1,2,3,4}, 17 | {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, 18 | 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, 19 | 17,17,17,17,17,18,18,19,19,19,19,20,20,20,20,20,20,20,20,20}, 20 | }; 21 | int[] targets = {3, 4}; 22 | int[] results = {2, 9}; 23 | searchInABigSortedArray s = new searchInABigSortedArray(); 24 | for (int i = 0; i < inputs.length; i++) { 25 | int r = s.searchBigSortedArray(inputs[i], targets[i]); 26 | System.out.println(r); 27 | assertEquals(results[i], r); 28 | } 29 | 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /algorithms/java/src/dynamicProgramming/climbStairs/climbStairs.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/climbing-stairs/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/climbing-stairs/ 3 | // Author : Lei Cao 4 | // Date : 2015-10-12 5 | 6 | /********************************************************************************** 7 | * 8 | * You are climbing a stair case. It takes n steps to reach to the top. 9 | * 10 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 11 | * 12 | * 13 | **********************************************************************************/ 14 | 15 | package dynamicProgramming.climbStairs; 16 | 17 | public class climbStairs { 18 | /** 19 | * @param n: An integer 20 | * @return: An integer 21 | */ 22 | public int climbStairs(int n) { 23 | int[] matrix = new int[n]; 24 | if (n < 3) { 25 | return n; 26 | } 27 | matrix[0] = 1; 28 | matrix[1] = 2; 29 | // write your code here 30 | for (int i = 2; i < matrix.length; i++) { 31 | matrix[i] = matrix[i-1] + matrix[i-2]; 32 | } 33 | return matrix[n-1]; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /scripts/readme.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pushd `dirname $0` > /dev/null 4 | SCRIPTPATH=`pwd -P` 5 | popd > /dev/null 6 | SCRIPTFILE=`basename $0` 7 | 8 | COLOR_INFO='\033[0;36m' 9 | COLOR_NONE='\033[0m' 10 | 11 | source ${SCRIPTPATH}/lib/query_problem.sh 12 | 13 | function usage() 14 | { 15 | 16 | echo -e "Usage: ${0} [file]" 17 | echo -e "" 18 | echo -e "Example:" 19 | echo -e "" 20 | echo -e " ${0} ./LargestNumber.cpp" 21 | echo -e "" 22 | } 23 | 24 | 25 | 26 | if [ $# -lt 1 ] || [[ ! -f ${1} ]]; then 27 | usage 28 | exit 255 29 | fi 30 | 31 | DIR=`cd $(dirname ${1}) && pwd -P` 32 | FILE=${DIR}/$(basename ${1}) 33 | 34 | URL=`grep Source ${FILE} | awk '{print $4}'` 35 | 36 | URL=$(echo $URL | sed -e 's/oj\.leetcode\.com/leetcode\.com/g') 37 | 38 | get_question_slug ${URL} 39 | query_problem ${URL} ${QUESTION_TITLE_SLUG} 40 | 41 | #echo "$QUESTION_CONTENT" 42 | #echo $QUESTION_DIFFICULTY 43 | #echo $QUESTION_TITLE 44 | #echo $QUESTION_ID 45 | #echo $QUESTION_FRONTEND_ID 46 | #echo $QUESTION_CATEGORY 47 | 48 | 49 | FILE=`echo ${FILE} | sed "s/.*\/algorithms/\.\/algorithms/"` 50 | 51 | echo "|${QUESTION_FRONTEND_ID}|[${QUESTION_TITLE}](${URL}) | [C++](${FILE})|${QUESTION_DIFFICULTY}|" 52 | -------------------------------------------------------------------------------- /algorithms/python/DeleteNodeInABST/deleteNode.py: -------------------------------------------------------------------------------- 1 | """ 2 | case 1: if node we want to delete has no children: simply delete it 3 | case 2: if it has only one child, then replace it with its child 4 | case 3: if it has two children, first find the inorder successor (or predecessor), 5 | then replace the node's value with successor's value, and finally delete this successor 6 | """ 7 | 8 | def deleteNode(self, root, key): 9 | if not root: return None 10 | if key < root.val: 11 | root.left = self.deleteNode(root.left, key) 12 | elif key > root.val: 13 | root.right = self.deleteNode(root.right, key) 14 | else: 15 | # if this node has only one child or no child: 16 | if not root.left: 17 | temp = root.right 18 | root = None 19 | return temp 20 | elif not root.right: 21 | temp = root.left 22 | root = None 23 | return temp 24 | 25 | # otherwise, find the inorder successor: 26 | curr = root.right 27 | while curr.left: 28 | curr = curr.left 29 | 30 | root.val = curr.val 31 | root.right = self.deleteNode(root.right, curr.val) 32 | return root -------------------------------------------------------------------------------- /algorithms/cpp/removeElement/removeElement.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/remove-element/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-19 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array and a value, remove all instances of that value in place and return the new length. 8 | * 9 | * The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | * 11 | * 12 | **********************************************************************************/ 13 | 14 | class Solution { 15 | public: 16 | int removeElement(vector& nums, int val) { 17 | int pos = 0; 18 | for (int i=0; i target: high = mid - 1 9 | else: return True 10 | return False 11 | 12 | if not matrix or not matrix[0]: return False 13 | for i in range(len(matrix)): 14 | if matrix[i][0] > target: return False 15 | elif matrix[i][0] == target: return True 16 | if helper(0, len(matrix[i]) - 1, i): return True 17 | return False 18 | 19 | # Method 2: compare the element with top-right corner, and reduce the search range 20 | # Time complexity: O(m + n) 21 | def searchMatrix2(self, matrix, target): 22 | if not matrix or not matrix[0]: return False 23 | row, col = 0, len(matrix[0]) - 1 24 | while row < len(matrix) and col >= 0: 25 | if matrix[row][col] > target: col -= 1 26 | elif matrix[row][col] < target: row += 1 27 | else: return True 28 | return False -------------------------------------------------------------------------------- /algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sum-of-two-integers/description/ 2 | // Author : Hao Chen 3 | // Date : 2018-06-25 4 | 5 | /*************************************************************************************** 6 | * 7 | * Calculate the sum of two integers a and b, but you are not allowed to use the 8 | * operator + and -. 9 | * 10 | * Example: 11 | * Given a = 1 and b = 2, return 3. 12 | * 13 | * 14 | * Credits:Special thanks to @fujiaozhu for adding this problem and creating all test 15 | * cases. 16 | ***************************************************************************************/ 17 | 18 | class Solution { 19 | public: 20 | int getSum(int x, int y) { 21 | // Iterate till there is no carry 22 | while (y != 0) { 23 | // carry now contains common 24 | //set bits of x and y 25 | int carry = x & y; 26 | 27 | // Sum of bits of x and y where at 28 | //least one of the bits is not set 29 | x = x ^ y; 30 | 31 | // Carry is shifted by one so that adding 32 | // it to x gives the required sum 33 | y = carry << 1; 34 | } 35 | return x; 36 | } 37 | }; 38 | 39 | -------------------------------------------------------------------------------- /algorithms/java/src/strStr/strStr.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/implement-strstr/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/implement-strstr/ 3 | // Author : Lei Cao 4 | // Date : 2015-10-02 5 | 6 | /********************************************************************************** 7 | * 8 | * Implement strStr(). 9 | * 10 | * Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 11 | * 12 | * 13 | **********************************************************************************/ 14 | 15 | package strStr; 16 | 17 | /** 18 | * Created by leicao on 2/10/15. 19 | */ 20 | public class strStr { 21 | public int strStr(String haystack, String needle) { 22 | if (haystack == null || needle == null) { 23 | return -1; 24 | } 25 | int i, j = 0; 26 | for (i = 0; i < haystack.length() - needle.length() + 1; i++) { 27 | for (j = 0; j < needle.length(); j++) { 28 | if (haystack.charAt(i + j) != needle.charAt(j)) { 29 | break; 30 | } 31 | } 32 | if (j == needle.length()) { 33 | return i; 34 | } 35 | } 36 | return -1; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /algorithms/cpp/powerOfFour/PowerOfFour.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-four/ 2 | // Author : Hao Chen 3 | // Date : 2016-05-29 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given an integer (signed 32 bits), write a function to check whether it is a power 8 | * of 4. 9 | * 10 | * Example: 11 | * Given num = 16, return true. 12 | * Given num = 5, return false. 13 | * 14 | * Follow up: Could you solve it without loops/recursion? 15 | * 16 | * Credits:Special thanks to @yukuairoy for adding this problem and creating all test 17 | * cases. 18 | ***************************************************************************************/ 19 | 20 | 21 | class Solution { 22 | public: 23 | bool isPowerOfFour(int num) { 24 | static int mask = 0b01010101010101010101010101010101; 25 | 26 | //edge case 27 | if (num<=0) return false; 28 | 29 | // there are multiple bits are 1 30 | if ((num & num-1) != 0) return false; 31 | 32 | // check which one bit is zero, if the place is 1 or 3 or 5 or 7 or 9..., 33 | // then it is the power of 4 34 | if ((num & mask) != 0) return true; 35 | return false; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /algorithms/java/src/lruCache/LRUCacheTest.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | public class LRUCacheTest { 7 | 8 | private LRUCache c; 9 | 10 | public LRUCacheTest() { 11 | this.c = new LRUCache(2); 12 | } 13 | 14 | @Test 15 | public void testCacheStartsEmpty() { 16 | assertEquals(c.get(1), -1); 17 | } 18 | 19 | @Test 20 | public void testSetBelowCapacity() { 21 | c.set(1, 1); 22 | assertEquals(c.get(1), 1); 23 | assertEquals(c.get(2), -1); 24 | c.set(2, 4); 25 | assertEquals(c.get(1), 1); 26 | assertEquals(c.get(2), 4); 27 | } 28 | 29 | @Test 30 | public void testCapacityReachedOldestRemoved() { 31 | c.set(1, 1); 32 | c.set(2, 4); 33 | c.set(3, 9); 34 | assertEquals(c.get(1), -1); 35 | assertEquals(c.get(2), 4); 36 | assertEquals(c.get(3), 9); 37 | } 38 | 39 | @Test 40 | public void testGetRenewsEntry() { 41 | c.set(1, 1); 42 | c.set(2, 4); 43 | assertEquals(c.get(1), 1); 44 | c.set(3, 9); 45 | assertEquals(c.get(1), 1); 46 | assertEquals(c.get(2), -1); 47 | assertEquals(c.get(3), 9); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/length-of-last-word/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 8 | * 9 | * If the last word does not exist, return 0. 10 | * 11 | * Note: A word is defined as a character sequence consists of non-space characters only. 12 | * 13 | * Example: 14 | * 15 | * Input: "Hello World" 16 | * Output: 5 17 | * 18 | **********************************************************************************/ 19 | package lengthOfLastWord; 20 | 21 | public class LengthOfLastWord { 22 | 23 | public int lengthOfLastWord(String s) { 24 | // don't forget rangeCheck 25 | if (s == null || s.length() == 0) { 26 | return 0; 27 | } 28 | int len = s.length(); 29 | int i = len - 1; 30 | while (i >= 0 && s.charAt(i) == ' ') { 31 | i--; 32 | } 33 | if (i == -1) { 34 | return 0; 35 | } 36 | int count = 0; 37 | while (i >= 0 && s.charAt(i) != ' ') { 38 | count++; 39 | i--; 40 | } 41 | return count; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /algorithms/cpp/integerToRoman/integerToRoman.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/integer-to-roman/ 2 | // Author : Hao Chen 3 | // Date : 2014-07-17 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an integer, convert it to a roman numeral. 8 | * 9 | * Input is guaranteed to be within the range from 1 to 3999. 10 | * 11 | **********************************************************************************/ 12 | 13 | #include 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | //greeding algorithm 19 | string intToRoman(int num) { 20 | string symbol[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 21 | int value[] = {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 22 | string result; 23 | 24 | for(int i=0; num!=0; i++){ 25 | while(num >= value[i]){ 26 | num -= value[i]; 27 | result+=symbol[i]; 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | 34 | 35 | int main(int argc, char** argv) 36 | { 37 | int num = 1234; 38 | if (argc>0){ 39 | num = atoi(argv[1]); 40 | } 41 | 42 | cout << num << " : " << intToRoman(num) << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /algorithms/java/src/balancedBinaryTree/balancedBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package balancedBinaryTree; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | /** 9 | * Created by leicao on 7/10/15. 10 | */ 11 | public class balancedBinaryTreeTest { 12 | 13 | @Test 14 | public void testIsBalanced() throws Exception { 15 | ArrayList inputes = new ArrayList(); 16 | boolean[] results = {false, false}; 17 | TreeNode n0 = new TreeNode(0); 18 | TreeNode n1 = new TreeNode(1); 19 | TreeNode n2 = new TreeNode(2); 20 | TreeNode n3 = new TreeNode(3); 21 | 22 | n0.left = n1; 23 | n1.left = n2; 24 | n2.left = n3; 25 | 26 | TreeNode nn0 = new TreeNode(0); 27 | TreeNode nn1 = new TreeNode(1); 28 | TreeNode nn2 = new TreeNode(2); 29 | TreeNode nn3 = new TreeNode(3); 30 | nn0.right = nn1; 31 | nn1.left = nn2; 32 | nn2.left = nn3; 33 | 34 | inputes.add(n0); 35 | inputes.add(nn0); 36 | 37 | for (int i = 0; i < results.length; i++) { 38 | balancedBinaryTree b = new balancedBinaryTree(); 39 | assertEquals(results[i], b.isBalanced(inputes.get(i))); 40 | } 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIteratorTest.java: -------------------------------------------------------------------------------- 1 | package binarySearchTreeIterator; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by leicao on 11/10/15. 11 | */ 12 | public class binarySearchTreeIteratorTest { 13 | @Test 14 | public void testIterator() throws Exception { 15 | ArrayList inputs = new ArrayList(); 16 | TreeNode t0 = new TreeNode(10); 17 | TreeNode t1 = new TreeNode(1); 18 | TreeNode t2 = new TreeNode(11); 19 | TreeNode t3 = new TreeNode(6); 20 | TreeNode t4 = new TreeNode(12); 21 | t0.left = t1; 22 | t0.right = t2; 23 | t1.right = t3; 24 | t2.right = t4; 25 | 26 | inputs.add(t0); 27 | 28 | int[][] results = { 29 | {1,6,10,11,12} 30 | }; 31 | 32 | for (int i = 0; i < results.length; i++) { 33 | binarySearchTreeIterator it = new binarySearchTreeIterator(inputs.get(i)); 34 | int j = 0; 35 | while (it.hasNext()) { 36 | TreeNode r = it.next(); 37 | assertEquals(results[i][j], r.val); 38 | j++; 39 | } 40 | } 41 | 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /algorithms/cpp/uglyNumber/UglyNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number/ 2 | // Author : Hao Chen 3 | // Date : 2015-10-21 4 | 5 | /*************************************************************************************** 6 | * 7 | * Write a program to check whether a given number is an ugly number. 8 | * 9 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For 10 | * example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 11 | * 12 | * Note that 1 is typically treated as an ugly number. 13 | * 14 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 15 | * all test cases. 16 | * 17 | ***************************************************************************************/ 18 | 19 | class Solution { 20 | public: 21 | //greeting algorithm 22 | bool isUgly(int num) { 23 | if ( num == 0 ) return false; 24 | if ( num == 1 ) return true; 25 | //becasue the 2,3,5 are prime numbers, so, we just simply remove each factors 26 | //by keeping dividing them one by one 27 | while ( num % 2 == 0 ) num /= 2; 28 | while ( num % 3 == 0 ) num /= 3; 29 | while ( num % 5 == 0 ) num /= 5; 30 | 31 | return num == 1; 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/longest-common-prefix/ 2 | // Author : Hao Chen 3 | // Date : 2014-07-03 4 | 5 | /********************************************************************************** 6 | * 7 | * Write a function to find the longest common prefix string amongst an array of strings. 8 | * 9 | * 10 | **********************************************************************************/ 11 | 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | 18 | string longestCommonPrefix(vector &strs) { 19 | string word; 20 | if (strs.size()<=0) return word; 21 | for(int i=1; i<=strs[0].size(); i++){ 22 | string w = strs[0].substr(0, i); 23 | bool match = true; 24 | int j=1; 25 | for(j=1; jstrs[j].size() || w!=strs[j].substr(0, i) ) { 27 | match=false; 28 | break; 29 | } 30 | } 31 | if (!match) { 32 | return word; 33 | } 34 | word = w; 35 | } 36 | return word; 37 | } 38 | 39 | int main() 40 | { 41 | const char* s[]={"abab","aba","abc"}; 42 | vector v(s, s+3); 43 | cout << longestCommonPrefix(v) < 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | vector getRow(int rowIndex) { 24 | vector v(rowIndex+1, 0); 25 | v[0]=1; 26 | 27 | for (int i=0; i0; j--){ 29 | v[j] += v[j-1]; 30 | } 31 | } 32 | return v; 33 | 34 | } 35 | 36 | void printVector( vector pt) 37 | { 38 | cout << "{ "; 39 | for(int j=0; j1) { 49 | n = atoi(argv[1]); 50 | } 51 | printVector(getRow(n)); 52 | } 53 | -------------------------------------------------------------------------------- /algorithms/cpp/eliminationGame/EliminationGame.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/elimination-game 2 | // Author : Hao Chen 3 | // Date : 2016-09-07- 4 | 5 | /********************************************************************************** 6 | * 7 | * There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other 8 | * number afterward until you reach the end of the list. 9 | * 10 | * Repeat the previous step again, but this time from right to left, remove the right most number and every other number 11 | * from the remaining numbers. 12 | * 13 | * We keep repeating the steps again, alternating left to right and right to left, until a single number remains. 14 | * 15 | * Find the last number that remains starting with a list of length n. 16 | * 17 | * Example: 18 | * 19 | * Input: 20 | * n = 9, 21 | * 1 2 3 4 5 6 7 8 9 22 | * 2 4 6 8 23 | * 2 6 24 | * 6 25 | * 26 | * Output: 27 | * 6 28 | **********************************************************************************/ 29 | 30 | class Solution { 31 | public: 32 | int lastRemaining(int n) { 33 | int start = 1, step = 1; 34 | while (n > 1) { 35 | start += step + (n-2)/2 * 2*step; 36 | n /= 2; 37 | step *= -2; 38 | } 39 | return start; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /algorithms/cpp/jumpGame/jumpGame.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/jump-game/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-27 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 8 | * 9 | * Each element in the array represents your maximum jump length at that position. 10 | * 11 | * Determine if you are able to reach the last index. 12 | * 13 | * For example: 14 | * A = [2,3,1,1,4], return true. 15 | * 16 | * A = [3,2,1,0,4], return false. 17 | * 18 | * 19 | **********************************************************************************/ 20 | 21 | class Solution { 22 | public: 23 | bool canJump(int A[], int n) { 24 | if (n<=0) return false; 25 | 26 | // the basic idea is traverse array, maintain the most far can go 27 | int coverPos=0; 28 | // the condition i<=coverPos means traverse all of covered position 29 | for(int i=0; i<=coverPos && i=n-1){ 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package maximumDepthOfBinaryTree; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by leicao on 5/10/15. 11 | */ 12 | public class maximumDepthOfBinaryTreeTest { 13 | 14 | @Test 15 | public void testMaxDepth() throws Exception { 16 | TreeNode t0 = new TreeNode(0); 17 | 18 | TreeNode n0 = new TreeNode(0); 19 | TreeNode n1 = new TreeNode(1); 20 | TreeNode n2 = new TreeNode(2); 21 | TreeNode n3 = new TreeNode(3); 22 | TreeNode n4 = new TreeNode(5); 23 | TreeNode n5 = new TreeNode(6); 24 | TreeNode n6 = new TreeNode(6); 25 | 26 | n0.left = n1; 27 | n0.right = n2; 28 | n1.left = n3; 29 | n1.right = n4; 30 | n4.left = n5; 31 | n2.right = n6; 32 | 33 | ArrayList inputes = new ArrayList(); 34 | inputes.add(t0); 35 | inputes.add(n0); 36 | int[] results = {1,3}; 37 | 38 | maximumDepthOfBinaryTree m = new maximumDepthOfBinaryTree(); 39 | for (int i = 0; i < results.length; i++) { 40 | int d = m.maxDepth(inputes.get(i)); 41 | System.out.println(d); 42 | assertEquals(results[i], d); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /shell/WordFrequency.sh: -------------------------------------------------------------------------------- 1 | # Source : https://leetcode.com/problems/word-frequency/ 2 | # Author : Hao Chen 3 | # Date : 2015-03-31 4 | 5 | ################################################################################## 6 | # 7 | # Write a bash script to calculate the frequency of each word in a text file words.txt. 8 | # 9 | # For simplicity sake, you may assume: 10 | # 11 | # words.txt contains only lowercase characters and space ' ' characters. 12 | # Each word must consist of lowercase characters only. 13 | # Words are separated by one or more whitespace characters. 14 | # 15 | # For example, assume that words.txt has the following content: 16 | # the day is sunny the the 17 | # the sunny is is 18 | # 19 | # Your script should output the following, sorted by descending frequency: 20 | # 21 | # the 4 22 | # is 3 23 | # sunny 2 24 | # day 1 25 | # 26 | # Note: 27 | # Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. 28 | # 29 | # [show hint] 30 | # Hint: 31 | # Could you write it in one-line using Unix pipes? 32 | ################################################################################## 33 | 34 | #!/bin/sh 35 | 36 | # Read from the file words.txt and output the word frequency list to stdout. 37 | cat words.txt | tr [:space:] "\n" | sed '/^$/d' | tr '[:upper:]' '[:lower:]'|sort|uniq -c|sort -nr | awk '{ print $2,$1}' 38 | 39 | -------------------------------------------------------------------------------- /algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package lowestCommonAncestorOfABinaryTree; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by leicao on 7/10/15. 11 | */ 12 | public class lowestCommonAncestorOfABinaryTreeTest { 13 | 14 | @Test 15 | public void testLowestCommonAncestor() throws Exception { 16 | ArrayList inputeRoots = new ArrayList(); 17 | ArrayList inputeAs = new ArrayList(); 18 | ArrayList inputeBs = new ArrayList(); 19 | ArrayList results = new ArrayList(); 20 | 21 | TreeNode n0 = new TreeNode(0); 22 | TreeNode n1 = new TreeNode(1); 23 | TreeNode n2 = new TreeNode(2); 24 | n0.left = n1; 25 | n0.right = n2; 26 | inputeRoots.add(n0); 27 | inputeAs.add(n1); 28 | inputeBs.add(n2); 29 | results.add(n0); 30 | 31 | for (int i = 0; i < results.size(); i++) { 32 | lowestCommonAncestorOfABinaryTree l = new lowestCommonAncestorOfABinaryTree(); 33 | TreeNode r = l.lowestCommonAncestor(inputeRoots.get(i), inputeAs.get(i), inputeBs.get(i)); 34 | assertEquals(results.get(i).val, r.val); 35 | } 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /algorithms/cpp/minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-22 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a binary tree, find its minimum depth. 8 | * 9 | * The minimum depth is the number of nodes along the shortest path from the root node 10 | * down to the nearest leaf node. 11 | * 12 | **********************************************************************************/ 13 | 14 | /** 15 | * Definition for binary tree 16 | * struct TreeNode { 17 | * int val; 18 | * TreeNode *left; 19 | * TreeNode *right; 20 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | int minDepth(TreeNode *root) { 26 | if (root==NULL){ 27 | return 0; 28 | } 29 | if (root->left==NULL && root->right==NULL){ 30 | return 1; 31 | } 32 | int left=INT_MAX; 33 | if (root->left){ 34 | left = minDepth(root->left) + 1 ; 35 | } 36 | int right=INT_MAX; 37 | if (root->right){ 38 | right = minDepth(root->right) + 1; 39 | } 40 | 41 | return left 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 11 | * Return: 1 --> 2 --> 3 --> 4 --> 5 12 | * 13 | * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 14 | * 15 | **********************************************************************************/ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | ListNode* removeElements(ListNode* head, int val) { 28 | static ListNode dummy(-1); 29 | dummy.next = head; 30 | ListNode *p = &dummy; 31 | 32 | while( p->next) { 33 | if (p->next->val == val) { 34 | p->next = p->next->next; 35 | }else{ 36 | p = p->next; 37 | } 38 | } 39 | 40 | return dummy.next; 41 | } 42 | }; 43 | 44 | 45 | -------------------------------------------------------------------------------- /algorithms/cpp/powerOfTwo/PowerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-two/ 2 | // Author : Hao Chen 3 | // Date : 2015-07-16 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an integer, write a function to determine if it is a power of two. 8 | * 9 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 10 | * all test cases. 11 | * 12 | * 13 | * 14 | **********************************************************************************/ 15 | 16 | 17 | class Solution { 18 | public: 19 | 20 | // count the number fo bits 1, if it only has one, then return true 21 | bool isPowerOfTwo01(int n) { 22 | int cnt = 0; //num of bits 1 23 | for(; n>0; n>>=1){ 24 | if ( n & 1 ) { 25 | cnt++; 26 | if (cnt>1) return false; 27 | } 28 | } 29 | return cnt==1; 30 | } 31 | 32 | //we notice: 2^n - 1 always be 1111111... 33 | //so, (2^n) & (2^n-1) always be zero 34 | bool isPowerOfTwo02(int n) { 35 | return n<=0 ? false : (n & (n-1)) == 0; 36 | } 37 | 38 | bool isPowerOfTwo(int n) { 39 | if (random()%2){ 40 | return isPowerOfTwo02(n); 41 | } 42 | return isPowerOfTwo01(n); 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /algorithms/cpp/plusOne/plusOne.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/plus-one/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-21 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a non-negative number represented as an array of digits, plus one to the number. 8 | * 9 | * The digits are stored such that the most significant digit is at the head of the list. 10 | * 11 | **********************************************************************************/ 12 | 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | vector plusOne(vector &digits) { 18 | int carry=1; 19 | vector v; 20 | while(digits.size()>0){ 21 | int x = digits.back(); 22 | digits.pop_back(); 23 | x = x + carry; 24 | v.insert(v.begin(), x%10); 25 | carry = x/10; 26 | } 27 | if (carry>0){ 28 | v.insert(v.begin(), carry); 29 | } 30 | return v; 31 | 32 | } 33 | 34 | void printVector(vector& v) 35 | { 36 | cout << "{ "; 37 | for(int i=0; i d(&a[0], &a[0]+sizeof(a)/sizeof(int)); 48 | vector v = plusOne(d); 49 | printVector(v); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/cpp/validPalindrome/validPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-palindrome/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-26 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 8 | * 9 | * For example, 10 | * "A man, a plan, a canal: Panama" is a palindrome. 11 | * "race a car" is not a palindrome. 12 | * 13 | * Note: 14 | * Have you consider that the string might be empty? This is a good question to ask during an interview. 15 | * 16 | * For the purpose of this problem, we define empty string as valid palindrome. 17 | * 18 | * 19 | **********************************************************************************/ 20 | 21 | class Solution { 22 | public: 23 | bool isPalindrome(string s) { 24 | s = removeNoise(s); 25 | for(int i=0; i& nums, int k) { 31 | int sum=0; 32 | for(int i=0; i sum) { 42 | sum = s; 43 | } 44 | } 45 | return (double)sum/k; 46 | } 47 | }; 48 | 49 | -------------------------------------------------------------------------------- /algorithms/java/src/removeDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-02 4 | 5 | /********************************************************************************** 6 | * Implement the following operations of a stack using queues. 7 | 8 | * Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. 9 | 10 | * Do not allocate extra space for another array, 11 | * you must do this by modifying the input array in-place with O(1) extra memory. 12 | 13 | * Example: 14 | 15 | * Given nums = [1,1,2], 16 | 17 | * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 18 | * It doesn't matter what you leave beyond the new length. 19 | * 20 | **********************************************************************************/ 21 | package removeDuplicatesFromSortedArray; 22 | 23 | public class RemoveDuplicatesFromSortedArray { 24 | public int removeDuplicates(int[] nums) { 25 | if (nums == null || nums.length == 0) { 26 | return 0; 27 | } 28 | int n = nums.length; 29 | int len = 0; 30 | for (int i = 1; i < n; i++) { 31 | if (nums[i] != nums[len]) { 32 | nums[len + 1] = nums[i]; 33 | len++; 34 | } 35 | } 36 | return len + 1; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /algorithms/cpp/fibonacciNumber/FibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/fibonacci-number/ 2 | // Author : Hao Chen 3 | // Date : 2019-03-26 4 | 5 | /***************************************************************************************************** 6 | * 7 | * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such 8 | * that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 9 | * 10 | * F(0) = 0, F(1) = 1 11 | * F(N) = F(N - 1) + F(N - 2), for N > 1. 12 | * 13 | * Given N, calculate F(N). 14 | * 15 | * Example 1: 16 | * 17 | * Input: 2 18 | * Output: 1 19 | * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 20 | * 21 | * Example 2: 22 | * 23 | * Input: 3 24 | * Output: 2 25 | * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 26 | * 27 | * Example 3: 28 | * 29 | * Input: 4 30 | * Output: 3 31 | * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 32 | * 33 | * Note: 34 | * 35 | * 0 ≤ N ≤ 30. 36 | ******************************************************************************************************/ 37 | 38 | class Solution { 39 | public: 40 | int fib(int N) { 41 | if (N < 2 ) return N; 42 | int first = 0, second = 1; 43 | 44 | for ( N-=1; N > 0; N-- ) { 45 | second += first; 46 | first = second - first; 47 | } 48 | return second; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /algorithms/cpp/twoSum/twoSum.III.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/ 2 | // Author : Hao Chen 3 | // Date : 2014-12-29 4 | 5 | /********************************************************************************** 6 | * 7 | * Design and implement a TwoSum class. It should support the following operations: add and find. 8 | * 9 | * add - Add the number to an internal data structure. 10 | * find - Find if there exists any pair of numbers which sum is equal to the value. 11 | * 12 | * For example, 13 | * 14 | * add(1); add(3); add(5); 15 | * find(4) -> true 16 | * find(7) -> false 17 | * 18 | **********************************************************************************/ 19 | 20 | class TwoSum { 21 | private: 22 | unordered_map nums; 23 | public: 24 | 25 | //O(1) add 26 | void add(int number) { 27 | nums[number]++; 28 | } 29 | 30 | //O(n) find 31 | bool find(int value) { 32 | int one, two; 33 | for(auto it = nums.begin(); it != nums.end(); it++){ 34 | one = it->first; 35 | two = value - one; 36 | if ( (one == two && it->second > 1) || 37 | (one != two && nums.find(two) != nums.end() ) ){ 38 | return true; 39 | } 40 | } 41 | return false; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /algorithms/cpp/ransomNote/RansomNote.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ransom-note/ 2 | // Author : Hao Chen 3 | // Date : 2016-08-24 4 | 5 | /*************************************************************************************** 6 | * 7 | * 
Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 8 | * 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 9 | * 
if 
the 
ransom 
 10 | * note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 11 | * 
false. 

 12 | * 13 | * Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 14 | * 
ransom
 note. 15 | * 16 | * Note: 17 | * You may assume that both strings contain only lowercase letters. 18 | * 19 | * canConstruct("a", "b") -> false 20 | * canConstruct("aa", "ab") -> false 21 | * canConstruct("aa", "aab") -> true 22 | ***************************************************************************************/ 23 | 24 | class Solution { 25 | public: 26 | bool canConstruct(string ransomNote, string magazine) { 27 | unordered_map m; 28 | for(int i=0; i 18 | #include 19 | using namespace std; 20 | 21 | string addBinary(string a, string b) { 22 | int alen = a.size(); 23 | int blen = b.size(); 24 | bool carry = false; 25 | string result; 26 | while( alen>0 || blen>0) { 27 | int abit = alen<=0 ? 0 : a[alen-1]-'0'; 28 | int bbit = blen<=0 ? 0 : b[blen-1]-'0'; 29 | int cbit = carry ? 1 : 0; 30 | result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) ); 31 | carry = (abit+bbit+cbit>1); 32 | alen--; blen--; 33 | } 34 | if (carry){ 35 | result.insert(result.begin(), '1'); 36 | } 37 | return result; 38 | } 39 | 40 | 41 | int main(int argc, char** argv) 42 | { 43 | string a = "11"; 44 | string b = "1"; 45 | if (argc>2){ 46 | a = argv[1]; 47 | b = argv[2]; 48 | } 49 | 50 | cout << a << "+" << b << "=" << addBinary(a, b) << endl; 51 | 52 | } 53 | -------------------------------------------------------------------------------- /algorithms/cpp/sortArrayByParity/SortArrayByParity.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-array-by-parity/ 2 | // Author : Hao Chen 3 | // Date : 2019-03-26 4 | 5 | /***************************************************************************************************** 6 | * 7 | * Given an array A of non-negative integers, return an array consisting of all the even elements of 8 | * A, followed by all the odd elements of A. 9 | * 10 | * You may return any answer array that satisfies this condition. 11 | * 12 | * Example 1: 13 | * 14 | * Input: [3,1,2,4] 15 | * Output: [2,4,3,1] 16 | * The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 17 | * 18 | * Note: 19 | * 20 | * 1 <= A.length <= 5000 21 | * 0 <= A[i] <= 5000 22 | * 23 | ******************************************************************************************************/ 24 | 25 | class Solution { 26 | public: 27 | bool isEven(int& x) { 28 | return x % 2 == 0; 29 | } 30 | vector sortArrayByParity(vector& A) { 31 | //two pointer, one from left to right, another from right to left 32 | // if left is odd number and right is even number, switch them 33 | int l=0, r=A.size()-1; 34 | while ( l < r ) { 35 | if ( !isEven(A[l]) && isEven(A[r]) ) swap(A[l], A[r]); 36 | if ( isEven(A[l]) ) l++; 37 | if ( !isEven(A[r]) ) r--; 38 | } 39 | return A; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/product-of-array-except-self/ 2 | // Author : Hao Chen 3 | // Date : 2015-07-17 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of n integers where n > 1, nums, return an array output such that 8 | * output[i] is equal to the product of all the elements of nums except nums[i]. 9 | * 10 | * Solve it without division and in O(n). 11 | * 12 | * For example, given [1,2,3,4], return [24,12,8,6]. 13 | * 14 | * Follow up: 15 | * Could you solve it with constant space complexity? (Note: The output array does not 16 | * count as extra space for the purpose of space complexity analysis.) 17 | * 18 | **********************************************************************************/ 19 | 20 | class Solution { 21 | public: 22 | vector productExceptSelf(vector& nums) { 23 | 24 | int len = nums.size(); 25 | vector result(len, 1); 26 | 27 | //from the left to right 28 | for (int i=1; i=0; i--){ 34 | factorial *= nums[i+1]; 35 | result[i] *= factorial; 36 | } 37 | return result; 38 | } 39 | }; 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /algorithms/cpp/twoSum/twoSum.II.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 2 | // Author : Hao Chen 3 | // Date : 2014-12-25 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of integers that is already sorted in ascending order, 8 | * find two numbers such that they add up to a specific target number. 9 | * 10 | * The function twoSum should return indices of the two numbers such that they add up to the target, 11 | * where index1 must be less than index2. Please note that your returned answers (both index1 and index2) 12 | * are not zero-based. 13 | * 14 | * You may assume that each input would have exactly one solution. 15 | * 16 | * Input: numbers={2, 7, 11, 15}, target=9 17 | * Output: index1=1, index2=2 18 | * 19 | **********************************************************************************/ 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | vector twoSum(vector &numbers, int target) { 26 | vector result; 27 | int low=0, high = numbers.size()-1; 28 | while (low < high){ 29 | if (numbers[low] + numbers[high] == target){ 30 | result.push_back(low+1); 31 | result.push_back(high+1); 32 | return result; 33 | }else{ 34 | numbers[low] + numbers[high] > target ? high-- : low++; 35 | } 36 | } 37 | 38 | return result; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jewels-and-stones/description 2 | // Author : Hao Chen 3 | // Date : 2018-06-23 4 | 5 | /*************************************************************************************** 6 | * 7 | * You're given strings J representing the types of stones that are jewels, and S 8 | * representing the stones you have. Each character in S is a type of stone you have. 9 | * You want to know how many of the stones you have are also jewels. 10 | * 11 | * The letters in J are guaranteed distinct, and all characters in J and S are letters. 12 | * Letters are case sensitive, so "a" is considered a different type of stone from "A". 13 | * 14 | * Example 1: 15 | * 16 | * 17 | * Input: J = "aA", S = "aAAbbbb" 18 | * Output: 3 19 | * 20 | * 21 | * Example 2: 22 | * 23 | * 24 | * Input: J = "z", S = "ZZ" 25 | * Output: 0 26 | * 27 | * 28 | * Note: 29 | * 30 | * 31 | * S and J will consist of letters and have length at most 50. 32 | * The characters in J are distinct. 33 | ***************************************************************************************/ 34 | 35 | 36 | class Solution { 37 | public: 38 | int numJewelsInStones(string J, string S) { 39 | bool map[256] = {false}; 40 | for (auto c : J) { 41 | map[c]=true; 42 | } 43 | int cnt=0; 44 | for (auto c : S) { 45 | if (map[c]) cnt++; 46 | } 47 | return cnt; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /algorithms/python/CopyListWithRandomPointer/copyRandomList.py: -------------------------------------------------------------------------------- 1 | # method 1: using a dict and store each node as key, each copied node as value 2 | # Space complexity: O(n) 3 | # Time complexity: O(n) 4 | 5 | def copyRandomList(self, head): 6 | d = {} 7 | m = n = head 8 | while m: 9 | d[m] = RandomListNode(m.label) 10 | m = m.next 11 | 12 | while n: 13 | d[n].next = d.get(n.next) 14 | d[n].random = d.get(n.random) 15 | n = n.next 16 | 17 | return d.get(head) 18 | 19 | # Method 2: 20 | # Space complexity: O(1) 21 | # Time complexity: O(n) 22 | 23 | def copyRandomList(self, head): 24 | if not head: return None 25 | 26 | # Step 1: copy each node and link them together with original ones 27 | curr = head 28 | while curr: 29 | new = RandomListNode(curr.label) 30 | new.next = curr.next 31 | curr.next = new 32 | curr = curr.next.next 33 | 34 | # Step 2: build random node for each copied nodes 35 | curr = head 36 | while curr: 37 | if curr.random: curr.next.random = curr.random.next 38 | curr = curr.next.next 39 | 40 | # Step 3: restore the original list and extract copied list 41 | newhead = head.next 42 | pold = head 43 | pnew = newhead 44 | while pnew.next: 45 | pold.next = pnew.next 46 | pold = pold.next 47 | pnew.next = pold.next 48 | pnew = pnew.next 49 | pold.next = None 50 | pnew.next = None 51 | return newhead -------------------------------------------------------------------------------- /algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/ 3 | // Author : Lei Cao 4 | // Date : 2015-10-03 5 | 6 | /********************************************************************************** 7 | * 8 | * Given a binary tree, find its maximum depth. 9 | * 10 | * The maximum depth is the number of nodes along the longest path from the root node 11 | * down to the farthest leaf node. 12 | * 13 | **********************************************************************************/ 14 | 15 | 16 | package maximumDepthOfBinaryTree; 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * public class TreeNode { 21 | * int val; 22 | * TreeNode left; 23 | * TreeNode right; 24 | * TreeNode(int x) { val = x; } 25 | * } 26 | */ 27 | public class maximumDepthOfBinaryTree { 28 | public int maxDepth(TreeNode root) { 29 | if (root == null) { 30 | return 0; 31 | } 32 | return theDepth(root); 33 | } 34 | 35 | private int theDepth(TreeNode root) { 36 | int leftDepth = 1; 37 | int rightDepth = 1; 38 | 39 | if (root.left != null) { 40 | leftDepth = theDepth(root.left) + 1; 41 | } 42 | if (root.right != null) { 43 | rightDepth = theDepth(root.right) + 1; 44 | } 45 | return Math.max(leftDepth, rightDepth); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedList/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Reverse a singly linked list. 8 | * 9 | * Hint: 10 | * A linked list can be reversed either iteratively or recursively. Could you implement both? 11 | * 12 | **********************************************************************************/ 13 | package reverseLinkedList; 14 | 15 | public class ReverseLinkedList { 16 | 17 | /** 18 | * The iterative solution 19 | */ 20 | public ListNode reverseList(ListNode head) { 21 | if (head == null) { 22 | return head; 23 | } 24 | ListNode p = head; 25 | ListNode next = p.next; 26 | while (next != null) { 27 | ListNode temp = next.next; 28 | next.next = p; 29 | p = next; 30 | next = temp; 31 | } 32 | head.next = null; 33 | return p; 34 | } 35 | 36 | public ListNode reverseListRecursion(ListNode head) { 37 | if (head == null) { 38 | return head; 39 | } 40 | ListNode newHead = recursion(head); 41 | head.next = null; 42 | return newHead; 43 | } 44 | /** 45 | * The recursive solution 46 | */ 47 | public ListNode recursion(ListNode p) { 48 | if (p.next == null) { 49 | return p; 50 | } else { 51 | ListNode next = p.next; 52 | ListNode newHead = recursion(next); 53 | next.next = p; 54 | return newHead; 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-21 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a binary tree, find its maximum depth. 8 | * 9 | * The maximum depth is the number of nodes along the longest path from the root node 10 | * down to the farthest leaf node. 11 | * 12 | **********************************************************************************/ 13 | 14 | /** 15 | * Definition for binary tree 16 | * struct TreeNode { 17 | * int val; 18 | * TreeNode *left; 19 | * TreeNode *right; 20 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | int maxDepth(TreeNode *root) { 26 | if (root==NULL){ 27 | return 0; 28 | } 29 | if (!root->left && !root->right){ 30 | return 1; 31 | } 32 | int left=1, right=1; 33 | if (root->left){ 34 | left += maxDepth(root->left); 35 | } 36 | if (root->right){ 37 | right += maxDepth(root->right); 38 | } 39 | return left>right?left:right; 40 | } 41 | 42 | }; 43 | 44 | class Solution2 { 45 | public: 46 | int maxDepth(TreeNode *root) { 47 | if (root==NULL) return 0; 48 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /algorithms/cpp/longestPalindrome/LongestPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-palindrome/ 2 | // Author : Hao Chen 3 | // Date : 2016-11-13 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given a string which consists of lowercase or uppercase letters, find the length of 8 | * the longest palindromes that can be built with those letters. 9 | * 10 | * This is case sensitive, for example "Aa" is not considered a palindrome here. 11 | * 12 | * Note: 13 | * Assume the length of given string will not exceed 1,010. 14 | * 15 | * Example: 16 | * 17 | * Input: 18 | * "abccccdd" 19 | * 20 | * Output: 21 | * 7 22 | * 23 | * Explanation: 24 | * One longest palindrome that can be built is "dccaccd", whose length is 7. 25 | ***************************************************************************************/ 26 | 27 | class Solution { 28 | public: 29 | int longestPalindrome(string s) { 30 | 31 | int hashtable[128]; 32 | memset(hashtable, 0, sizeof(hashtable)); 33 | 34 | for(char ch : s) { 35 | hashtable[ch]++; 36 | } 37 | int result = 0; 38 | bool hasOdd = false; 39 | for (int n : hashtable) { 40 | if ( n%2 == 0 ) { 41 | result += n; 42 | } else { 43 | result += n -1; 44 | hasOdd = true; 45 | } 46 | } 47 | 48 | return hasOdd ? result + 1 : result; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /algorithms/cpp/sqrt/sqrt.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/sqrtx/ 2 | // Author : Hao Chen 3 | // Date : 2014-08-26 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement int sqrt(int x). 8 | * 9 | * Compute and return the square root of x. 10 | * 11 | **********************************************************************************/ 12 | 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | 18 | int sqrt(int x) { 19 | 20 | if (x <=0 ) return 0; 21 | 22 | //the sqrt is not greater than x/2+1 23 | int e = x/2+1; 24 | int s = 0; 25 | // binary search 26 | while ( s <= e ) { 27 | int mid = s + (e-s)/2; 28 | long long sq = (long long)mid*(long long)mid; 29 | if (sq == x ) return mid; 30 | if (sq < x) { 31 | s = mid + 1; 32 | }else { 33 | e = mid - 1; 34 | } 35 | } 36 | return e; 37 | 38 | } 39 | 40 | // http://en.wikipedia.org/wiki/Newton%27s_method 41 | int sqrt_nt(int x) { 42 | if (x == 0) return 0; 43 | double last = 0; 44 | double res = 1; 45 | while (res != last) 46 | { 47 | last = res; 48 | res = (res + x / res) / 2; 49 | } 50 | return int(res); 51 | } 52 | 53 | 54 | int main(int argc, char**argv) 55 | { 56 | int n = 2; 57 | if( argc > 1 ){ 58 | n = atoi(argv[1]); 59 | } 60 | cout << "sqrt(" << n << ") = " << sqrt(n) << endl; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /algorithms/java/src/lruCache/LRUCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | Analogous to the C++ solution at: 3 | https://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp 4 | which uses linked list + hash map. But the Java stdlib provides LinkedHashMap 5 | which already implements that for us, making this solution shorter. 6 | 7 | This could also be done by using, but that generates 8 | some inheritance boilerplate, and ends up taking the same number of lines: 9 | https://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd 10 | */ 11 | 12 | import java.util.LinkedHashMap; 13 | import java.util.Iterator; 14 | 15 | public class LRUCache { 16 | 17 | private int capacity; 18 | private LinkedHashMap map; 19 | 20 | public LRUCache(int capacity) { 21 | this.capacity = capacity; 22 | this.map = new LinkedHashMap<>(); 23 | } 24 | 25 | public int get(int key) { 26 | Integer value = this.map.get(key); 27 | if (value == null) { 28 | value = -1; 29 | } else { 30 | this.set(key, value); 31 | } 32 | return value; 33 | } 34 | 35 | public void set(int key, int value) { 36 | if (this.map.containsKey(key)) { 37 | this.map.remove(key); 38 | } else if (this.map.size() == this.capacity) { 39 | Iterator it = this.map.keySet().iterator(); 40 | it.next(); 41 | it.remove(); 42 | } 43 | map.put(key, value); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/java/src/validAnagram/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-anagram/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given two strings s and t, write a function to determine if t is an anagram of s. 8 | * 9 | * For example, 10 | * s = "anagram", t = "nagaram", return true. 11 | * s = "rat", t = "car", return false. 12 | * 13 | * Note: 14 | * You may assume the string contains only lowercase alphabets. 15 | * 16 | * Follow up: 17 | * What if the inputs contain unicode characters? How would you adapt your solution to such case? 18 | * 19 | **********************************************************************************/ 20 | package validAnagram; 21 | 22 | public class ValidAnagram { 23 | 24 | /** 25 | * Like counting-sort 26 | */ 27 | public boolean isAnagram(String s, String t) { 28 | if (s == null && t == null) { 29 | return true; 30 | } 31 | if (s.length() != t.length()) { 32 | return false; 33 | } 34 | final int mapLen = 26; 35 | int[] map1 = new int[mapLen]; 36 | int[] map2 = new int[mapLen]; 37 | int len = s.length(); 38 | for (int i = 0; i < len; i++) { 39 | char c1 = s.charAt(i); 40 | map1[c1 - 'a']++; 41 | // ASCII of letter a is 97 42 | int c2 = t.charAt(i); 43 | map2[c2 - 97]++; 44 | } 45 | for (int i = 0; i < mapLen; i++) { 46 | if (map1[i] != map2[i]) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /algorithms/cpp/reverseLinkedList/reverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : Hao Chen 3 | // Date : 2015-06-09 4 | 5 | /********************************************************************************** 6 | * 7 | * Reverse a singly linked list. 8 | * 9 | * click to show more hints. 10 | * 11 | * Hint: 12 | * A linked list can be reversed either iteratively or recursively. Could you implement both? 13 | * 14 | * 15 | **********************************************************************************/ 16 | 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * ListNode *next; 23 | * ListNode(int x) : val(x), next(NULL) {} 24 | * }; 25 | */ 26 | class Solution { 27 | public: 28 | ListNode* reverseList_iteratively(ListNode* head) { 29 | ListNode *h=NULL, *p=NULL; 30 | while (head){ 31 | p = head->next; 32 | head->next = h; 33 | h = head; 34 | head = p; 35 | } 36 | return h; 37 | } 38 | ListNode* reverseList_recursively(ListNode* head) { 39 | if (head==NULL || head->next==NULL) return head; 40 | ListNode *h = reverseList_recursively(head->next); 41 | head->next->next = head; 42 | head->next = NULL; 43 | return h; 44 | 45 | } 46 | ListNode* reverseList(ListNode* head) { 47 | return reverseList_iteratively(head); 48 | return reverseList_recursively(head); 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /algorithms/cpp/rotateList/rotateList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/rotate-list/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-20 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a list, rotate the list to the right by k places, where k is non-negative. 8 | * 9 | * For example: 10 | * Given 1->2->3->4->5->NULL and k = 2, 11 | * return 4->5->1->2->3->NULL. 12 | * 13 | **********************************************************************************/ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | ListNode *rotateRight(ListNode *head, int k) { 26 | if (!head || k<=0){ 27 | return head; 28 | } 29 | 30 | //find the length of List 31 | int len=1; 32 | ListNode *p=head; 33 | while( p->next != NULL ){ 34 | p = p->next; 35 | len++; 36 | } 37 | //connect the tail to head 38 | p->next = head; 39 | //find the left place (take care the case - k > len) 40 | k = len - k % len; 41 | 42 | //find the place 43 | for(int i=0; inext; 45 | } 46 | 47 | //break the list 48 | head = p->next; 49 | p->next = NULL; 50 | 51 | return head; 52 | 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/binary-tree-preorder-traversal/ 3 | // Author : Lei Cao 4 | // Date : 2015-10-05 5 | 6 | /********************************************************************************** 7 | * 8 | * Given a binary tree, return the preorder traversal of its nodes' values. 9 | * 10 | * For example: 11 | * Given binary tree {1,#,2,3}, 12 | * 13 | * 1 14 | * \ 15 | * 2 16 | * / 17 | * 3 18 | * 19 | * return [1,2,3]. 20 | * 21 | * Note: Recursive solution is trivial, could you do it iteratively? 22 | * 23 | **********************************************************************************/ 24 | 25 | package binaryTreePreorderTraversal; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | /** 31 | * Created by leicao on 5/10/15. 32 | */ 33 | public class binaryTreePreorderTraversal { 34 | 35 | //Version 1: Traverse 36 | public List preorderTraversal(TreeNode root) { 37 | List results = new ArrayList(); 38 | traversal(results, root); 39 | return results; 40 | 41 | } 42 | 43 | private void traversal(List results, TreeNode root) { 44 | if (results == null || root == null) { 45 | return; 46 | } 47 | results.add(root.val); 48 | traversal(results, root.left); 49 | traversal(results, root.right); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/cpp/containsDuplicate/ContainsDuplicate.III.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-iii/ 2 | // Author : Hao Chen 3 | // Date : 2015-06-12 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of integers, find out whether there are two distinct indices i and j 8 | * in the array such that the difference between nums[i] and nums[j] is at most t and 9 | * the difference between i and j is at most k. 10 | * 11 | **********************************************************************************/ 12 | 13 | 14 | 15 | class Solution { 16 | public: 17 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 18 | if(nums.size() < 2 || k == 0) return false; 19 | int low = 0; 20 | //maintain a sliding window 21 | set window; 22 | for (int i=0; i k) { 25 | window.erase(nums[low]); 26 | low++; 27 | } 28 | 29 | // lower_bound() is the key, 30 | // it returns an iterator pointing to the first element >= val 31 | auto it = window.lower_bound((long long)nums[i] - (long long)t ); 32 | if (it != window.end() && abs((long long)nums[i] - *it) <= (long long)t) { 33 | return true; 34 | } 35 | window.insert(nums[i]); 36 | } 37 | return false; 38 | } 39 | }; 40 | 41 | -------------------------------------------------------------------------------- /algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/third-maximum-number/ 2 | // Author : Hao Chen 3 | // Date : 2016-11-12 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given a non-empty array of integers, return the third maximum number in this array. 8 | * If it does not exist, return the maximum number. The time complexity must be in O(n). 9 | * 10 | * Example 1: 11 | * 12 | * Input: [3, 2, 1] 13 | * 14 | * Output: 1 15 | * 16 | * Explanation: The third maximum is 1. 17 | * 18 | * Example 2: 19 | * 20 | * Input: [1, 2] 21 | * 22 | * Output: 2 23 | * 24 | * Explanation: The third maximum does not exist, so the maximum (2) is returned 25 | * instead. 26 | * 27 | * Example 3: 28 | * 29 | * Input: [2, 2, 3, 1] 30 | * 31 | * Output: 1 32 | * 33 | * Explanation: Note that the third maximum here means the third maximum distinct 34 | * number. 35 | * Both numbers with value 2 are both considered as second maximum. 36 | ***************************************************************************************/ 37 | 38 | class Solution { 39 | public: 40 | int nMax(vector& nums, int n) { 41 | set topN; 42 | for(auto num : nums) { 43 | topN.insert(num); 44 | if (topN.size() > n) topN.erase(topN.begin()); 45 | } 46 | return (topN.size() >= n) ? *(topN.begin()) : *(topN.rbegin()); 47 | } 48 | int thirdMax(vector& nums) { 49 | return nMax(nums, 3); 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /algorithms/cpp/validParentheses/validParentheses.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-parentheses/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-30 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 8 | * determine if the input string is valid. 9 | * 10 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid 11 | * but "(]" and "([)]" are not. 12 | * 13 | * 14 | **********************************************************************************/ 15 | 16 | #include 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | bool isValid(string s) { 22 | stack st; 23 | for(auto ch : s) { 24 | if (ch=='{' || ch =='[' || ch=='(' ) { 25 | st.push(ch); 26 | }else if (ch=='}' || ch ==']' || ch == ')' ){ 27 | if (st.empty()) return false; 28 | char sch = st.top(); 29 | if ( (sch=='{' && ch =='}') || (sch=='[' && ch==']') || (sch=='(' && ch==')' ) ){ 30 | st.pop(); 31 | }else { 32 | return false; 33 | } 34 | }else{ 35 | return false; 36 | } 37 | } 38 | return st.empty(); 39 | } 40 | 41 | int main(int argc, char**argv) 42 | { 43 | string s = "{{}{[]()}}"; 44 | if (argc>1){ 45 | s = argv[1]; 46 | } 47 | cout << "str = \"" << (s) << "\"" << endl; 48 | cout << isValid(s) << endl; 49 | } 50 | -------------------------------------------------------------------------------- /algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/find-minimum-in-rotated-sorted-array/ 3 | // Author : Lei Cao 4 | // Date : 2014-10-05 5 | 6 | /********************************************************************************** 7 | * 8 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 9 | * 10 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 11 | * 12 | * Find the minimum element. 13 | * 14 | * You may assume no duplicate exists in the array. 15 | * 16 | **********************************************************************************/ 17 | 18 | package findMinimumInRotatedSortedArray; 19 | 20 | public class findMinimumInRotatedSortedArray { 21 | public int findMin(int[] num) { 22 | if (num == null || num.length == 0) { 23 | return Integer.MIN_VALUE; 24 | } 25 | 26 | int start = 0; 27 | int end = num.length - 1; 28 | 29 | while (start + 1 < end) { 30 | int mid = start + (end - start) / 2; 31 | if (num[start] < num[end]) { 32 | end = mid; 33 | } else if (num[start] < num[mid]) { 34 | start = mid; 35 | } else { 36 | end = mid; 37 | } 38 | } 39 | 40 | if (num[start] < num[end]) { 41 | return num[start]; 42 | } else { 43 | return num[end]; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTreeTest.java: -------------------------------------------------------------------------------- 1 | package searchRangeInBinarySearchTree; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collection; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | /** 11 | * Created by leicao on 9/10/15. 12 | */ 13 | public class searchRangeInBinarySearchTreeTest { 14 | 15 | @Test 16 | public void testSearchRange() throws Exception { 17 | ArrayList inputs = new ArrayList(); 18 | 19 | TreeNode t1 = new TreeNode(20); 20 | TreeNode t2 = new TreeNode(8); 21 | TreeNode t3 = new TreeNode(22); 22 | TreeNode t4 = new TreeNode(4); 23 | TreeNode t5 = new TreeNode(12); 24 | 25 | t1.left = t2; 26 | t1.right = t3; 27 | t2.left = t4; 28 | t2.right = t5; 29 | 30 | inputs.add(t1); 31 | 32 | int[][] ranges = { 33 | {10,22} 34 | }; 35 | 36 | ArrayList> results = new ArrayList>(){{ 37 | add(new ArrayList(){{ 38 | add(12); 39 | add(20); 40 | add(22); 41 | }}); 42 | }}; 43 | 44 | for (int i = 0; i < results.size(); i++) { 45 | searchRangeInBinarySearchTree s = new searchRangeInBinarySearchTree(); 46 | ArrayList r = s.searchRange(inputs.get(i), ranges[i][0], ranges[i][1]); 47 | assertTrue(r.containsAll(results.get(i)) && r.size() == results.get(i).size()); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /algorithms/cpp/largestNumber/largestNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/largest-number/ 2 | // Author : Hao Chen 3 | // Date : 2015-01-16 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a list of non negative integers, arrange them such that they form the largest number. 8 | * 9 | * For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 10 | * 11 | * Note: The result may be very large, so you need to return a string instead of an integer. 12 | * 13 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 14 | * 15 | **********************************************************************************/ 16 | 17 | class Solution { 18 | public: 19 | 20 | //compare function 21 | static bool comp (string& s1, string& s2) { return s1+s2 > s2+s1; } 22 | 23 | string largestNumber(vector &num) { 24 | 25 | //convert int to string 26 | vector v; 27 | for (int i=0; i 22 | #include 23 | 24 | int lengthOfLastWord(const char *s) { 25 | 26 | if ( !s ||!*s ) return 0; 27 | 28 | int wordLen=0; 29 | int cnt=0; 30 | 31 | for (;*s!='\0';s++) { 32 | if (isalpha(*s)){ 33 | cnt++; 34 | } 35 | if (!isalpha(*s)){ 36 | if (cnt>0){ 37 | wordLen = cnt; 38 | } 39 | cnt=0; 40 | } 41 | } 42 | 43 | return cnt>0 ? cnt : wordLen; 44 | } 45 | 46 | 47 | int main(int argc, char** argv) 48 | { 49 | const char* p; 50 | p = "hello world"; 51 | printf("%s, %d\n", p, lengthOfLastWord(p)); 52 | p = "a"; 53 | printf("%s, %d\n", p, lengthOfLastWord(p)); 54 | 55 | if(argc>1){ 56 | p = argv[1]; 57 | printf("%s, %d\n", p, lengthOfLastWord(p)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /algorithms/cpp/searchInsertPosition/searchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/search-insert-position/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-22 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a sorted array and a target value, return the index if the target is found. 8 | * If not, return the index where it would be if it were inserted in order. 9 | * 10 | * You may assume no duplicates in the array. 11 | * 12 | * Here are few examples. 13 | * [1,3,5,6], 5 → 2 14 | * [1,3,5,6], 2 → 1 15 | * [1,3,5,6], 7 → 4 16 | * [1,3,5,6], 0 → 0 17 | * 18 | * 19 | **********************************************************************************/ 20 | 21 | #include 22 | 23 | 24 | int binary_search(int A[], int n, int key) { 25 | int low = 0; 26 | int high = n-1; 27 | while (low <= high){ 28 | int mid = low +(high-low)/2; 29 | if (A[mid] == key){ 30 | return mid; 31 | } 32 | if ( key> A[mid] ) { 33 | low = mid+1; 34 | }else{ 35 | high = mid-1; 36 | } 37 | } 38 | return low; 39 | } 40 | int searchInsert(int A[], int n, int target) { 41 | if (n==0) return n; 42 | return binary_search(A, n, target); 43 | } 44 | 45 | int main() 46 | { 47 | int a[]={1,3,5,6}; 48 | printf("%d -> %d\n", 5, searchInsert(a, 4, 5)); 49 | printf("%d -> %d\n", 2, searchInsert(a, 4, 2)); 50 | printf("%d -> %d\n", 7, searchInsert(a, 4, 7)); 51 | printf("%d -> %d\n", 0, searchInsert(a, 4, 0)); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /algorithms/cpp/gasStation/gasStation.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/gas-station/ 2 | // Author : Hao Chen 3 | // Date : 2014-10-11 4 | 5 | /********************************************************************************** 6 | * 7 | * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 8 | * 9 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to 10 | * its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 11 | * 12 | * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 13 | * 14 | * Note: 15 | * The solution is guaranteed to be unique. 16 | * 17 | * 18 | **********************************************************************************/ 19 | 20 | class Solution { 21 | public: 22 | int canCompleteCircuit(vector &gas, vector &cost) { 23 | int current = 0; 24 | int start = gas.size(); //start from the end to beginning 25 | int total = 0; 26 | 27 | do { 28 | if (total + gas[current] - cost[current] >= 0) { 29 | total += (gas[current] - cost[current]); 30 | current++; // can go from current to current+1 31 | }else{ 32 | start--; //not enough gas, try to start the one before origin start point. 33 | total += (gas[start] - cost[start]); 34 | } 35 | } while(current != start); 36 | 37 | return total>=0 ? start % gas.size() : -1; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /algorithms/java/src/reverseLinkedListII/ReverseLinkedListII.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list-ii/description/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Reverse a linked list from position m to n. Do it in-place and in one-pass. 8 | * 9 | * For example: 10 | * Given 1->2->3->4->5->NULL, m = 2 and n = 4, 11 | * 12 | * return 1->4->3->2->5->NULL. 13 | * 14 | * Note: 15 | * Given m, n satisfy the following condition: 16 | * 1 ≤ m ≤ n ≤ length of list. 17 | * 18 | **********************************************************************************/ 19 | package reverseLinkedListII; 20 | 21 | public class ReverseLinkedListII { 22 | public ListNode reverseBetween(ListNode head, int m, int n) { 23 | // Assume that the list is:[1,2,3,4,5,6,7] m=3 n=5 24 | if (head == null || m == n) { 25 | // bounds check 26 | return head; 27 | } 28 | // We'd better create a default head due to m may equals 1 29 | ListNode defaultHead = new ListNode(0); 30 | defaultHead.next = head; 31 | int index = 1; 32 | ListNode pre = defaultHead; 33 | while (index < m) { 34 | pre = pre.next; 35 | index++; 36 | } 37 | // pre is 2, first is 3 38 | ListNode first = pre.next; 39 | ListNode p = first; 40 | ListNode next = p.next; 41 | while (index < n) { 42 | ListNode t = next.next; 43 | next.next = p; 44 | p = next; 45 | next = t; 46 | index++; 47 | } 48 | // next is 6 49 | first.next = next; 50 | pre.next = p; 51 | return defaultHead.next; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-21 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a linked list, remove the nth node from the end of list and return its head. 8 | * 9 | * For example, 10 | * 11 | * Given linked list: 1->2->3->4->5, and n = 2. 12 | * 13 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 14 | * 15 | * Note: 16 | * Given n will always be valid. 17 | * Try to do this in one pass. 18 | * 19 | * 20 | **********************************************************************************/ 21 | 22 | /** 23 | * Definition for singly-linked list. 24 | * struct ListNode { 25 | * int val; 26 | * ListNode *next; 27 | * ListNode(int x) : val(x), next(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | ListNode *removeNthFromEnd(ListNode *head, int n) { 33 | if (head==NULL || n<=0){ 34 | return NULL; 35 | } 36 | ListNode fakeHead(0); 37 | fakeHead.next=head; 38 | head=&fakeHead; 39 | 40 | ListNode *p1, *p2; 41 | p1=p2=head; 42 | for(int i=0; inext; 45 | } 46 | while (p2->next!=NULL){ 47 | p2=p2->next; 48 | p1=p1->next; 49 | } 50 | 51 | p1->next = p1->next->next; 52 | return head->next; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-linked-list/ 2 | // Author : Hao Chen 3 | // Date : 2015-07-17 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a singly linked list, determine if it is a palindrome. 8 | * 9 | * Follow up: 10 | * Could you do it in O(n) time and O(1) space? 11 | * 12 | **********************************************************************************/ 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * struct ListNode { 17 | * int val; 18 | * ListNode *next; 19 | * ListNode(int x) : val(x), next(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | ListNode* findMiddle(ListNode* head) { 25 | ListNode *p1=head, *p2=head; 26 | while(p2 && p2->next){ 27 | p1 = p1->next; 28 | p2 = p2->next->next; 29 | } 30 | return p1; 31 | } 32 | 33 | ListNode* reverseLink(ListNode* head) { 34 | ListNode* p=NULL; 35 | 36 | while (head) { 37 | ListNode* q = head->next; 38 | head->next = p; 39 | p = head; 40 | head = q; 41 | } 42 | return p; 43 | } 44 | 45 | bool isPalindrome(ListNode* head) { 46 | ListNode* pMid = findMiddle(head); 47 | ListNode* pRev = reverseLink(pMid); 48 | for(;head!=pMid; head=head->next, pRev=pRev->next) { 49 | if (head->val != pRev->val) { 50 | return false; 51 | } 52 | } 53 | return true; 54 | } 55 | }; 56 | 57 | 58 | -------------------------------------------------------------------------------- /algorithms/cpp/integerBreak/IntegerBreak.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-break/ 2 | // Author : Hao Chen 3 | // Date : 2016-05-29 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given a positive integer n, break it into the sum of at least two positive integers 8 | * and maximize the product of those integers. Return the maximum product you can get. 9 | * 10 | * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 11 | * + 4). 12 | * 13 | * Note: you may assume that n is not less than 2. 14 | * 15 | * There is a simple O(n) solution to this problem. 16 | * You may check the breaking results of n ranging from 7 to 10 to discover the 17 | * regularities. 18 | * 19 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 20 | * all test cases. 21 | ***************************************************************************************/ 22 | 23 | class Solution { 24 | public: 25 | // As the hint said, checking the n with ranging from 7 to 10 to discover the regularities. 26 | // n = 7, 3*4 = 12 27 | // n = 8, 3*3*2 = 18 28 | // n = 9, 3*3*3 = 27 29 | // n = 10, 3*3*4 = 36 30 | // n = 11, 3*3*3*2 = 54 31 | // 32 | // we can see we can break the number by 3 if it is greater than 4; 33 | // 34 | int integerBreak(int n) { 35 | if ( n == 2 ) return 1; 36 | if ( n == 3 ) return 2; 37 | int result = 1; 38 | while( n > 4 ) { 39 | result *= 3; 40 | n -= 3; 41 | } 42 | result *= n; 43 | return result; 44 | } 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /algorithms/java/src/palindromeNumber/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/palindrome-number/ 2 | // Author : Tianming Cao 3 | // Date : 2018-02-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Determine whether an integer is a palindrome. Do this without extra space. 8 | * 9 | * Some hints: 10 | * Could negative integers be palindromes? (ie, -1) 11 | * 12 | * If you are thinking of converting the integer to string, note the restriction of using extra space. 13 | * 14 | * You could also try reversing an integer. 15 | * However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. 16 | * How would you handle such case? 17 | * 18 | * There is a more generic way of solving this problem. 19 | * 20 | **********************************************************************************/ 21 | package palindromeNumber; 22 | 23 | public class PalindromeNumber { 24 | 25 | /** 26 | * The simple way is : 27 | * Reverse x to reverseX and judge whether reverseX is equal to x 28 | * For example: 29 | * x is 1234321, then reverseX is 1234321, they are equal, so 1234321 is palindrome 30 | * x is 1234123, then reverseX is 3214321, they are not equal, so 1234123 is not palindrome 31 | */ 32 | public boolean isPalindrome(int x) { 33 | if (x < 0) { 34 | return false; 35 | } 36 | if (x < 10) { 37 | return true; 38 | } 39 | int n = x; 40 | int reverseX = 0; 41 | while (n > 0) { 42 | reverseX = 10 * reverseX + n % 10; 43 | n /= 10; 44 | } 45 | if (reverseX == x) { 46 | return true; 47 | } else { 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/cpp/palindromicSubstrings/PalindromicSubstrings.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindromic-substrings/ 2 | // Author : Hao Chen 3 | // Date : 2019-01-30 4 | 5 | /***************************************************************************************************** 6 | * 7 | * 8 | * Given a string, your task is to count how many palindromic substrings in this string. 9 | * 10 | * The substrings with different start indexes or end indexes are counted as different substrings even 11 | * they consist of same characters. 12 | * 13 | * Example 1: 14 | * 15 | * Input: "abc" 16 | * Output: 3 17 | * Explanation: Three palindromic strings: "a", "b", "c". 18 | * 19 | * Example 2: 20 | * 21 | * Input: "aaa" 22 | * Output: 6 23 | * Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 24 | * 25 | * Note: 26 | * 27 | * The input string length won't exceed 1000. 28 | * 29 | ******************************************************************************************************/ 30 | class Solution { 31 | public: 32 | int countSubstrings(string s) { 33 | int len = s.size(); 34 | if (len<=1) return len; 35 | 36 | vector< vector > dp(len, vector(len, false)); 37 | 38 | int cnt = 0; 39 | for( int i=len-1; i>=0; i--) { 40 | for (int j=i; j<=len-1; j++) { 41 | if ( i == j || ( s[i] == s[j] && ( j-i<2 || dp[i+1][j-1]) ) ) { 42 | dp[i][j] = true; 43 | cnt++; 44 | } 45 | } 46 | } 47 | 48 | return cnt; 49 | 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /algorithms/java/src/firstBadVersion/firstBadVersion.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-bad-version/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/first-bad-version/ 3 | // Author : Lei Cao 4 | // Date : 2014-10-05 5 | 6 | /********************************************************************************** 7 | * 8 | * The code base version is an integer start from 1 to n. 9 | * 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. 10 | * Find the first bad version. 11 | * 12 | * You can call isBadVersion to help you determine which version is the first bad one. 13 | * The details interface can be found in the code's annotation part. 14 | * 15 | **********************************************************************************/ 16 | 17 | package firstBadVersion; 18 | 19 | /* The isBadVersion API is defined in the parent class VersionControl. 20 | boolean isBadVersion(int version); */ 21 | public class firstBadVersion extends VersionControl { 22 | public int firstBadVersion(int n) { 23 | if (n < 1) { 24 | return 0; 25 | } 26 | int start = 1; 27 | int end = n; 28 | 29 | while (start + 1 < end) { 30 | int mid = start + (end - start) / 2; 31 | if (super.isBadVersion(mid)) { 32 | end = mid; 33 | } else { 34 | start = mid; 35 | } 36 | } 37 | 38 | if (super.isBadVersion(start)) { 39 | return start; 40 | } 41 | if (super.isBadVersion(end)) { 42 | return end; 43 | } 44 | return 0; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /algorithms/cpp/addStrings/AddStrings.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-strings/ 2 | // Author : Hao Chen 3 | // Date : 2016-11-12 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given two non-negative numbers num1 and num2 represented as string, return the sum 8 | * of num1 and num2. 9 | * 10 | * Note: 11 | * 12 | * The length of both num1 and num2 is 13 | * Both num1 and num2 contains only digits 0-9. 14 | * Both num1 and num2 does not contain any leading zero. 15 | * You must not use any built-in BigInteger library or convert the inputs to integer 16 | * directly. 17 | ***************************************************************************************/ 18 | 19 | class Solution { 20 | public: 21 | string addStrings(string num1, string num2) { 22 | string& longstr = ( num1.size() >= num2.size() ? num1 : num2 ); 23 | string& shortstr = ( num1.size() < num2.size() ? num1 : num2 ); 24 | 25 | int longlen = longstr.size(); 26 | int shortlen = shortstr.size(); 27 | 28 | char carry = 0; 29 | int i, j; 30 | 31 | string result; 32 | for (i = longlen-1, j=shortlen-1; i>=0; i--, j--) { 33 | int add = 0; 34 | if (j>=0) { 35 | add = longstr[i] + shortstr[j] - 2 * '0' + carry; 36 | }else{ 37 | add = longstr[i] - '0' + carry; 38 | } 39 | carry = add/10; 40 | result = char('0' + add % 10) + result; 41 | } 42 | 43 | if (carry) { 44 | result = '1' + result; 45 | } 46 | return result; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /algorithms/cpp/convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-23 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 8 | * 9 | **********************************************************************************/ 10 | 11 | /** 12 | * Definition for binary tree 13 | * struct TreeNode { 14 | * int val; 15 | * TreeNode *left; 16 | * TreeNode *right; 17 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | TreeNode *sortedArrayToBST(vector &num) { 23 | if(num.size()==0){ 24 | return NULL; 25 | } 26 | if(num.size()==1){ 27 | return new TreeNode(num[0]); 28 | } 29 | int mid = num.size()/2; 30 | 31 | TreeNode *node = new TreeNode(num[mid]); 32 | 33 | vector::const_iterator first; 34 | vector::const_iterator last; 35 | 36 | first = num.begin(); 37 | last = num.begin()+mid; 38 | vector v(first, last); 39 | node->left = sortedArrayToBST(v); 40 | 41 | if (mid==num.size()-1){ 42 | node->right = NULL; 43 | }else{ 44 | first = num.begin()+mid+1; 45 | last = num.end(); 46 | vector v(first, last); 47 | node->right = sortedArrayToBST(v); 48 | } 49 | return node; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBSTTest.java: -------------------------------------------------------------------------------- 1 | package inorderSuccessorInBST; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by leicao on 7/10/15. 11 | */ 12 | public class inorderSuccessorInBSTTest { 13 | 14 | @Test 15 | public void testInorderSuccessor() throws Exception { 16 | ArrayList inputes = new ArrayList(); 17 | ArrayList targets = new ArrayList(); 18 | 19 | TreeNode n0 = new TreeNode(2); 20 | TreeNode n1 = new TreeNode(1); 21 | TreeNode n2 = new TreeNode(3); 22 | n0.left = n1; 23 | n0.right = n2; 24 | inputes.add(n0); 25 | targets.add(n2); 26 | 27 | TreeNode nn0 = new TreeNode(2); 28 | TreeNode nn1 = new TreeNode(1); 29 | nn0.left = nn1; 30 | inputes.add(nn0); 31 | targets.add(nn1); 32 | 33 | TreeNode t0 = new TreeNode(1); 34 | TreeNode t1 = new TreeNode(2); 35 | t0.right = t1; 36 | inputes.add(t0); 37 | targets.add(t0); 38 | 39 | 40 | ArrayList results = new ArrayList(); 41 | results.add(null); 42 | results.add(nn0); 43 | results.add(t1); 44 | 45 | for (int i = 0; i < results.size(); i++) { 46 | inorderSuccessorInBST finder = new inorderSuccessorInBST(); 47 | TreeNode node = finder.inorderSuccessor(inputes.get(i), targets.get(i)); 48 | System.out.println(node); 49 | boolean result = node == results.get(i) || node.val == results.get(i).val; 50 | assertTrue(result); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /algorithms/cpp/generateParentheses/generateParentheses.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/generate-parentheses/ 2 | // Author : Hao Chen 3 | // Date : 2014-06-29 4 | 5 | /********************************************************************************** 6 | * 7 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 8 | * 9 | * For example, given n = 3, a solution set is: 10 | * 11 | * "((()))", "(()())", "(())()", "()(())", "()()()" 12 | * 13 | * 14 | **********************************************************************************/ 15 | 16 | #include 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | 22 | void generator(vector& result, int left, int right, string s); 23 | vector generateParenthesis(int n) { 24 | 25 | vector result; 26 | string s; 27 | generator(result, n, n, s); 28 | return result; 29 | } 30 | 31 | void generator(vector& result, int left, int right, string s){ 32 | if (left==0 && right==0){ 33 | result.push_back(s); 34 | return; 35 | } 36 | if (left>0){ 37 | generator(result, left-1, right, s+'('); 38 | } 39 | if (right>0 && right>left){ 40 | generator(result, left, right-1, s+')'); 41 | } 42 | } 43 | 44 | void printResult(vector& result) 45 | { 46 | for(int i=0; i1){ 55 | n = atoi(argv[1]); 56 | } 57 | vector r = generateParenthesis(n); 58 | printResult(r); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/convert-a-number-to-hexadecimal/ 2 | // Author : Hao Chen 3 | // Date : 2016-11-12 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given an integer, write an algorithm to convert it to hexadecimal. For negative 8 | * integer, two’s complement method is used. 9 | * 10 | * Note: 11 | * 12 | * All letters in hexadecimal (a-f) must be in lowercase. 13 | * The hexadecimal string must not contain extra leading 0s. If the number is zero, it 14 | * is represented by a single zero character '0'; otherwise, the first character in the 15 | * hexadecimal string will not be the zero character. 16 | * The given number is guaranteed to fit within the range of a 32-bit signed integer. 17 | * You must not use any method provided by the library which converts/formats the 18 | * number to hex directly. 19 | * 20 | * Example 1: 21 | * 22 | * Input: 23 | * 26 24 | * 25 | * Output: 26 | * "1a" 27 | * 28 | * Example 2: 29 | * 30 | * Input: 31 | * -1 32 | * 33 | * Output: 34 | * "ffffffff" 35 | ***************************************************************************************/ 36 | 37 | class Solution { 38 | public: 39 | 40 | string toHex(int num) { 41 | 42 | if (num == 0) return "0"; 43 | 44 | unsigned int x = num; 45 | 46 | string result; 47 | for(;x > 0; x/=16) { 48 | int n = x % 16; 49 | char c; 50 | if (n < 10) c = n + '0'; 51 | else c = 'a' + n - 10 ; 52 | result = c + result; 53 | } 54 | return result; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /algorithms/java/src/dynamicProgramming/minimumPathSum/minimumPathSum.java: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/minimum-path-sum/ 2 | // Inspired by : http://www.jiuzhang.com/solutions/minimum-path-sum/ 3 | // Author : Lei Cao 4 | // Date : 2015-10-12 5 | 6 | /********************************************************************************** 7 | * 8 | * Given a m x n grid filled with non-negative numbers, find a path from top left to 9 | * bottom right which minimizes the sum of all numbers along its path. 10 | * 11 | * Note: You can only move either down or right at any point in time. 12 | * 13 | **********************************************************************************/ 14 | 15 | package dynamicProgramming.minimumPathSum; 16 | 17 | public class minimumPathSum { 18 | /** 19 | * @param grid: a list of lists of integers. 20 | * @return: An integer, minimizes the sum of all numbers along its path 21 | */ 22 | public int minPathSum(int[][] grid) { 23 | if (grid.length == 0 || grid[0].length == 0) { 24 | return 0; 25 | } 26 | int m = grid.length; 27 | int n = grid[0].length; 28 | int[][] matrix = new int[m][n]; 29 | 30 | matrix[0][0] = grid[0][0]; 31 | for (int i = 1; i < m; i++) { 32 | matrix[i][0] = grid[i][0] + matrix[i-1][0]; 33 | } 34 | 35 | for (int i = 1; i < n; i++) { 36 | matrix[0][i] = grid[0][i] + matrix[0][i-1]; 37 | } 38 | 39 | for (int i = 1; i < m; i++) { 40 | for (int j = 1; j < n; j++) { 41 | matrix[i][j] = grid[i][j] + Math.min(matrix[i-1][j], matrix[i][j-1]); 42 | } 43 | } 44 | 45 | return matrix[m-1][n-1]; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /algorithms/cpp/sortArrayByParity/SortArrayByParity.II.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-array-by-parity-ii/ 2 | // Author : Hao Chen 3 | // Date : 2019-03-26 4 | 5 | /***************************************************************************************************** 6 | * 7 | * Given an array A of non-negative integers, half of the integers in A are odd, and half of the 8 | * integers are even. 9 | * 10 | * Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. 11 | * 12 | * You may return any answer array that satisfies this condition. 13 | * 14 | * Example 1: 15 | * 16 | * Input: [4,2,5,7] 17 | * Output: [4,5,2,7] 18 | * Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. 19 | * 20 | * Note: 21 | * 22 | * 2 <= A.length <= 20000 23 | * A.length % 2 == 0 24 | * 0 <= A[i] <= 1000 25 | * 26 | ******************************************************************************************************/ 27 | 28 | class Solution { 29 | public: 30 | bool isEven(int &x) { 31 | return x % 2 == 0; 32 | } 33 | vector sortArrayByParityII(vector& A) { 34 | //two pointer, `even` and `odd`, 35 | // - `even` pointer step into even position 36 | // - `odd` pointer step into odd position. 37 | // if `even` points to odd number, and `odd` points to even number switch them. 38 | int even = 0; 39 | int odd = 1; 40 | while(even < A.size() && odd < A.size() ) { 41 | if ( !isEven(A[even]) && isEven(A[odd]) ) swap( A[even], A[odd] ); 42 | if ( isEven(A[even]) ) even += 2; 43 | if ( !isEven(A[odd]) ) odd += 2; 44 | } 45 | return A; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /algorithms/cpp/isSubsequence/IsSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/is-subsequence/ 2 | // Author : Hao Chen 3 | // Date : 2016-09-08 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given a string s and a string t, check if s is subsequence of t. 8 | * 9 | * You may assume that there is only lower case English letters in both s and t. t is 10 | * potentially a very long (length ~= 500,000) string, and s is a short string ( 11 | * 12 | * A subsequence of a string is a new string which is formed from the original string 13 | * by deleting some (can be none) of the characters without disturbing the relative 14 | * positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while 15 | * "aec" is not). 16 | * 17 | * Example 1: 18 | * s = "abc", t = "ahbgdc" 19 | * 20 | * Return true. 21 | * 22 | * Example 2: 23 | * s = "axc", t = "ahbgdc" 24 | * 25 | * Return false. 26 | * 27 | * Follow up: 28 | * If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to 29 | * check one by one to see if T has its subsequence. In this scenario, how would you 30 | * change your code? 31 | ***************************************************************************************/ 32 | 33 | class Solution { 34 | public: 35 | bool isSubsequence(string s, string t) { 36 | if (s.size() <= 0) return true; 37 | 38 | int ps=0, pt=0; 39 | while (pt < t.size()) { 40 | if (s[ps] == t[pt]) { 41 | ps++; pt++; 42 | if (ps >= s.size()) return true; 43 | }else { 44 | pt++; 45 | } 46 | } 47 | 48 | return false; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Immutable.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/range-sum-query-immutable/ 2 | // Author : Calinescu Valentin, Hao Chen 3 | // Date : 2015-11-10 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given an integer array nums, find the sum of the elements between indices i and j 8 | * (i ≤ j), inclusive. 9 | * 10 | * Example: 11 | * Given nums = [-2, 0, 3, -5, 2, -1] 12 | * 13 | * sumRange(0, 2) -> 1 14 | * sumRange(2, 5) -> -1 15 | * sumRange(0, 5) -> -3 16 | * Note: 17 | * You may assume that the array does not change. 18 | * There are many calls to sumRange function. 19 | * 20 | ***************************************************************************************/ 21 | 22 | class NumArray { 23 | /* 24 | * Solution 25 | * ========= 26 | * 27 | * The sum of all the elements starting from position 0 to position i is stored in 28 | * sums[i]. This way we can reconstruct the sum from position i to position j by 29 | * subtracting sums[i - 1] from sums[j], leaving us with the sum of the desired elements. 30 | * 31 | * Note: we can add a dummy sum at then beginning to simplify the code 32 | * 33 | */ 34 | private: 35 | int size; 36 | vector sums; 37 | public: 38 | NumArray(vector &nums): size(nums.size()), sums(size+1, 0) { 39 | for(int i=0; i 26 | #include 27 | #include 28 | using namespace std; 29 | 30 | string convert(string s, int nRows) { 31 | //The cases no need to do anything 32 | if (nRows<=1 || nRows>=s.size()) return s; 33 | 34 | vector r(nRows); 35 | int row = 0; 36 | int step = 1; 37 | for(int i=0; i