Repository: kdn251/interviews
Branch: master
Commit: 03fdcb2703ce
Files: 526
Total size: 696.0 KB
Directory structure:
gitextract_nak9cli1/
├── .gitignore
├── .project
├── LICENSE
├── README-zh-cn.md
├── README.md
├── company/
│ ├── Company.iml
│ ├── adobe/
│ │ ├── AddDigits.java
│ │ └── MajorityElement.java
│ ├── airbnb/
│ │ ├── AddTwoNumbers.java
│ │ ├── ContainsDuplicate.java
│ │ ├── ContainsDuplicatesII.java
│ │ ├── ConvertSortedArrayToBinarySearchTree.java
│ │ ├── HouseRobber.java
│ │ ├── MergeKSortedLists.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── TwoSum.java
│ │ └── ValidParentheses.java
│ ├── amazon/
│ │ ├── 3Sum.java
│ │ ├── AddTwoNumbers.java
│ │ ├── BestTimeToBuyAndSellStock.java
│ │ ├── BinaryTreeLevelOrderTraversal.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── GroupAnagrams.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── KthLargestElementInAnArray.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ ├── LinkedListCycle.java
│ │ ├── LongestPalindromicSubstring.java
│ │ ├── LowestCommonAncestorOfABinaryTree.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MinCostClimbingStairs.java
│ │ ├── MinStack.java
│ │ ├── NumberOfIslands.java
│ │ ├── PalindromeLinkedList.java
│ │ ├── ProductOfArrayExceptSelf.java
│ │ ├── ReverseLinkedList.java
│ │ ├── RotateImage.java
│ │ ├── Subsets.java
│ │ ├── TrappingRainWater.java
│ │ ├── TwoSum.java
│ │ ├── ValidParentheses.java
│ │ ├── ValidateBinarySearchTree.java
│ │ └── WordBreak.java
│ ├── apple/
│ │ ├── ReverseWordsInAString.java
│ │ └── ValidSudoku.java
│ ├── bloomberg/
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── LinkedListCycle.java
│ │ ├── LongestPalindromicSubstring.java
│ │ ├── MinStack.java
│ │ ├── ReverseWordsInAString.java
│ │ └── UniquePaths.java
│ ├── facebook/
│ │ ├── 3Sum.java
│ │ ├── AddAndSearchWordDataStructureDesign.java
│ │ ├── AddBinary.java
│ │ ├── BestTimeToBuyAndSellStock.java
│ │ ├── BinarySearchTreeIterator.java
│ │ ├── BinaryTreeLevelOrderTraversal.java
│ │ ├── BinaryTreePaths.java
│ │ ├── BinaryTreeVerticalOrderTraversal.java
│ │ ├── CloneGraph.java
│ │ ├── CombinationSumIV.java
│ │ ├── CountAndSay.java
│ │ ├── DecodeWays.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── ExclusiveTimeOfFunctions.java
│ │ ├── ExpressionAddOperators.java
│ │ ├── FindTheCelebrity.java
│ │ ├── FirstBadVersion.java
│ │ ├── FlattenNestedListIterator.java
│ │ ├── GroupAnagrams.java
│ │ ├── HammingDistance.java
│ │ ├── ImplementTrie.java
│ │ ├── InorderSuccessorInBST.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── InsertInterval.java
│ │ ├── IntegerToEnglishWords.java
│ │ ├── KthLargestElementInAnArray.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ ├── LongestConsecutiveSequence.java
│ │ ├── LowestCommonAncestorOfABinaryTree.java
│ │ ├── MaximumSizeSubarraySumEqualsK.java
│ │ ├── MeetingRooms.java
│ │ ├── MergeIntervals.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MergeSortedArray.java
│ │ ├── MinStack.java
│ │ ├── MinimumSizeSubarraySum.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── MoveZeros.java
│ │ ├── MultiplyStrings.java
│ │ ├── NumberOfIslands.java
│ │ ├── OneEditDistance.java
│ │ ├── PaintHouseII.java
│ │ ├── PalindromeLinkedList.java
│ │ ├── PalindromicSubstrings.java
│ │ ├── PowerOfXToTheN.java
│ │ ├── ProductOfArrayExceptSelf.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── RemoveDuplicatesFromSortedArray.java
│ │ ├── RemoveInvalidParentheses.java
│ │ ├── ReverseLinkedList.java
│ │ ├── RomanToInteger.java
│ │ ├── SearchInRotatedSortedArray.java
│ │ ├── SortColors.java
│ │ ├── SparseMatrixMultiplication.java
│ │ ├── SquareRootX.java
│ │ ├── Subsets.java
│ │ ├── SubsetsII.java
│ │ ├── SumOfLeftLeaves.java
│ │ ├── TwoSum.java
│ │ ├── ValidPalindrome.java
│ │ ├── ValidParentheses.java
│ │ ├── ValidateBinarySearchTree.java
│ │ ├── WallsAndGates.java
│ │ ├── WordBreak.java
│ │ └── WordSearch.java
│ ├── google/
│ │ ├── 3SumSmaller.java
│ │ ├── AndroidUnlockPatterns.java
│ │ ├── BinarySearchTreeIterator.java
│ │ ├── BinaryTreePaths.java
│ │ ├── BinaryTreeVerticalOrderTraversal.java
│ │ ├── BinaryWatch.java
│ │ ├── BombEnemy.java
│ │ ├── BullsAndCows.java
│ │ ├── CloneGraph.java
│ │ ├── ClosestBinarySearchTreeValue.java
│ │ ├── CombinationSumIV.java
│ │ ├── DailyTemperatures.java
│ │ ├── DecodeString.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── ExpressionAddOperators.java
│ │ ├── FindAllNumbersDisappearedInAnArray.java
│ │ ├── FindTheDifference.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── FlattenNestedListIterator.java
│ │ ├── GameOfLife.java
│ │ ├── GeneralizedAbbreviation.java
│ │ ├── GenerateParentheses.java
│ │ ├── GroupShiftedStrings.java
│ │ ├── GuessNumberHigherOrLower.java
│ │ ├── ImplementTrie.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── InsertInterval.java
│ │ ├── IslandPerimeter.java
│ │ ├── JudgeRouteCircle.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ ├── LoggerRateLimiter.java
│ │ ├── LongestConsecutiveSequence.java
│ │ ├── LongestSubstringWithAtMostKDistinctCharacters.java
│ │ ├── MaximumProductOfWordLengths.java
│ │ ├── MergeIntervals.java
│ │ ├── MinStack.java
│ │ ├── MissingRanges.java
│ │ ├── MovingAverageFromDataStream.java
│ │ ├── NumberOfIslands.java
│ │ ├── PacificAtlanticWaterFlow.java
│ │ ├── PaintFence.java
│ │ ├── PlusOne.java
│ │ ├── PlusOneLinkedList.java
│ │ ├── PowerOfTwo.java
│ │ ├── PowerOfXToTheN.java
│ │ ├── RegularExpressionMatching.javaa
│ │ ├── ReverseVowelsOfAString.java
│ │ ├── SentenceScreenFitting.java
│ │ ├── ShortestDistanceFromAllBuildings.java
│ │ ├── SpiralMatrix.java
│ │ ├── StrobogrammaticNumber.java
│ │ ├── SummaryRanges.java
│ │ ├── TrappingRainWater.java
│ │ ├── UniqueWordAbbreviation.java
│ │ ├── Utf8Validation.java
│ │ ├── ValidParentheses.java
│ │ ├── WallsAndGates.java
│ │ ├── WiggleSort.java
│ │ ├── WordBreak.java
│ │ ├── WordSquares.java
│ │ └── ZigZagIterator.java
│ ├── linkedin/
│ │ ├── BinarySearchTreeIterator.java
│ │ ├── BinaryTreeLevelOrderTraversal.java
│ │ ├── FindTheCelebrity.java
│ │ ├── HouseRobber.java
│ │ ├── InsertInterval.java
│ │ ├── LowestCommonAncestorOfABinaryTree.java
│ │ ├── MaximumDepthOfABinaryTree.java
│ │ ├── MaximumProductSubarray.java
│ │ ├── MaximumSubarray.java
│ │ ├── MergeIntervals.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── PaintHouse.java
│ │ ├── PalindromicSubstrings.java
│ │ ├── Permutations.java
│ │ ├── PowerOfXToTheN.java
│ │ ├── ProductOfArrayExceptSelf.java
│ │ ├── SearchInRotatedSortedArray.java
│ │ ├── SparseMatrixMultiplication.java
│ │ ├── SymmetricTree.java
│ │ └── TwoSum.java
│ ├── microsoft/
│ │ ├── AddDigits.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── HouseRobberII.java
│ │ ├── LinkedListCycle.java
│ │ ├── LongestIncreasingSubsequence.java
│ │ ├── LongestPalindromicSubstring.java
│ │ ├── Permutations.java
│ │ ├── ReverseWordsInAString.java
│ │ └── SpiralMatrix.java
│ ├── palantir/
│ │ ├── ContainsDuplicate.java
│ │ └── ContainsDuplicatesII.java
│ ├── snapchat/
│ │ ├── MinStack.java
│ │ ├── ReverseWordsInAString.java
│ │ └── ValidSudoku.java
│ ├── twitter/
│ │ ├── FlattenNestedListIterator.java
│ │ ├── ImplementTrie.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── LowestCommonAncestorOfABinaryTree.java
│ │ ├── MergeIntervals.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MultiplyStrings.java
│ │ ├── OneEditDistance.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── ReverseLinkedList.java
│ │ ├── TrappingRainWater.java
│ │ └── ValidParentheses.java
│ ├── uber/
│ │ ├── BestTimeToBuyOrSellStock.java
│ │ ├── CloneGraph.java
│ │ ├── DecodeWays.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── ExclusiveTimeOfFunctions.java
│ │ ├── GenerateParentheses.java
│ │ ├── GroupAnagrams.java
│ │ ├── GroupShiftedStrings.java
│ │ ├── ImplementTrie.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ ├── MaximumDepthOfABinaryTree.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MinStack.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── OneEditDistance.java
│ │ ├── PalindromePermutation.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── ReverseLinkedList.java
│ │ ├── RomanToInteger.java
│ │ ├── SearchInRotatedSortedArray.java
│ │ ├── SpiralMatrix.java
│ │ ├── Subsets.java
│ │ ├── TwoSum.java
│ │ ├── ValidPalindrome.java
│ │ ├── ValidSudoku.java
│ │ └── WordBreak.java
│ ├── yahoo/
│ │ ├── ContainsDuplicate.java
│ │ └── LinkedListCycle.java
│ └── yelp/
│ ├── InsertDeleteGetRandomO1.java
│ └── ReverseWordsInAString.java
├── cracking-the-coding-interview/
│ ├── CrackingTheCodingInterview.iml
│ ├── chapter-five-bit-manipulation/
│ │ ├── BinaryRepresentation.java
│ │ ├── FindMissingInteger.java
│ │ ├── InsertMIntoN.java
│ │ └── SwapBits.java
│ ├── chapter-four-trees-and-graphs/
│ │ ├── BinaryTreeIsBalanced.java
│ │ ├── CreateBinarySearchTree.java
│ │ ├── CreateLinkedListForEachLevel.java
│ │ ├── FindPath.java
│ │ ├── IsSubtree.java
│ │ ├── PrintPaths.java
│ │ └── ValidBinarySearchTree.java
│ ├── chapter-nine-recursion-and-dynamic-programming/
│ │ ├── AllPermutations.java
│ │ ├── AllSubsets.java
│ │ ├── EightQueens.java
│ │ ├── MagicIndex.java
│ │ ├── RepresentingNCents.java
│ │ ├── StackBoxes.java
│ │ └── Staircase.java
│ ├── chapter-one-arrays-and-strings/
│ │ ├── DeleteDups.java
│ │ ├── IsRotation.java
│ │ ├── IsUniqueChars.java
│ │ ├── NthToLast.java
│ │ ├── Permutation.java
│ │ └── ReplaceSpaces.java
│ ├── chapter-seven-mathematics-and-probability/
│ │ ├── Operations.java
│ │ └── WouldIntersect.java
│ ├── chapter-three-stacks-and-queues/
│ │ ├── BinaryTreeIsBalanced.java
│ │ ├── MyQUeue.java
│ │ ├── MyQueue.java
│ │ ├── QueueUsingTwoStacks.java
│ │ ├── SetOfStacks.java
│ │ ├── SortStack.java
│ │ ├── StackWithMin.java
│ │ ├── ThreeStacks.java
│ │ └── TowersOfHanoi.java
│ └── chapter-two-linked-lists/
│ ├── DeleteDups.java
│ ├── DeleteNode.java
│ ├── FindBeginning.java
│ ├── IsPalindrome.java
│ ├── NthToLast.java
│ └── Partition.java
├── interviews.iml
├── leetcode/
│ ├── LeetCode.iml
│ ├── array/
│ │ ├── BestTimeToBuyAndSellStock.java
│ │ ├── ContainsDuplicatesII.java
│ │ ├── FindAllNumbersDisappearedInAnArray.java
│ │ ├── FindTheCelebrity.java
│ │ ├── GameOfLife.java
│ │ ├── IncreasingTripletSubsequence.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── InsertInterval.java
│ │ ├── LongestConsecutiveSequence.java
│ │ ├── MajorityElement.java
│ │ ├── MaximumProductSubarray.java
│ │ ├── MaximumSubarray.java
│ │ ├── MergeIntervals.java
│ │ ├── MinCostClimbingStairs.java
│ │ ├── MinimumPathSum.java
│ │ ├── MissingRanges.java
│ │ ├── PlusOne.java
│ │ ├── ProductofArrayExceptSelf.java
│ │ ├── RemoveElement.java
│ │ ├── RotateImage.java
│ │ ├── SearchInRotatedSortedArray.java
│ │ ├── SpiralMatrix.java
│ │ ├── SpiralMatrixII.java
│ │ ├── Subsets.java
│ │ ├── SubsetsII.java
│ │ ├── SummaryRanges.java
│ │ ├── UniquePaths.java
│ │ ├── WiggleSort.java
│ │ └── WordSearch.java
│ ├── backtracking/
│ │ ├── AndroidUnlockPatterns.java
│ │ ├── GeneralizedAbbreviation.java
│ │ ├── GenerateParentheses.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ └── Permutations.java
│ ├── binary-search/
│ │ ├── ClosestBinarySearchTreeValue.java
│ │ ├── FirstBadVersion.java
│ │ ├── GuessNumberHigherOrLower.java
│ │ ├── PowerOfXToTheN.java
│ │ └── SquareRootX.java
│ ├── bit-manipulation/
│ │ ├── BinaryWatch.java
│ │ ├── CountingBits.java
│ │ ├── HammingDistance.java
│ │ ├── MaximumProductOfWordLengths.java
│ │ ├── NumberOfOneBits.java
│ │ ├── PowerOfTwo.java
│ │ ├── SumOfTwoInteger.java
│ │ └── Utf8Validation.java
│ ├── brainteaser/
│ │ └── BulbSwitcher.java
│ ├── breadth-first-search/
│ │ ├── BinaryTreeLevelOrderTraversal.java
│ │ ├── CloneGraph.java
│ │ ├── PacificAtlanticWaterFlow.java
│ │ ├── RemoveInvalidParentheses.java
│ │ ├── ShortestDistanceFromAllBuildings.java
│ │ ├── SymmetricTree.java
│ │ └── WallsAndGates.java
│ ├── depth-first-search/
│ │ ├── BalancedBinaryTree.java
│ │ ├── BattleshipsInABoard.java
│ │ ├── ConvertSortedArrayToBinarySearchTree.java
│ │ ├── MaximumDepthOfABinaryTree.java
│ │ ├── NumberOfIslands.java
│ │ ├── PopulatingNextRightPointersInEachNode.java
│ │ └── SameTree.java
│ ├── design/
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── MinStack.java
│ │ └── ZigZagIterator.java
│ ├── divide-and-conquer/
│ │ ├── ExpressionAddOperators.java
│ │ └── KthLargestElementInAnArray.java
│ ├── dynamic-programming/
│ │ ├── BombEnemy.java
│ │ ├── ClimbingStairs.java
│ │ ├── CoinChange.java
│ │ ├── CombinationSumIV.java
│ │ ├── CountingBits.java
│ │ ├── EditDistance.java
│ │ ├── HouseRobber.java
│ │ ├── HouseRobberII.java
│ │ ├── LongestIncreasingSubsequence.java
│ │ ├── MinCostClimbingStairs.java
│ │ ├── MinimumPathSum.java
│ │ ├── PaintFence.java
│ │ ├── PaintHouse.java
│ │ ├── PaintHouseII.java
│ │ ├── PalindromicSubstrings.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── SentenceScreenFitting.java
│ │ ├── UniqueBinarySearchTrees.java
│ │ ├── UniquePaths.java
│ │ └── WordBreak.java
│ ├── greedy/
│ │ └── BestTimeToBuyAndSellStockII.java
│ ├── hash-table/
│ │ ├── BinaryTreeVerticalOrderTraversal.java
│ │ ├── BullsAndCows.java
│ │ ├── ContainsDuplicate.java
│ │ ├── ContainsDuplicatesII.java
│ │ ├── DailyTemperatures.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── FindAnagramMappings.java
│ │ ├── FindTheDifference.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── GroupAnagrams.java
│ │ ├── GroupShiftedStrings.java
│ │ ├── InsertDeleteGetRandomO1.java
│ │ ├── IslandPerimeter.java
│ │ ├── JewelsAndStones.java
│ │ ├── LoggerRateLimiter.java
│ │ ├── MaximumSizeSubarraySumEqualsK.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── SingleNumberII.java
│ │ ├── SparseMatrixMultiplication.java
│ │ ├── StrobogrammaticNumber.java
│ │ ├── TwoSum.java
│ │ ├── UniqueWordAbbreviation.java
│ │ ├── ValidAnagram.java
│ │ └── ValidSudoku.java
│ ├── linked-list/
│ │ ├── AddTwoNumbers.java
│ │ ├── DeleteNodeInALinkedList.java
│ │ ├── LinkedListCycle.java
│ │ ├── MergeKSortedLists.java
│ │ ├── PalindromeLinkedList.java
│ │ ├── PlusOneLinkedList.java
│ │ └── ReverseLinkedList.java
│ ├── math/
│ │ ├── AddDigits.java
│ │ ├── BulbSwitcher.java
│ │ ├── EncodeAndDecodeTinyURL.java
│ │ ├── PalindromeNumber.java
│ │ ├── PlusOne.java
│ │ ├── PoorPigs.java
│ │ └── PowerOfTwo.java
│ ├── queue/
│ │ └── MovingAverageFromDataStream.java
│ ├── sort/
│ │ ├── MeetingRooms.java
│ │ └── MeetingRoomsII.java
│ ├── stack/
│ │ ├── BinarySearchTreeIterator.java
│ │ ├── DailyTemperatures.java
│ │ ├── DecodeString.java
│ │ ├── ExclusiveTimeOfFunctions.java
│ │ ├── FlattenNestedListIterator.java
│ │ ├── MinStack.java
│ │ └── TrappingRainWater.java
│ ├── string/
│ │ ├── AddBinary.java
│ │ ├── CountAndSay.java
│ │ ├── DecodeWays.java
│ │ ├── EditDistance.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── GenerateParentheses.java
│ │ ├── IntegerToEnglishWords.java
│ │ ├── JudgeRouteCircle.java
│ │ ├── LongestCommonPrefix.java
│ │ ├── LongestPalindrome.java
│ │ ├── LongestPalindromicSubstring.java
│ │ ├── LongestSubstringWithAtMostKDistinctCharacters.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── MultiplyStrings.java
│ │ ├── OneEditDistance.java
│ │ ├── PalindromePermutation.java
│ │ ├── PalindromicSubstrings.java
│ │ ├── ReverseVowelsOfAString.java
│ │ ├── ReverseWordsInAString.java
│ │ ├── RomanToInteger.java
│ │ ├── ValidPalindrome.java
│ │ └── ValidParentheses.java
│ ├── tree/
│ │ ├── BinaryTreeMaximumPathSum.java
│ │ ├── BinaryTreePaths.java
│ │ ├── InorderSuccessorInBST.java
│ │ ├── InvertBinaryTree.java
│ │ ├── LowestCommonAncestorOfABinaryTree.java
│ │ ├── SumOfLeftLeaves.java
│ │ ├── TrimABinarySearchTree.java
│ │ └── ValidateBinarySearchTree.java
│ ├── trie/
│ │ ├── AddAndSearchWordDataStructureDesign.java
│ │ ├── ImplementTrie.java
│ │ └── WordSquares.java
│ └── two-pointers/
│ ├── 3Sum.java
│ ├── 3SumSmaller.java
│ ├── LinkedListCycle.java
│ ├── MergeSortedArray.java
│ ├── MinimumSizeSubarraySum.java
│ ├── MoveZeros.java
│ ├── RemoveDuplicatesFromSortedArray.java
│ ├── RemoveElement.java
│ ├── ReverseString.java
│ └── SortColors.java
└── uva/
├── AddingReversedNumbers.java
├── Ants.java
├── ArchaeologistsDilemma.java
├── AverageSpeed.java
├── BackToIntermediateMath.java
├── BasicRemains.java
├── BasicallySpeaking.java
├── BigMod.java
├── BrickGame.java
├── CoconutsRevisited.java
├── DigitCounting.java
├── FactorialFrequenices.java
├── FiveHundredFactorial.java
├── Friends.java
├── GoldbachConjecture.java
├── GoogleIsFeelingLucky.java
├── HashmatWarriors.java
├── HighPrecisionNumber.java
├── HighSchoolPhysics.java
├── ICanGuessTheDataStructure.java
├── IntegerInquiry.java
├── JollyJumpers.java
├── LargestPrimeDivisor.java
├── LightMoreLight.java
├── MischievousChildren.java
├── Modex.java
├── MultipleOfSeventeen.java
├── Newspaper.java
├── NumberTheoryForNewbies.java
├── NumberingRoads.java
├── OpenSource.java
├── Parity.java
├── PeskyPalindromes.java
├── PrimeFactors.java
├── PseudoPrimeNumbers.java
├── SimplifyingFractions.java
├── SimplyEmirp.java
├── SkewBinary.java
├── SolveEquation.java
├── SplittingNumbers.java
├── TheHugeOne.java
├── TheLastNonZeroDigit.java
├── TheSettlersOfCatan.java
├── VeryEasy.java
├── VirtualFriends.java
├── WhatBaseIsThis.java
└── WhoSaidCrisis.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/bin/
.idea
================================================
FILE: .project
================================================
interviews
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 Kevin Naughton Jr.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README-zh-cn.md
================================================
> * 原文地址:[github.com/kdn251/interviews](https://github.com/kdn251/interviews)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 译者:[王下邀月熊](https://github.com/wxyyxc1992)
> * 校对者:[PhxNirvana](https://github.com/phxnirvana)、[根号三](https://github.com/sqrthree)
> * 这个 [链接](https://github.com/xitu/interviews/compare/master...kdn251:master) 用来查看本翻译与英文版是否有差别(如果你没有看到 README.md 发生变化,那就意味着这份翻译文档是最新的)。
# Interviews
> 软件工程技术面试个人指南。
>
> Maintainer - [Kevin Naughton Jr.](https://github.com/kdn251)
## 其他语言版本
- [English](./README.md)
## 目录
- [在线练习](#在线练习)
- [在线面试编程](#在线面试编程)
- [数据结构](#数据结构)
- [算法](#算法)
- [位运算](#位运算)
- [算法复杂度分析](#算法复杂度分析)
- [视频教程](#视频教程)
- [面试书籍](#面试书籍)
- [计算机科学与技术资讯](#计算机科学与技术资讯)
- [文件结构](#文件结构)
## 在线练习
* [LeetCode](https://leetcode.com/)
* [Virtual Judge](https://vjudge.net/)
* [CareerCup](https://www.careercup.com/)
* [HackerRank](https://www.hackerrank.com/)
* [CodeFights](https://codefights.com/)
* [Kattis](https://open.kattis.com/)
* [HackerEarth](https://www.hackerearth.com)
* [Codility](https://codility.com/programmers/lessons/1-iterations/)
* [Code Forces](http://codeforces.com/)
* [Code Chef](https://www.codechef.com/)
* [Sphere Online Judge - SPOJ](http://www.spoj.com/)
* [InterviewBit](https://www.interviewbit.com/)
## 在线面试编程
* [Pramp](https://www.pramp.com/ref/gt4-cn)
* [Gainlo](http://www.gainlo.co/#!/)
* [Refdash](https://refdash.com/)
* [Interviewing.io](https://www.interviewing.io/)
## 数据结构
### Linked List
* 链表即是由节点(Node)组成的线性集合,每个节点可以利用指针指向其他节点。它是一种包含了多个节点的、能够用于表示序列的数据结构。
* **单向链表**: 链表中的节点仅指向下一个节点,并且最后一个节点指向空。
* **双向链表**: 其中每个节点具有两个指针 p、n,使得 p 指向先前节点并且 n 指向下一个节点;最后一个节点的 n 指针指向 null。
* **循环链表**:每个节点指向下一个节点并且最后一个节点指向第一个节点的链表。
* 时间复杂度:
* 索引: `O(n)`
* 搜索: `O(n)`
* 插入: `O(1)`
* 移除: `O(1)`
### Stack
* 栈是元素的集合,其包含了两个基本操作:push 操作可以用于将元素压入栈,pop 操作可以将栈顶元素移除。
* 遵循后入先出(LIFO)原则。
* 时间复杂度:
* 索引: `O(n)`
* 搜索: `O(n)`
* 插入: `O(1)`
* 移除: `O(1)`
### Queue
* 队列是元素的集合,其包含了两个基本操作:enqueue 操作可以用于将元素插入到队列中,而 dequeue 操作则是将元素从队列中移除。
* 遵循先入先出原则 (FIFO)。
* 时间复杂度:
* 索引: `O(n)`
* 搜索: `O(n)`
* 插入: `O(1)`
* 移除: `O(1)`
### Tree
* 树是无向、连通的无环图。
### Binary Tree
* 二叉树即是每个节点最多包含左子节点与右子节点这两个节点的树形数据结构。
* **满二叉树**: 树中的每个节点仅包含 0 或 2 个节点。
* **完美二叉树(Perfect Binary Tree)**: 二叉树中的每个叶节点都拥有两个子节点,并且具有相同的高度。
* **完全二叉树**: 除最后一层外,每一层上的结点数均达到最大值;在最后一层上只缺少右边的若干结点。
### Binary Search Tree
* 二叉搜索树(BST)是一种特殊的二叉树,其任何节点中的值都会大于或者等于其左子树中存储的值并且小于或者等于其右子树中存储的值。
* 时间复杂度:
* 索引: `O(log(n))`
* 搜索: `O(log(n))`
* 插入: `O(log(n))`
* 删除: `O(log(n))`
### Trie
* 字典树,又称基数树或者前缀树,能够用于存储键为字符串的动态集合或者关联数组的搜索树。树中的节点并没有直接存储关联键值,而是该节点在树中的挂载位置决定了其关联键值。某个节点的所有子节点都拥有相同的前缀,整棵树的根节点则是空字符串。

### Fenwick Tree
* 树状数组又称 Binary Indexed Tree,其表现形式为树,不过本质上是以数组实现。数组中的下标代表着树中的顶点,每个顶点的父节点或者子节点的下标能够通过位运算获得。数组中的每个元素包含了预计算的区间值之和,在整棵树更新的过程中同样会更新这些预计算的值。
* 时间复杂度:
* 区间求值: `O(log(n))`
* 更新: `O(log(n))`

### Segment Tree
* 线段树是用于存放间隔或者线段的树形数据结构,它允许快速的查找某一个节点在若干条线段中出现的次数.
* 时间复杂度:
* 区间查询: `O(log(n))`
* 更新: `O(log(n))`

### Heap
* 堆是一种特殊的基于树的满足某些特性的数据结构,整个堆中的所有父子节点的键值都会满足相同的排序条件。堆更准确地可以分为最大堆与最小堆,在最大堆中,父节点的键值永远大于或者等于子节点的值,并且整个堆中的最大值存储于根节点;而最小堆中,父节点的键值永远小于或者等于其子节点的键值,并且整个堆中的最小值存储于根节点。
* 时间复杂度:
* 访问最大值 / 最小值: `O(1)`
* 插入: `O(log(n))`
* 移除最大值 / 最小值: `O(log(n))`
### Hashing
* 哈希能够将任意长度的数据映射到固定长度的数据。哈希函数返回的即是哈希值,如果两个不同的键得到相同的哈希值,即将这种现象称为碰撞。
* **Hash Map**: Hash Map 是一种能够建立起键与值之间关系的数据结构,Hash Map 能够使用哈希函数将键转化为桶或者槽中的下标,从而优化对于目标值的搜索速度。
* 碰撞解决
* **链地址法(Separate Chaining)**: 链地址法中,每个桶是相互独立的,包含了一系列索引的列表。搜索操作的时间复杂度即是搜索桶的时间(固定时间)与遍历列表的时间之和。
* **开地址法(Open Addressing)**: 在开地址法中,当插入新值时,会判断该值对应的哈希桶是否存在,如果存在则根据某种算法依次选择下一个可能的位置,直到找到一个尚未被占用的地址。所谓开地址法也是指某个元素的位置并不永远由其哈希值决定。

### Graph
* 图是一种数据元素间为多对多关系的数据结构,加上一组基本操作构成的抽象数据类型。
* **无向图(Undirected Graph)**: 无向图具有对称的邻接矩阵,因此如果存在某条从节点 u 到节点 v 的边,反之从 v 到 u 的边也存在。
* **有向图(Directed Graph)**: 有向图的邻接矩阵是非对称的,即如果存在从 u 到 v 的边并不意味着一定存在从 v 到 u 的边。
## 算法
### 排序
#### 快速排序
* 稳定: 否
* 时间复杂度:
* 最优时间: `O(nlog(n))`
* 最坏时间: `O(n^2)`
* 平均时间: `O(nlog(n))`

#### 归并排序
* 归并排序是典型的分治算法,它不断地将某个数组分为两个部分,分别对左子数组与右子数组进行排序,然后将两个数组合并为新的有序数组。
* 稳定: 是
* 时间复杂度:
* 最优时间: `O(nlog(n))`
* 最坏时间: `O(nlog(n))`
* 平均时间: `O(nlog(n))`

#### 桶排序
* 桶排序将数组分到有限数量的桶子里。每个桶子再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。
* 时间复杂度:
* 最优时间: `Ω(n + k)`
* 最坏时间: `O(n^2)`
* 平均时间:`Θ(n + k)`

#### 基数排序
* 基数排序类似于桶排序,将数组分割到有限数目的桶中;不过其在分割之后并没有让每个桶单独地进行排序,而是直接进行了合并操作。
* 时间复杂度:
* 最优时间: `Ω(nk)`
* 最坏时间: `O(nk)`
* 平均时间: `Θ(nk)`
### 图算法
#### 深度优先搜索
* 深度优先算法是一种优先遍历子节点而不是回溯的算法。
* 时间复杂度: `O(|V| + |E|)`

#### 广度优先搜索
* 广度优先搜索是优先遍历邻居节点而不是子节点的图遍历算法。
* 时间复杂度: `O(|V| + |E|)`

#### 拓扑排序
* 拓扑排序是对于有向图节点的线性排序,如果存在某条从 u 到 v 的边,则认为 u 的下标先于 v。
* 时间复杂度: `O(|V| + |E|)`
#### Dijkstra 算法
* **Dijkstra 算法** 用于计算有向图中单源最短路径问题。
* 时间复杂度: `O(|V|^2)`

#### Bellman-Ford 算法
* **Bellman-Ford 算法**是在带权图中计算从单一源点出发到其他节点的最短路径的算法。
* 尽管算法复杂度大于 Dijkstra 算法,但是它适用于包含了负值边的图。
* 时间复杂度:
* 最优时间: `O(|E|)`
- 最坏时间: `O(|V||E|)`

#### Floyd-Warshall 算法
* **Floyd-Warshall 算法** 能够用于在无环带权图中寻找任意节点的最短路径。
* 时间复杂度:
* 最优时间: `O(|V|^3)`
* 最坏时间: `O(|V|^3)`
* 平均时间: `O(|V|^3)`
#### Prim 算法
* **Prim 算法**是用于在带权无向图中计算最小生成树的贪婪算法。换言之,Prim 算法能够在图中抽取出连接所有节点的边的最小代价子集。
* 时间复杂度: `O(|V|^2)`

#### Kruskal 算法
* **Kruskal 算法**同样是计算图的最小生成树的算法,与 Prim 的区别在于并不需要图是连通的。
* 时间复杂度: `O(|E|log|V|)`

## 位运算
* 位运算即是在位级别进行操作的技术,合适的位运算能够帮助我们得到更快地运算速度与更小的内存使用。
* 测试第 k 位: `s & (1 << k)`
* 设置第 k 位: `s |= (1 << k)`
* 第 k 位置零: `s &= ~(1 << k)`
* 切换第 k 位值: `s ^= ~(1 << k)`
* 乘以 2n: `s << n`
* 除以 2n: `s >> n`
* 交集: `s & t`
* 并集: `s | t`
* 减法: `s & ~t`
* 交换 `x = x ^ y ^ (y = x)`
* 取出最小非 0 位(Extract lowest set bit): `s & (-s)`
* 取出最小 0 位(Extract lowest unset bit): `~s & (s + 1)`
* 交换值:
```
x ^= y;
y ^= x;
x ^= y;
```
## 算法复杂度分析
#### 大 O 表示
* **大 O 表示** 用于表示某个算法的上限,往往用于描述最坏的情况。

#### 小 O 表示
* **小 O 表示**用于描述某个算法的渐进上界,不过二者要更为紧密。
#### 大 Ω 表示
* **大 Ω 表示**用于描述某个算法的渐进下界。

#### 小 ω 表示
* **Little Omega Notation**用于描述某个特定算法的下界,不过不一定很靠近。
#### Theta Θ 表示
* **Theta Notation**用于描述某个确定算法的确界。

## 视频教程
* Data Structures
* [UC Berkeley Data Structures](https://www.youtube.com/watch?v=mFPmKGIrQs4&index=1&list=PL-XXv-cvA_iAlnI-BQr9hjqADPBtujFJd)
* [MIT Advanced Data Structures](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf&index=1)
* Algorithms
* [MIT Introduction to Algorithms](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&index=1)
* [MIT Advanced Algorithms](https://www.youtube.com/playlist?list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c)
## 面试书籍
* Competitive Programming 3 - Steven Halim & Felix Halim
* Cracking The Coding Interview - Gayle Laakmann McDowell
* Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro
## 计算机科学与技术资讯
* [Hacker News](https://news.ycombinator.com/)
* [Lobsters](https://lobste.rs/)
## 文件结构
```
.
├── Array
│ ├── bestTimeToBuyAndSellStock.java
│ ├── findTheCelebrity.java
│ ├── gameOfLife.java
│ ├── increasingTripletSubsequence.java
│ ├── insertInterval.java
│ ├── longestConsecutiveSequence.java
│ ├── maximumProductSubarray.java
│ ├── maximumSubarray.java
│ ├── mergeIntervals.java
│ ├── missingRanges.java
│ ├── productOfArrayExceptSelf.java
│ ├── rotateImage.java
│ ├── searchInRotatedSortedArray.java
│ ├── spiralMatrixII.java
│ ├── subsetsII.java
│ ├── subsets.java
│ ├── summaryRanges.java
│ ├── wiggleSort.java
│ └── wordSearch.java
├── Backtracking
│ ├── androidUnlockPatterns.java
│ ├── generalizedAbbreviation.java
│ └── letterCombinationsOfAPhoneNumber.java
├── BinarySearch
│ ├── closestBinarySearchTreeValue.java
│ ├── firstBadVersion.java
│ ├── guessNumberHigherOrLower.java
│ ├── pow(x,n).java
│ └── sqrt(x).java
├── BitManipulation
│ ├── binaryWatch.java
│ ├── countingBits.java
│ ├── hammingDistance.java
│ ├── maximumProductOfWordLengths.java
│ ├── numberOf1Bits.java
│ ├── sumOfTwoIntegers.java
│ └── utf-8Validation.java
├── BreadthFirstSearch
│ ├── binaryTreeLevelOrderTraversal.java
│ ├── cloneGraph.java
│ ├── pacificAtlanticWaterFlow.java
│ ├── removeInvalidParentheses.java
│ ├── shortestDistanceFromAllBuildings.java
│ ├── symmetricTree.java
│ └── wallsAndGates.java
├── DepthFirstSearch
│ ├── balancedBinaryTree.java
│ ├── battleshipsInABoard.java
│ ├── convertSortedArrayToBinarySearchTree.java
│ ├── maximumDepthOfABinaryTree.java
│ ├── numberOfIslands.java
│ ├── populatingNextRightPointersInEachNode.java
│ └── sameTree.java
├── Design
│ └── zigzagIterator.java
├── DivideAndConquer
│ ├── expressionAddOperators.java
│ └── kthLargestElementInAnArray.java
├── DynamicProgramming
│ ├── bombEnemy.java
│ ├── climbingStairs.java
│ ├── combinationSumIV.java
│ ├── countingBits.java
│ ├── editDistance.java
│ ├── houseRobber.java
│ ├── paintFence.java
│ ├── paintHouseII.java
│ ├── regularExpressionMatching.java
│ ├── sentenceScreenFitting.java
│ ├── uniqueBinarySearchTrees.java
│ └── wordBreak.java
├── HashTable
│ ├── binaryTreeVerticalOrderTraversal.java
│ ├── findTheDifference.java
│ ├── groupAnagrams.java
│ ├── groupShiftedStrings.java
│ ├── islandPerimeter.java
│ ├── loggerRateLimiter.java
│ ├── maximumSizeSubarraySumEqualsK.java
│ ├── minimumWindowSubstring.java
│ ├── sparseMatrixMultiplication.java
│ ├── strobogrammaticNumber.java
│ ├── twoSum.java
│ └── uniqueWordAbbreviation.java
├── LinkedList
│ ├── addTwoNumbers.java
│ ├── deleteNodeInALinkedList.java
│ ├── mergeKSortedLists.java
│ ├── palindromeLinkedList.java
│ ├── plusOneLinkedList.java
│ ├── README.md
│ └── reverseLinkedList.java
├── Queue
│ └── movingAverageFromDataStream.java
├── README.md
├── Sort
│ ├── meetingRoomsII.java
│ └── meetingRooms.java
├── Stack
│ ├── binarySearchTreeIterator.java
│ ├── decodeString.java
│ ├── flattenNestedListIterator.java
│ └── trappingRainWater.java
├── String
│ ├── addBinary.java
│ ├── countAndSay.java
│ ├── decodeWays.java
│ ├── editDistance.java
│ ├── integerToEnglishWords.java
│ ├── longestPalindrome.java
│ ├── longestSubstringWithAtMostKDistinctCharacters.java
│ ├── minimumWindowSubstring.java
│ ├── multiplyString.java
│ ├── oneEditDistance.java
│ ├── palindromePermutation.java
│ ├── README.md
│ ├── reverseVowelsOfAString.java
│ ├── romanToInteger.java
│ ├── validPalindrome.java
│ └── validParentheses.java
├── Tree
│ ├── binaryTreeMaximumPathSum.java
│ ├── binaryTreePaths.java
│ ├── inorderSuccessorInBST.java
│ ├── invertBinaryTree.java
│ ├── lowestCommonAncestorOfABinaryTree.java
│ ├── sumOfLeftLeaves.java
│ └── validateBinarySearchTree.java
├── Trie
│ ├── addAndSearchWordDataStructureDesign.java
│ ├── implementTrie.java
│ └── wordSquares.java
└── TwoPointers
├── 3Sum.java
├── 3SumSmaller.java
├── mergeSortedArray.java
├── minimumSizeSubarraySum.java
├── moveZeros.java
├── removeDuplicatesFromSortedArray.java
├── reverseString.java
└── sortColors.java
18 directories, 124 files
```
================================================
FILE: README.md
================================================
# Interviews
> Pass your coding interviews with [The Daily Byte](https://thedailybyte.dev/?ref=kevin)
> [30,000+ Software Engineers have trusted us with their interview prep](https://thedailybyte.dev/?ref=kevin).
>
> Maintainer - [Kevin Naughton Jr.](https://github.com/kdn251)
## Translations
- [简体中文](./README-zh-cn.md)
## Table of Contents
- [YouTube](#youtube)
- [The Daily Byte](#the-daily-byte)
- [Instagram](#instagram)
- [Articles](#articles)
- [Online Judges](#online-judges)
- [Live Coding Practice](#live-coding-practice)
- [Data Structures](#data-structures)
- [Algorithms](#algorithms)
- [Greedy Algorithms](#greedy-algorithms)
- [Bitmasks](#bitmasks)
- [Runtime Analysis](#runtime-analysis)
- [Video Lectures](#video-lectures)
- [Interview Books](#interview-books)
- [Computer Science News](#computer-science-news)
- [Directory Tree](#directory-tree)
## YouTube
* [Kevin Naughton Jr.](https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g)
## The Daily Byte
* [FAANG Interview Prep](https://thedailybyte.dev/?ref=kevin)
## Instagram
* [Kevin Naughton Jr.](https://www.instagram.com/kevinnaughtonjr)
## Online Judges
* [LeetCode](https://leetcode.com/)
* [Virtual Judge](https://vjudge.net/)
* [CareerCup](https://www.careercup.com/)
* [HackerRank](https://www.hackerrank.com/)
* [CodeFights](https://codefights.com/)
* [Kattis](https://open.kattis.com/)
* [HackerEarth](https://www.hackerearth.com)
* [Codility](https://codility.com/programmers/lessons/1-iterations/)
* [Code Forces](http://codeforces.com/)
* [Code Chef](https://www.codechef.com/)
* [Sphere Online Judge - SPOJ](http://www.spoj.com/)
* [InterviewBit](https://www.interviewbit.com/)
## Live Mock Interviews
* [The Daily Byte](https://thedailybyte.dev/mock-interview)
## Live Coding Practice
* [The Daily Byte](https://thedailybyte.dev/?ref=kevin)
* [Pramp](https://www.pramp.com/ref/gt4)
* [Gainlo](http://www.gainlo.co/#!/)
* [Refdash](https://refdash.com/)
* [Interviewing.io](https://www.interviewing.io/)
## Data Structures
### Linked List
* A *Linked List* is a linear collection of data elements, called nodes, each
pointing to the next node by means of a pointer. It is a data structure
consisting of a group of nodes which together represent a sequence.
* **Singly-linked list**: linked list in which each node points to the next node and the last node points to null
* **Doubly-linked list**: linked list in which each node has two pointers, p and n, such that p points to the previous node and n points to the next node; the last node's n pointer points to null
* **Circular-linked list**: linked list in which each node points to the next node and the last node points back to the first node
* Time Complexity:
* Access: `O(n)`
* Search: `O(n)`
* Insert: `O(1)`
* Remove: `O(1)`
### Stack
* A *Stack* is a collection of elements, with two principle operations: *push*, which adds to the collection, and
*pop*, which removes the most recently added element
* **Last in, first out data structure (LIFO)**: the most recently added object is the first to be removed
* Time Complexity:
* Access: `O(n)`
* Search: `O(n)`
* Insert: `O(1)`
* Remove: `O(1)`
### Queue
* A *Queue* is a collection of elements, supporting two principle operations: *enqueue*, which inserts an element
into the queue, and *dequeue*, which removes an element from the queue
* **First in, first out data structure (FIFO)**: the oldest added object is the first to be removed
* Time Complexity:
* Access: `O(n)`
* Search: `O(n)`
* Insert: `O(1)`
* Remove: `O(1)`
### Tree
* A *Tree* is an undirected, connected, acyclic graph
### Binary Tree
* A *Binary Tree* is a tree data structure in which each node has at most two children, which are referred to as
the *left child* and *right child*
* **Full Tree**: a tree in which every node has either 0 or 2 children
* **Perfect Binary Tree**: a binary tree in which all interior nodes have two children and all leave have the same depth
* **Complete Tree**: a binary tree in which every level *except possibly the last* is full and all nodes in the last
level are as far left as possible
### Binary Search Tree
* A binary search tree, sometimes called BST, is a type of binary tree which maintains the property that the value in each
node must be greater than or equal to any value stored in the left sub-tree, and less than or equal to any value stored
in the right sub-tree
* Time Complexity:
* Access: `O(log(n))`
* Search: `O(log(n))`
* Insert: `O(log(n))`
* Remove: `O(log(n))`
### Trie
* A trie, sometimes called a radix or prefix tree, is a kind of search tree that is used to store a dynamic set or associative
array where the keys are usually Strings. No node in the tree stores the key associated with that node; instead, its position
in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the String associated
with that node, and the root is associated with the empty String.

### Fenwick Tree
* A Fenwick tree, sometimes called a binary indexed tree, is a tree in concept, but in practice is implemented as an implicit data
structure using an array. Given an index in the array representing a vertex, the index of a vertex's parent or child is calculated
through bitwise operations on the binary representation of its index. Each element of the array contains the pre-calculated sum of
a range of values, and by combining that sum with additional ranges encountered during an upward traversal to the root, the prefix
sum is calculated
* Time Complexity:
* Range Sum: `O(log(n))`
* Update: `O(log(n))`

### Segment Tree
* A Segment tree, is a tree data structure for storing intervals, or segments. It allows querying which of the stored segments contain
a given point
* Time Complexity:
* Range Query: `O(log(n))`
* Update: `O(log(n))`

### Heap
* A *Heap* is a specialized tree based structure data structure that satisfies the *heap* property: if A is a parent node of
B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap.
A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater
than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than
or equal to those of the children and the lowest key is in the root node
* Time Complexity:
* Access Max / Min: `O(1)`
* Insert: `O(log(n))`
* Remove Max / Min: `O(log(n))`
### Hashing
* *Hashing* is used to map data of an arbitrary size to data of a fixed size. The values returned by a hash
function are called hash values, hash codes, or simply hashes. If two keys map to the same value, a collision occurs
* **Hash Map**: a *hash map* is a structure that can map keys to values. A hash map uses a hash function to compute
an index into an array of buckets or slots, from which the desired value can be found.
* Collision Resolution
* **Separate Chaining**: in *separate chaining*, each bucket is independent, and contains a list of entries for each index. The
time for hash map operations is the time to find the bucket (constant time), plus the time to iterate through the list
* **Open Addressing**: in *open addressing*, when a new entry is inserted, the buckets are examined, starting with the
hashed-to-slot and proceeding in some sequence, until an unoccupied slot is found. The name open addressing refers to
the fact that the location of an item is not always determined by its hash value

### Graph
* A *Graph* is an ordered pair of G = (V, E) comprising a set V of vertices or nodes together with a set E of edges or arcs,
which are 2-element subsets of V (i.e. an edge is associated with two vertices, and that association takes the form of the
unordered pair comprising those two vertices)
* **Undirected Graph**: a graph in which the adjacency relation is symmetric. So if there exists an edge from node u to node
v (u -> v), then it is also the case that there exists an edge from node v to node u (v -> u)
* **Directed Graph**: a graph in which the adjacency relation is not symmetric. So if there exists an edge from node u to node v
(u -> v), this does *not* imply that there exists an edge from node v to node u (v -> u)
## Algorithms
### Sorting
#### Quicksort
* Stable: `No`
* Time Complexity:
* Best Case: `O(nlog(n))`
* Worst Case: `O(n^2)`
* Average Case: `O(nlog(n))`

#### Mergesort
* *Mergesort* is also a divide and conquer algorithm. It continuously divides an array into two halves, recurses on both the
left subarray and right subarray and then merges the two sorted halves
* Stable: `Yes`
* Time Complexity:
* Best Case: `O(nlog(n))`
* Worst Case: `O(nlog(n))`
* Average Case: `O(nlog(n))`

#### Bucket Sort
* *Bucket Sort* is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket
is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm
* Time Complexity:
* Best Case: `Ω(n + k)`
* Worst Case: `O(n^2)`
* Average Case:`Θ(n + k)`

#### Radix Sort
* *Radix Sort* is a sorting algorithm that like bucket sort, distributes elements of an array into a number of buckets. However, radix
sort differs from bucket sort by 're-bucketing' the array after the initial pass as opposed to sorting each bucket and merging
* Time Complexity:
* Best Case: `Ω(nk)`
* Worst Case: `O(nk)`
* Average Case: `Θ(nk)`
### Graph Algorithms
#### Depth First Search
* *Depth First Search* is a graph traversal algorithm which explores as far as possible along each branch before backtracking
* Time Complexity: `O(|V| + |E|)`

#### Breadth First Search
* *Breadth First Search* is a graph traversal algorithm which explores the neighbor nodes first, before moving to the next
level neighbors
* Time Complexity: `O(|V| + |E|)`

#### Topological Sort
* *Topological Sort* is the linear ordering of a directed graph's nodes such that for every edge from node u to node v, u
comes before v in the ordering
* Time Complexity: `O(|V| + |E|)`
#### Dijkstra's Algorithm
* *Dijkstra's Algorithm* is an algorithm for finding the shortest path between nodes in a graph
* Time Complexity: `O(|V|^2)`

#### Bellman-Ford Algorithm
* *Bellman-Ford Algorithm* is an algorithm that computes the shortest paths from a single source node to all other nodes in a weighted graph
* Although it is slower than Dijkstra's, it is more versatile, as it is capable of handling graphs in which some of the edge weights are
negative numbers
* Time Complexity:
* Best Case: `O(|E|)`
* Worst Case: `O(|V||E|)`

#### Floyd-Warshall Algorithm
* *Floyd-Warshall Algorithm* is an algorithm for finding the shortest paths in a weighted graph with positive or negative edge weights, but
no negative cycles
* A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between *all* pairs of nodes
* Time Complexity:
* Best Case: `O(|V|^3)`
* Worst Case: `O(|V|^3)`
* Average Case: `O(|V|^3)`
#### Prim's Algorithm
* *Prim's Algorithm* is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. In other words, Prim's find a
subset of edges that forms a tree that includes every node in the graph
* Time Complexity: `O(|V|^2)`

#### Kruskal's Algorithm
* *Kruskal's Algorithm* is also a greedy algorithm that finds a minimum spanning tree in a graph. However, in Kruskal's, the graph does not
have to be connected
* Time Complexity: `O(|E|log|V|)`

## Greedy Algorithms
* *Greedy Algorithms* are algorithms that make locally optimal choices at each step in the hope of eventually reaching the globally optimal solution
* Problems must exhibit two properties in order to implement a Greedy solution:
* Optimal Substructure
* An optimal solution to the problem contains optimal solutions to the given problem's subproblems
* The Greedy Property
* An optimal solution is reached by "greedily" choosing the locally optimal choice without ever reconsidering previous choices
* Example - Coin Change
* Given a target amount V cents and a list of denominations of n coins, i.e. we have coinValue[i] (in cents) for coin types i from [0...n - 1],
what is the minimum number of coins that we must use to represent amount V? Assume that we have an unlimited supply of coins of any type
* Coins - Penny (1 cent), Nickel (5 cents), Dime (10 cents), Quarter (25 cents)
* Assume V = 41. We can use the Greedy algorithm of continuously selecting the largest coin denomination less than or equal to V, subtract that
coin's value from V, and repeat.
* V = 41 | 0 coins used
* V = 16 | 1 coin used (41 - 25 = 16)
* V = 6 | 2 coins used (16 - 10 = 6)
* V = 1 | 3 coins used (6 - 5 = 1)
* V = 0 | 4 coins used (1 - 1 = 0)
* Using this algorithm, we arrive at a total of 4 coins which is optimal
## Bitmasks
* Bitmasking is a technique used to perform operations at the bit level. Leveraging bitmasks often leads to faster runtime complexity and
helps limit memory usage
* Test kth bit: `s & (1 << k);`
* Set kth bit: `s |= (1 << k);`
* Turn off kth bit: `s &= ~(1 << k);`
* Toggle kth bit: `s ^= (1 << k);`
* Multiple by 2n: `s << n;`
* Divide by 2n: `s >> n;`
* Intersection: `s & t;`
* Union: `s | t;`
* Set Subtraction: `s & ~t;`
* Extract lowest set bit: `s & (-s);`
* Extract lowest unset bit: `~s & (s + 1);`
* Swap Values:
```
x ^= y;
y ^= x;
x ^= y;
```
## Runtime Analysis
#### Big O Notation
* *Big O Notation* is used to describe the upper bound of a particular algorithm. Big O is used to describe worst case scenarios

#### Little O Notation
* *Little O Notation* is also used to describe an upper bound of a particular algorithm; however, Little O provides a bound
that is not asymptotically tight
#### Big Ω Omega Notation
* *Big Omega Notation* is used to provide an asymptotic lower bound on a particular algorithm

#### Little ω Omega Notation
* *Little Omega Notation* is used to provide a lower bound on a particular algorithm that is not asymptotically tight
#### Theta Θ Notation
* *Theta Notation* is used to provide a bound on a particular algorithm such that it can be "sandwiched" between
two constants (one for an upper limit and one for a lower limit) for sufficiently large values

## Video Lectures
* Data Structures
* [UC Berkeley Data Structures](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22)
* [MIT Advanced Data Structures](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf&index=1)
* Algorithms
* [MIT Introduction to Algorithms](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&index=1)
* [MIT Advanced Algorithms](https://www.youtube.com/playlist?list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c)
* [UC Berkeley Algorithms](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22)
## Interview Books
* [Competitive Programming 3 - Steven Halim & Felix Halim](https://www.amazon.com/Competitive-Programming-3rd-Steven-Halim/dp/B00FG8MNN8)
* [Cracking The Coding Interview - Gayle Laakmann McDowell](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?s=books&ie=UTF8)
* [Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro](https://www.amazon.com/Cracking-PM-Interview-Product-Technology-ebook/dp/B00ISYMUR6/ref=sr_1_1?s=books&ie=UTF8)
* [Introduction to Algorithms - Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest & Clifford Stein](https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/ref=sr_1_1?ie=UTF8&qid=1490295989&sr=8-1&keywords=Introduction+to+Algorithms)
## Computer Science News
* [Hacker News](https://news.ycombinator.com/)
* [Lobsters](https://lobste.rs/)
## Directory Tree
```
.
├── Array
│ ├── bestTimeToBuyAndSellStock.java
│ ├── findTheCelebrity.java
│ ├── gameOfLife.java
│ ├── increasingTripletSubsequence.java
│ ├── insertInterval.java
│ ├── longestConsecutiveSequence.java
│ ├── maximumProductSubarray.java
│ ├── maximumSubarray.java
│ ├── mergeIntervals.java
│ ├── missingRanges.java
│ ├── productOfArrayExceptSelf.java
│ ├── rotateImage.java
│ ├── searchInRotatedSortedArray.java
│ ├── spiralMatrixII.java
│ ├── subsetsII.java
│ ├── subsets.java
│ ├── summaryRanges.java
│ ├── wiggleSort.java
│ └── wordSearch.java
├── Backtracking
│ ├── androidUnlockPatterns.java
│ ├── generalizedAbbreviation.java
│ └── letterCombinationsOfAPhoneNumber.java
├── BinarySearch
│ ├── closestBinarySearchTreeValue.java
│ ├── firstBadVersion.java
│ ├── guessNumberHigherOrLower.java
│ ├── pow(x,n).java
│ └── sqrt(x).java
├── BitManipulation
│ ├── binaryWatch.java
│ ├── countingBits.java
│ ├── hammingDistance.java
│ ├── maximumProductOfWordLengths.java
│ ├── numberOf1Bits.java
│ ├── sumOfTwoIntegers.java
│ └── utf-8Validation.java
├── BreadthFirstSearch
│ ├── binaryTreeLevelOrderTraversal.java
│ ├── cloneGraph.java
│ ├── pacificAtlanticWaterFlow.java
│ ├── removeInvalidParentheses.java
│ ├── shortestDistanceFromAllBuildings.java
│ ├── symmetricTree.java
│ └── wallsAndGates.java
├── DepthFirstSearch
│ ├── balancedBinaryTree.java
│ ├── battleshipsInABoard.java
│ ├── convertSortedArrayToBinarySearchTree.java
│ ├── maximumDepthOfABinaryTree.java
│ ├── numberOfIslands.java
│ ├── populatingNextRightPointersInEachNode.java
│ └── sameTree.java
├── Design
│ └── zigzagIterator.java
├── DivideAndConquer
│ ├── expressionAddOperators.java
│ └── kthLargestElementInAnArray.java
├── DynamicProgramming
│ ├── bombEnemy.java
│ ├── climbingStairs.java
│ ├── combinationSumIV.java
│ ├── countingBits.java
│ ├── editDistance.java
│ ├── houseRobber.java
│ ├── paintFence.java
│ ├── paintHouseII.java
│ ├── regularExpressionMatching.java
│ ├── sentenceScreenFitting.java
│ ├── uniqueBinarySearchTrees.java
│ └── wordBreak.java
├── HashTable
│ ├── binaryTreeVerticalOrderTraversal.java
│ ├── findTheDifference.java
│ ├── groupAnagrams.java
│ ├── groupShiftedStrings.java
│ ├── islandPerimeter.java
│ ├── loggerRateLimiter.java
│ ├── maximumSizeSubarraySumEqualsK.java
│ ├── minimumWindowSubstring.java
│ ├── sparseMatrixMultiplication.java
│ ├── strobogrammaticNumber.java
│ ├── twoSum.java
│ └── uniqueWordAbbreviation.java
├── LinkedList
│ ├── addTwoNumbers.java
│ ├── deleteNodeInALinkedList.java
│ ├── mergeKSortedLists.java
│ ├── palindromeLinkedList.java
│ ├── plusOneLinkedList.java
│ ├── README.md
│ └── reverseLinkedList.java
├── Queue
│ └── movingAverageFromDataStream.java
├── README.md
├── Sort
│ ├── meetingRoomsII.java
│ └── meetingRooms.java
├── Stack
│ ├── binarySearchTreeIterator.java
│ ├── decodeString.java
│ ├── flattenNestedListIterator.java
│ └── trappingRainWater.java
├── String
│ ├── addBinary.java
│ ├── countAndSay.java
│ ├── decodeWays.java
│ ├── editDistance.java
│ ├── integerToEnglishWords.java
│ ├── longestPalindrome.java
│ ├── longestSubstringWithAtMostKDistinctCharacters.java
│ ├── minimumWindowSubstring.java
│ ├── multiplyString.java
│ ├── oneEditDistance.java
│ ├── palindromePermutation.java
│ ├── README.md
│ ├── reverseVowelsOfAString.java
│ ├── romanToInteger.java
│ ├── validPalindrome.java
│ └── validParentheses.java
├── Tree
│ ├── binaryTreeMaximumPathSum.java
│ ├── binaryTreePaths.java
│ ├── inorderSuccessorInBST.java
│ ├── invertBinaryTree.java
│ ├── lowestCommonAncestorOfABinaryTree.java
│ ├── sumOfLeftLeaves.java
│ └── validateBinarySearchTree.java
├── Trie
│ ├── addAndSearchWordDataStructureDesign.java
│ ├── implementTrie.java
│ └── wordSquares.java
└── TwoPointers
├── 3Sum.java
├── 3SumSmaller.java
├── mergeSortedArray.java
├── minimumSizeSubarraySum.java
├── moveZeros.java
├── removeDuplicatesFromSortedArray.java
├── reverseString.java
└── sortColors.java
18 directories, 124 files
```
================================================
FILE: company/Company.iml
================================================
================================================
FILE: company/adobe/AddDigits.java
================================================
//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
//For example:
//Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
//Follow up:
//Could you do it without any loop/recursion in O(1) runtime?
class AddDigits {
public int addDigits(int num) {
while(num >= 10) {
int temp = 0;
while(num > 0) {
temp += num % 10;
num /= 10;
}
num = temp;
}
return num;
}
}
================================================
FILE: company/adobe/MajorityElement.java
================================================
//Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
//You may assume that the array is non-empty and the majority element always exist in the array.
class MajorityElement {
public int majorityElement(int[] nums) {
if(nums.length == 1) {
return nums[0];
}
HashMap map = new HashMap();
for(int current: nums) {
if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) {
return current;
} else if(map.containsKey(current)) {
map.put(current, map.get(current) + 1);
} else {
map.put(current, 1);
}
}
//no majority element exists
return -1;
}
}
================================================
FILE: company/airbnb/AddTwoNumbers.java
================================================
// You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
// You may assume the two numbers do not contain any leading zero, except the number 0 itself.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1 = l1;
ListNode current2 = l2;
ListNode head = new ListNode(0);
ListNode currentHead = head;
int sum = 0;
while(current1 != null || current2 != null) {
sum /= 10;
if(current1 != null) {
sum += current1.val;
current1 = current1.next;
}
if(current2 != null) {
sum += current2.val;
current2 = current2.next;
}
currentHead.next = new ListNode(sum % 10);
currentHead = currentHead.next;
}
if(sum / 10 == 1) {
currentHead.next = new ListNode(1);
}
return head.next;
}
}
================================================
FILE: company/airbnb/ContainsDuplicate.java
================================================
//Given an array of integers, find if the array contains any duplicates. Your function should return
//true if any value appears at least twice in the array, and it should return false if every element is distinct.
class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
HashMap map = new HashMap();
for(int i: nums) {
if(map.containsKey(i)) {
return true;
} else {
map.put(i, 1);
}
}
return false;
}
}
================================================
FILE: company/airbnb/ContainsDuplicatesII.java
================================================
//Given an array of integers and an integer k, find out whether there are two distinct indices i and
//j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
class ContainsDuplicatesII {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap map = new HashMap();
for(int i = 0; i < nums.length; i++) {
int current = nums[i];
if(map.containsKey(current) && i - map.get(current) <= k) {
return true;
} else {
map.put(current, i);
}
}
return false;
}
}
================================================
FILE: company/airbnb/ConvertSortedArrayToBinarySearchTree.java
================================================
// Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) {
return null;
}
TreeNode root = helper(nums, 0, nums.length - 1);
return root;
}
private TreeNode helper(int[] nums, int start, int end) {
if(start <= end) {
int mid = (start + end) / 2;
TreeNode current = new TreeNode(nums[mid]);
current.left = helper(nums, start, mid - 1);
current.right = helper(nums, mid + 1, end);
return current;
}
return null;
}
}
================================================
FILE: company/airbnb/HouseRobber.java
================================================
// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
// Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
public class HouseRobber {
public int rob(int[] nums) {
if(nums.length == 0) {
return 0;
}
if(nums.length == 1) {
return nums[0];
}
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = nums[0] > nums[1] ? nums[0] : nums[1];
for(int i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[dp.length - 1];
}
}
================================================
FILE: company/airbnb/MergeKSortedLists.java
================================================
// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) {
return null;
}
PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
================================================
FILE: company/airbnb/ValidParentheses.java
================================================
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack stack = new Stack();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
================================================
FILE: company/amazon/3Sum.java
================================================
// Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
public class 3Sum {
public List> threeSum(int[] nums) {
List> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
int target = -nums[i];
while(j < k) {
if(nums[j] + nums[k] == target) {
ArrayList temp = new ArrayList();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
j++;
k--;
while(j < k && nums[j] == nums[j - 1]) {
j++;
}
while(j < k && nums[k] == nums[k + 1]) {
k--;
}
} else if(nums[j] + nums[k] > target) {
k--;
} else {
j++;
}
}
}
return result;
}
}
================================================
FILE: company/amazon/AddTwoNumbers.java
================================================
// You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
// You may assume the two numbers do not contain any leading zero, except the number 0 itself.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1 = l1;
ListNode current2 = l2;
ListNode head = new ListNode(0);
ListNode currentHead = head;
int sum = 0;
while(current1 != null || current2 != null) {
sum /= 10;
if(current1 != null) {
sum += current1.val;
current1 = current1.next;
}
if(current2 != null) {
sum += current2.val;
current2 = current2.next;
}
currentHead.next = new ListNode(sum % 10);
currentHead = currentHead.next;
}
if(sum / 10 == 1) {
currentHead.next = new ListNode(1);
}
return head.next;
}
}
================================================
FILE: company/amazon/BestTimeToBuyAndSellStock.java
================================================
// Say you have an array for which the ith element is the price of a given stock on day i.
// If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
// Example 1:
// Input: [7, 1, 5, 3, 6, 4]
// Output: 5
// max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
// Example 2:
// Input: [7, 6, 4, 3, 1]
// Output: 0
// In this case, no transaction is done, i.e. max profit = 0.
public class BestTimeToBuyAndSellStock {
public int maxProfit(int[] prices) {
//Kadane's algorithm
if(prices.length == 0) {
return 0;
}
int max = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++) {
if(prices[i] > min) {
max = Math.max(max, prices[i] - min);
} else {
min = prices[i];
}
}
return max;
}
}
================================================
FILE: company/amazon/BinaryTreeLevelOrderTraversal.java
================================================
// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
// For example:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// return its level order traversal as:
// [
// [3],
// [9,20],
// [15,7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeLevelOrderTraversal {
public List> levelOrder(TreeNode root) {
List> result = new ArrayList>();
if(root == null) {
return result;
}
Queue queue = new LinkedList();
queue.add(root);
List tempList = new ArrayList();
tempList.add(root.val);
result.add(tempList);
while(!queue.isEmpty()) {
Queue currentLevel = new LinkedList();
List list = new ArrayList();
while(!queue.isEmpty()) {
TreeNode current = queue.remove();
if(current.left != null) {
currentLevel.add(current.left);
list.add(current.left.val);
}
if(current.right != null) {
currentLevel.add(current.right);
list.add(current.right.val);
}
}
if(list.size() > 0) {
result.add(list);
}
queue = currentLevel;
}
return result;
}
}
================================================
FILE: company/amazon/EncodeAndDecodeTinyURL.java
================================================
//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
//and it returns a short URL such as http://tinyurl.com/4e9iAk.
//
//Design the encode and decode methods for the TinyURL service. There is no restriction on how your
//encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL
//and the tiny URL can be decoded to the original URL.
public class EncodeAndDecodeTinyURL {
HashMap map = new HashMap();
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 1;
public String getKey() {
String key = "";
while(count > 0) {
count--;
key += characters.charAt(count);
count /= characters.length();
}
return key;
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
map.put(key, longUrl);
count++;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
================================================
FILE: company/amazon/FirstUniqueCharacterInAString.java
================================================
//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//
//Examples:
//
//s = "leetcode"
//return 0.
//
//s = "loveleetcode",
//return 2.
//Note: You may assume the string contain only lowercase letters.
class FirstUniqueCharacterInAString {
public int firstUniqChar(String s) {
HashMap characters = new HashMap();
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if(characters.containsKey(current)) {
characters.put(current, -1);
} else {
characters.put(current, i);
}
}
int min = Integer.MAX_VALUE;
for(char c: characters.keySet()) {
if(characters.get(c) > -1 && characters.get(c) < min) {
min = characters.get(c);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
================================================
FILE: company/amazon/GroupAnagrams.java
================================================
// Given an array of strings, group anagrams together.
// For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Return:
// [
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
// ]
// Note: All inputs will be in lower-case.
public class GroupAnagrams {
public List> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0) {
return new ArrayList>();
}
HashMap> map = new HashMap>();
Arrays.sort(strs);
for(String s : strs) {
char[] characters = s.toCharArray();
Arrays.sort(characters);
String key = String.valueOf(characters);
if(!map.containsKey(key)) {
map.put(key, new ArrayList());
}
map.get(key).add(s);
}
return new ArrayList>(map.values());
}
}
================================================
FILE: company/amazon/InsertDeleteGetRandomO1.java
================================================
//Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap map;
ArrayList values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap();
values = new ArrayList();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
================================================
FILE: company/amazon/KthLargestElementInAnArray.java
================================================
// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
// For example,
// Given [3,2,1,5,6,4] and k = 2, return 5.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ array's length.
public class KthLargestElementInAnArray {
public int findKthLargest(int[] nums, int k) {
int length = nums.length;
Arrays.sort(nums);
return nums[length - k];
}
}
================================================
FILE: company/amazon/LetterCombinationsOfAPhoneNumber.java
================================================
// Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// 2 - abc
// 3 - def
// 4 - ghi
// 5 - jkl
// 6 - mno
// 7 - pqrs
// 8 - tuv
// 9 - wxyz
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class LetterCombinationsOfAPhoneNumber {
public List letterCombinations(String digits) {
List result = new ArrayList();
if(digits == null || digits.length() == 0) {
return result;
}
String[] mapping = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
letterCombinationsRecursive(result, digits, "", 0, mapping);
return result;
}
public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) {
if(index == digits.length()) {
result.add(current);
return;
}
String letters = mapping[digits.charAt(index) - '0'];
for(int i = 0; i < letters.length(); i++) {
letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
}
}
}
================================================
FILE: company/amazon/LinkedListCycle.java
================================================
//Given a linked list, determine if it has a cycle in it.
//Follow up:
//Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast != slow) {
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}
================================================
FILE: company/amazon/LongestPalindromicSubstring.java
================================================
//Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
//Example:
//Input: "babad"
//Output: "bab"
//Note: "aba" is also a valid answer.
//Example:
//Input: "cbbd"
//Output: "bb"
class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
String longestPalindromicSubstring = "";
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
longestPalindromicSubstring = s.substring(i, j);
}
}
}
return longestPalindromicSubstring;
}
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}
================================================
FILE: company/amazon/LowestCommonAncestorOfABinaryTree.java
================================================
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
// _______3______
// / \
// ___5__ ___1__
// / \ / \
// 6 _2 0 8
// / \
// 7 4
// For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class LowestCommonAncestorOfABinaryTree {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) {
return root;
}
return left == null ? right : left;
}
}
================================================
FILE: company/amazon/MergeKSortedLists.java
================================================
// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) {
return null;
}
PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
return 0;
}
//set current index to 0
grid[i][j] = '0';
// sink all neighbors of current index
sink(grid, i + 1, j);
sink(grid, i - 1, j);
sink(grid, i, j + 1);
sink(grid, i, j - 1);
//increment number of islands
return 1;
}
}
================================================
FILE: company/amazon/PalindromeLinkedList.java
================================================
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
Stack stack = new Stack();
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
stack.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
if(stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
================================================
FILE: company/amazon/ProductOfArrayExceptSelf.java
================================================
// Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// Solve it without division and in O(n).
// For example, given [1,2,3,4], return [24,12,8,6].
// Follow up:
// Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
public class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 1;
for(int i = 0; i < nums.length; i++) {
if(i > 0) {
left *= nums[i - 1];
}
result[i] = left;
}
int right = 1;
for(int i = n - 1; i >= 0; i--) {
if(i < n - 1) {
right *= nums[i + 1];
}
result[i] *= right;
}
return result;
}
}
================================================
FILE: company/amazon/ReverseLinkedList.java
================================================
// Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
================================================
FILE: company/amazon/RotateImage.java
================================================
// You are given an n x n 2D matrix representing an image.
// Rotate the image by 90 degrees (clockwise).
// Follow up:
// Could you do this in-place?
public class RotateImage {
public void rotate(int[][] matrix) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix[0].length - 1 - j];
matrix[i][matrix[0].length - 1 - j] = temp;
}
}
}
}
================================================
FILE: company/amazon/Subsets.java
================================================
// Given a set of distinct integers, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
public class Subsets {
public List> subsets(int[] nums) {
List> result = new ArrayList<>();
recurse(result, nums, new Stack<>(), 0);
return result;
}
private void recurse(List> result, int[] nums, Stack path, int position) {
if(position == nums.length) {
result.add(new ArrayList<>(path));
return;
}
path.push(nums[position]);
recurse(result, nums, path, position + 1);
path.pop();
recurse(result, nums, path, position + 1);
}
}
================================================
FILE: company/amazon/TrappingRainWater.java
================================================
// Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
// For example,
// Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
public class TrappingRainWater {
public int trap(int[] height) {
int water = 0;
int leftIndex = 0;
int rightIndex = height.length - 1;
int leftMax = 0;
int rightMax = 0;
while(leftIndex <= rightIndex) {
leftMax = Math.max(leftMax, height[leftIndex]);
rightMax = Math.max(rightMax, height[rightIndex]);
if(leftMax < rightMax) {
water += leftMax - height[leftIndex];
leftIndex++;
} else {
water += rightMax - height[rightIndex];
rightIndex--;
}
}
return water;
}
}
================================================
FILE: company/amazon/TwoSum.java
================================================
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
================================================
FILE: company/amazon/ValidParentheses.java
================================================
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack stack = new Stack();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
================================================
FILE: company/amazon/ValidateBinarySearchTree.java
================================================
// Given a binary tree, determine if it is a valid binary search tree (BST).
// Assume a BST is defined as follows:
// The left subtree of a node contains only nodes with keys less than the node's key.
// The right subtree of a node contains only nodes with keys greater than the node's key.
// Both the left and right subtrees must also be binary search trees.
// Example 1:
// 2
// / \
// 1 3
// Binary tree [2,1,3], return true.
// Example 2:
// 1
// / \
// 2 3
// Binary tree [1,2,3], return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ValidateBinarySearchTree {
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) {
if(root == null) {
return true;
} else if(root.val >= maxValue || root.val <= minValue) {
return false;
} else {
return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue);
}
}
}
================================================
FILE: company/amazon/WordBreak.java
================================================
// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
// For example, given
// s = "leetcode",
// dict = ["leet", "code"].
// Return true because "leetcode" can be segmented as "leet code".
public class WordBreak {
public boolean wordBreak(String s, Set wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
================================================
FILE: company/apple/ReverseWordsInAString.java
================================================
//Given an input string, reverse the string word by word.
//For example,
//Given s = "the sky is blue",
//return "blue is sky the".
public class ReverseWordsInAString {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
String result = "";
for(int i = words.length - 1; i > 0; i--) {
result += words[i] + " ";
}
return result + words[0];
}
}
================================================
FILE: company/apple/ValidSudoku.java
================================================
//Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx)
//The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
//A partially filled sudoku which is valid.
//Note:
//A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < board.length; i++){
HashSet rows = new HashSet();
HashSet columns = new HashSet();
HashSet box = new HashSet();
for (int j = 0; j < board[0].length; j++){
if(board[i][j] != '.' && !rows.add(board[i][j])) {
return false;
}
if(board[j][i]!='.' && !columns.add(board[j][i])) {
return false;
}
int rowIndex = (i / 3) * 3;
int columnIndex = (i % 3) * 3;
if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) {
return false;
}
}
}
return true;
}
}
================================================
FILE: company/bloomberg/FirstUniqueCharacterInAString.java
================================================
//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//
//Examples:
//
//s = "leetcode"
//return 0.
//
//s = "loveleetcode",
//return 2.
//Note: You may assume the string contain only lowercase letters.
class FirstUniqueCharacterInAString {
public int firstUniqChar(String s) {
HashMap characters = new HashMap();
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if(characters.containsKey(current)) {
characters.put(current, -1);
} else {
characters.put(current, i);
}
}
int min = Integer.MAX_VALUE;
for(char c: characters.keySet()) {
if(characters.get(c) > -1 && characters.get(c) < min) {
min = characters.get(c);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
================================================
FILE: company/bloomberg/LinkedListCycle.java
================================================
//Given a linked list, determine if it has a cycle in it.
//Follow up:
//Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast != slow) {
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}
================================================
FILE: company/bloomberg/LongestPalindromicSubstring.java
================================================
//Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
//Example:
//Input: "babad"
//Output: "bab"
//Note: "aba" is also a valid answer.
//Example:
//Input: "cbbd"
//Output: "bb"
class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
String longestPalindromicSubstring = "";
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
longestPalindromicSubstring = s.substring(i, j);
}
}
}
return longestPalindromicSubstring;
}
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}
================================================
FILE: company/bloomberg/MinStack.java
================================================
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
================================================
FILE: company/bloomberg/ReverseWordsInAString.java
================================================
//Given an input string, reverse the string word by word.
//For example,
//Given s = "the sky is blue",
//return "blue is sky the".
public class ReverseWordsInAString {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
String result = "";
for(int i = words.length - 1; i > 0; i--) {
result += words[i] + " ";
}
return result + words[0];
}
}
================================================
FILE: company/bloomberg/UniquePaths.java
================================================
//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
//
//The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
//
//How many possible unique paths are there?
class UniquePaths {
public int uniquePaths(int m, int n) {
Integer[][] map = new Integer[m][n];
//only 1 way to get to ith row, 0th column (move down)
for(int i = 0; i < m; i++){
map[i][0] = 1;
}
//only 1 way to get to ith column, 0th row (move right)
for(int j= 0; j < n; j++){
map[0][j]=1;
}
//x ways to get to ith row, jth column (# of ways to get to
//ith - 1 row, jth column + # of ways to get to jth - 1 column
//ith column
for(int i = 1;i < m; i++){
for(int j = 1; j < n; j++){
map[i][j] = map[i - 1][j] + map[i][j - 1];
}
}
return map[m - 1][n - 1];
}
}
================================================
FILE: company/facebook/3Sum.java
================================================
// Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
public class 3Sum {
public List> threeSum(int[] nums) {
List> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
int target = -nums[i];
while(j < k) {
if(nums[j] + nums[k] == target) {
ArrayList temp = new ArrayList();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
j++;
k--;
while(j < k && nums[j] == nums[j - 1]) {
j++;
}
while(j < k && nums[k] == nums[k + 1]) {
k--;
}
} else if(nums[j] + nums[k] > target) {
k--;
} else {
j++;
}
}
}
return result;
}
}
================================================
FILE: company/facebook/AddAndSearchWordDataStructureDesign.java
================================================
// Design a data structure that supports the following two operations:
// void addWord(word)
// bool search(word)
// search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
// For example:
// addWord("bad")
// addWord("dad")
// addWord("mad")
// search("pad") -> false
// search("bad") -> true
// search(".ad") -> true
// search("b..") -> true
// Note:
// You may assume that all words are consist of lowercase letters a-z.
public class AddAndSearchWordDataStructure {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public String item = "";
}
private TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.item = word;
}
public boolean search(String word) {
return match(word.toCharArray(), 0, root);
}
private boolean match(char[] chs, int k, TrieNode node) {
if (k == chs.length) {
return !node.item.equals("");
}
if (chs[k] != '.') {
return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']);
} else {
for (int i = 0; i < node.children.length; i++) {
if (node.children[i] != null) {
if (match(chs, k + 1, node.children[i])) {
return true;
}
}
}
}
return false;
}
}
================================================
FILE: company/facebook/AddBinary.java
================================================
// Given two binary strings, return their sum (also a binary string).
// For example,
// a = "11"
// b = "1"
// Return "100"
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while(i >= 0 || j >= 0) {
int sum = carry;
if(i >= 0) {
sum += a.charAt(i--) - '0';
}
if(j >= 0) {
sum += b.charAt(j--) - '0';
}
result.append(sum % 2);
carry = sum / 2;
}
if(carry != 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
================================================
FILE: company/facebook/BestTimeToBuyAndSellStock.java
================================================
// Say you have an array for which the ith element is the price of a given stock on day i.
// If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
// Example 1:
// Input: [7, 1, 5, 3, 6, 4]
// Output: 5
// max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
// Example 2:
// Input: [7, 6, 4, 3, 1]
// Output: 0
// In this case, no transaction is done, i.e. max profit = 0.
public class BestTimeToBuyAndSellStock {
public int maxProfit(int[] prices) {
//Kadane's algorithm
if(prices.length == 0) {
return 0;
}
int max = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++) {
if(prices[i] > min) {
max = Math.max(max, prices[i] - min);
} else {
min = prices[i];
}
}
return max;
}
}
================================================
FILE: company/facebook/BinarySearchTreeIterator.java
================================================
// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
// Calling next() will return the next smallest number in the BST.
// Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinarySearchTreeIterator {
Stack stack;
public BSTIterator(TreeNode root) {
stack = new Stack();
while(root != null) {
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return stack.isEmpty() ? false : true;
}
/** @return the next smallest number */
public int next() {
TreeNode nextSmallest = stack.pop();
TreeNode addToStack = nextSmallest.right;
while(addToStack != null) {
stack.add(addToStack);
addToStack = addToStack.left;
}
return nextSmallest.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
================================================
FILE: company/facebook/BinaryTreeLevelOrderTraversal.java
================================================
// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
// For example:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// return its level order traversal as:
// [
// [3],
// [9,20],
// [15,7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeLevelOrderTraversal {
public List> levelOrder(TreeNode root) {
List> result = new ArrayList>();
if(root == null) {
return result;
}
Queue queue = new LinkedList();
queue.add(root);
List tempList = new ArrayList();
tempList.add(root.val);
result.add(tempList);
while(!queue.isEmpty()) {
Queue currentLevel = new LinkedList();
List list = new ArrayList();
while(!queue.isEmpty()) {
TreeNode current = queue.remove();
if(current.left != null) {
currentLevel.add(current.left);
list.add(current.left.val);
}
if(current.right != null) {
currentLevel.add(current.right);
list.add(current.right.val);
}
}
if(list.size() > 0) {
result.add(list);
}
queue = currentLevel;
}
return result;
}
}
================================================
FILE: company/facebook/BinaryTreePaths.java
================================================
// Given a binary tree, return all root-to-leaf paths.
// For example, given the following binary tree:
// 1
// / \
// 2 3
// \
// 5
// All root-to-leaf paths are:
// ["1->2->5", "1->3"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths {
public List binaryTreePaths(TreeNode root) {
List result = new ArrayList();
if(root == null) {
return result;
}
helper(new String(), root, result);
return result;
}
public void helper(String current, TreeNode root, List result) {
if(root.left == null && root.right == null) {
result.add(current + root.val);
}
if(root.left != null) {
helper(current + root.val + "->", root.left, result);
}
if(root.right != null) {
helper(current + root.val + "->", root.right, result);
}
}
}
================================================
FILE: company/facebook/BinaryTreeVerticalOrderTraversal.java
================================================
// Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
// If two nodes are in the same row and column, the order should be from left to right.
// Examples:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// /\
// / \
// 9 20
// /\
// / \
// 15 7
// return its vertical order traversal as:
// [
// [9],
// [3,15],
// [20],
// [7]
// ]
// Given binary tree [3,9,8,4,0,1,7],
// 3
// /\
// / \
// 9 8
// /\ /\
// / \/ \
// 4 01 7
// return its vertical order traversal as:
// [
// [4],
// [9],
// [3,0,1],
// [8],
// [7]
// ]
// Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
// 3
// /\
// / \
// 9 8
// /\ /\
// / \/ \
// 4 01 7
// /\
// / \
// 5 2
// return its vertical order traversal as:
// [
// [4],
// [9,5],
// [3,0,1],
// [8,2],
// [7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeVerticalOrderTraversal {
public List> verticalOrder(TreeNode root) {
List> result = new ArrayList<>();
if(root == null) {
return result;
}
Map> map = new HashMap<>();
Queue q = new LinkedList<>();
Queue cols = new LinkedList<>();
q.add(root);
cols.add(0);
int min = 0;
int max = 0;
while(!q.isEmpty()) {
TreeNode node = q.poll();
int col = cols.poll();
if(!map.containsKey(col)) {
map.put(col, new ArrayList());
}
map.get(col).add(node.val);
if(node.left != null) {
q.add(node.left);
cols.add(col - 1);
min = Math.min(min, col - 1);
}
if(node.right != null) {
q.add(node.right);
cols.add(col + 1);
max = Math.max(max, col + 1);
}
}
for(int i = min; i <= max; i++) {
result.add(map.get(i));
}
return result;
}
}
================================================
FILE: company/facebook/CloneGraph.java
================================================
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
// OJ's undirected graph serialization:
// Nodes are labeled uniquely.
// We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
// As an example, consider the serialized graph {0,1,2#1,2#2,2}.
// The graph has a total of three nodes, and therefore contains three parts as separated by #.
// First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
// Second node is labeled as 1. Connect node 1 to node 2.
// Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
// Visually, the graph looks like the following:
// 1
// / \
// / \
// 0 --- 2
// / \
// \_/
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
* };
*/
public class CloneGraph {
public HashMap map = new HashMap();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) {
return null;
}
if(map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(newNode.label, newNode);
for(UndirectedGraphNode neighbor : node.neighbors) {
newNode.neighbors.add(cloneGraph(neighbor));
}
return newNode;
}
}
================================================
FILE: company/facebook/CombinationSumIV.java
================================================
// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
// Example:
// nums = [1, 2, 3]
// target = 4
// The possible combination ways are:
// (1, 1, 1, 1)
// (1, 1, 2)
// (1, 2, 1)
// (1, 3)
// (2, 1, 1)
// (2, 2)
// (3, 1)
// Note that different sequences are counted as different combinations.
// Therefore the output is 7.
// Follow up:
// What if negative numbers are allowed in the given array?
// How does it change the problem?
// What limitation we need to add to the question to allow negative numbers?
public class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for(int i = 1; i < dp.length; i++) {
for(int j = 0; j < nums.length; j++) {
if(i - nums[j] >= 0) {
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
}
================================================
FILE: company/facebook/CountAndSay.java
================================================
// The count-and-say sequence is the sequence of integers beginning as follows:
// 1, 11, 21, 1211, 111221, ...
// 1 is read off as "one 1" or 11.
// 11 is read off as "two 1s" or 21.
// 21 is read off as "one 2, then one 1" or 1211.
// Given an integer n, generate the nth sequence.
// Note: The sequence of integers will be represented as a string.
public class Solution {
public String countAndSay(int n) {
String s = "1";
for(int i = 1; i < n; i++) {
s = helper(s);
}
return s;
}
public String helper(String s) {
StringBuilder sb = new StringBuilder();
char c = s.charAt(0);
int count = 1;
for(int i = 1; i < s.length(); i++) {
if(s.charAt(i) == c) count++;
else {
sb.append(count);
sb.append(c);
c = s.charAt(i);
count = 1;
}
}
sb.append(count);
sb.append(c);
return sb.toString();
}
}
================================================
FILE: company/facebook/DecodeWays.java
================================================
// A message containing letters from A-Z is being encoded to numbers using the following mapping:
// 'A' -> 1
// 'B' -> 2
// ...
// 'Z' -> 26
// Given an encoded message containing digits, determine the total number of ways to decode it.
// For example,
// Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
// The number of ways decoding "12" is 2.
public class DecodeWays {
public int numDecodings(String s) {
int n = s.length();
if(n == 0) {
return 0;
}
int[] dp = new int[n + 1];
dp[n] = 1;
dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0;
for(int i = n - 2; i >= 0; i--) {
if(s.charAt(i) == '0') {
continue;
} else {
dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1];
}
}
return dp[0];
}
}
================================================
FILE: company/facebook/EncodeAndDecodeTinyURL.java
================================================
//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
//and it returns a short URL such as http://tinyurl.com/4e9iAk.
//
//Design the encode and decode methods for the TinyURL service. There is no restriction on how your
//encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL
//and the tiny URL can be decoded to the original URL.
public class EncodeAndDecodeTinyURL {
HashMap map = new HashMap();
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 1;
public String getKey() {
String key = "";
while(count > 0) {
count--;
key += characters.charAt(count);
count /= characters.length();
}
return key;
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
map.put(key, longUrl);
count++;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
================================================
FILE: company/facebook/ExclusiveTimeOfFunctions.java
================================================
//Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions.
//Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.
//A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0.
//Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id.
//Example 1:
//Input:
//n = 2
//logs =
//["0:start:0",
//"1:start:2",
//"1:end:5",
//"0:end:6"]
//Output:[3, 4]
//Explanation:
//Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1.
//Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5.
//Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time.
//So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.
//Note:
//Input logs will be sorted by timestamp, NOT log id.
//Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0.
//Two functions won't start or end at the same time.
//Functions could be called recursively, and will always end.
//1 <= n <= 100
class ExclusiveTimeOfFunctions {
public int[] exclusiveTime(int n, List logs) {
Stack stack = new Stack ();
int[] result = new int[n];
String[] current = logs.get(0).split(":");
stack.push(Integer.parseInt(current[0]));
int i = 1;
int previous = Integer.parseInt(current[2]);
while (i < logs.size()) {
current = logs.get(i).split(":");
if (current[1].equals("start")) {
if (!stack.isEmpty()) {
result[stack.peek()] += Integer.parseInt(current[2]) - previous;
}
stack.push(Integer.parseInt(current[0]));
previous = Integer.parseInt(current[2]);
} else {
result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1;
stack.pop();
previous = Integer.parseInt(current[2]) + 1;
}
i++;
}
return result;
}
}
================================================
FILE: company/facebook/ExpressionAddOperators.java
================================================
// Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
// Examples:
// "123", 6 -> ["1+2+3", "1*2*3"]
// "232", 8 -> ["2*3+2", "2+3*2"]
// "105", 5 -> ["1*0+5","10-5"]
// "00", 0 -> ["0+0", "0-0", "0*0"]
// "3456237490", 9191 -> []
public class ExpressionAddOperators {
public List addOperators(String num, int target) {
List result = new ArrayList();
if(num == null || num.length() == 0) {
return result;
}
helper(result, "", num, target, 0, 0, 0);
return result;
}
public void helper(List result, String path, String num, int target, int pos, long eval, long multed) {
if(pos == num.length()) {
if(eval == target) {
result.add(path);
}
return;
}
for(int i = pos; i < num.length(); i++) {
if(i != pos && num.charAt(pos) == '0') {
break;
}
long cur = Long.parseLong(num.substring(pos, i + 1));
if(pos == 0) {
helper(result, path + cur, num, target, i + 1, cur, cur);
} else {
helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur);
helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur);
helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur);
}
}
}
}
================================================
FILE: company/facebook/FindTheCelebrity.java
================================================
// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
// Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
// You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.
// Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.
/* The knows API is defined in the parent class Relation.
boolean knows(int a, int b); */
public class FindTheCelebrity extends Relation {
public int findCelebrity(int n) {
//initialize candidate to 0
int candidate = 0;
//find viable candidate
for(int i = 1; i < n; i++) {
if(knows(candidate, i)) {
candidate = i;
}
}
//check that everyone else knows the candidate
for(int i = 0; i < n; i++) {
//if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity)
if(i != candidate && knows(candidate, i) || !knows(i, candidate)) {
return -1;
}
}
//return the celebrity
return candidate;
}
}
================================================
FILE: company/facebook/FirstBadVersion.java
================================================
// You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
// Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
// You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class FirstBadVersion extends VersionControl {
public int firstBadVersion(int n) {
int start = 1;
int end = n;
while(start < end) {
int mid = start + (end - start) / 2;
if(!isBadVersion(mid)) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
}
================================================
FILE: company/facebook/FlattenNestedListIterator.java
================================================
// Given a nested list of integers, implement an iterator to flatten it.
// Each element is either an integer, or a list -- whose elements may also be integers or other lists.
// Example 1:
// Given the list [[1,1],2,[1,1]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
// Example 2:
// Given the list [1,[4,[6]]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List getList();
* }
*/
public class FlattenNestedListIterator implements Iterator {
Stack stack = new Stack();
public NestedIterator(List nestedList) {
for(int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!stack.isEmpty()) {
NestedInteger current = stack.peek();
if(current.isInteger()) {
return true;
}
stack.pop();
for(int i = current.getList().size() - 1; i >= 0; i--) {
stack.push(current.getList().get(i));
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
================================================
FILE: company/facebook/GroupAnagrams.java
================================================
// Given an array of strings, group anagrams together.
// For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Return:
// [
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
// ]
// Note: All inputs will be in lower-case.
public class GroupAnagrams {
public List> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0) {
return new ArrayList>();
}
HashMap> map = new HashMap>();
Arrays.sort(strs);
for(String s : strs) {
char[] characters = s.toCharArray();
Arrays.sort(characters);
String key = String.valueOf(characters);
if(!map.containsKey(key)) {
map.put(key, new ArrayList());
}
map.get(key).add(s);
}
return new ArrayList>(map.values());
}
}
================================================
FILE: company/facebook/HammingDistance.java
================================================
// The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
// Given two integers x and y, calculate the Hamming distance.
// Note:
// 0 ≤ x, y < 2^31.
// Example:
// Input: x = 1, y = 4
// Output: 2
// Explanation:
// 1 (0 0 0 1)
// 4 (0 1 0 0)
// ↑ ↑
// The above arrows point to positions where the corresponding bits are different.
public class HammingDistance {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
================================================
FILE: company/facebook/ImplementTrie.java
================================================
// Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap();
this.character = character;
this.last = false;
}
}
public class ImplementTrie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
================================================
FILE: company/facebook/InorderSuccessorInBST.java
================================================
// Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
// Note: If the given node has no in-order successor in the tree, return null.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class InorderSuccessorInBST {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode successor = null;
while(root != null) {
if(p.val < root.val) {
successor = root;
root = root.left;
} else {
root = root.right;
}
}
return successor;
}
}
================================================
FILE: company/facebook/InsertDeleteGetRandomO1.java
================================================
//Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap map;
ArrayList values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap();
values = new ArrayList();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
================================================
FILE: company/facebook/InsertInterval.java
================================================
// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
// You may assume that the intervals were initially sorted according to their start times.
// Example 1:
// Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
// Example 2:
// Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
// This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class InsertInterval {
public List insert(List intervals, Interval newInterval) {
int i = 0;
while(i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}
while(i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end));
intervals.remove(i);
}
intervals.add(i, newInterval);
return intervals;
}
}
================================================
FILE: company/facebook/IntegerToEnglishWords.java
================================================
// Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
// For example,
// 123 -> "One Hundred Twenty Three"
// 12345 -> "Twelve Thousand Three Hundred Forty Five"
// 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
public class IntegerToEnglishWords {
private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
private final String[] TENS = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
private final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" };
public String numberToWords(int num) {
if(num == 0) {
return "Zero";
}
int i = 0;
String words = "";
while(num > 0) {
if(num % 1000 != 0) {
words = helper(num % 1000) + THOUSANDS[i] + " " + words;
}
num /= 1000;
i++;
}
return words.trim();
}
private String helper(int num) {
if(num == 0) {
return "";
} else if(num < 20) {
return LESS_THAN_20[num] + " ";
} else if(num < 100) {
return TENS[num / 10] + " " + helper(num % 10);
} else {
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
}
}
}
================================================
FILE: company/facebook/KthLargestElementInAnArray.java
================================================
// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
// For example,
// Given [3,2,1,5,6,4] and k = 2, return 5.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ array's length.
public class KthLargestElementInAnArray {
public int findKthLargest(int[] nums, int k) {
int length = nums.length;
Arrays.sort(nums);
return nums[length - k];
}
}
================================================
FILE: company/facebook/LetterCombinationsOfAPhoneNumber.java
================================================
// Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// 2 - abc
// 3 - def
// 4 - ghi
// 5 - jkl
// 6 - mno
// 7 - pqrs
// 8 - tuv
// 9 - wxyz
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class LetterCombinationsOfAPhoneNumber {
public List letterCombinations(String digits) {
List result = new ArrayList();
if(digits == null || digits.length() == 0) {
return result;
}
String[] mapping = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
letterCombinationsRecursive(result, digits, "", 0, mapping);
return result;
}
public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) {
if(index == digits.length()) {
result.add(current);
return;
}
String letters = mapping[digits.charAt(index) - '0'];
for(int i = 0; i < letters.length(); i++) {
letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
}
}
}
================================================
FILE: company/facebook/LongestConsecutiveSequence.java
================================================
// Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
// For example,
// Given [100, 4, 200, 1, 3, 2],
// The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
// Your algorithm should run in O(n) complexity.
class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Set set = new HashSet();
for(int n: nums) {
set.add(n);
}
int maxLength = 0;
for(int n: set) {
if(!set.contains(n - 1)) {
int current = n;
int currentMax = 1;
while(set.contains(n + 1)) {
currentMax++;
n++;
}
maxLength = Math.max(maxLength, currentMax);
}
}
return maxLength;
}
}
================================================
FILE: company/facebook/LowestCommonAncestorOfABinaryTree.java
================================================
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
// _______3______
// / \
// ___5__ ___1__
// / \ / \
// 6 _2 0 8
// / \
// 7 4
// For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class LowestCommonAncestorsOfABinaryTree {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) {
return root;
}
return left == null ? right : left;
}
}
================================================
FILE: company/facebook/MaximumSizeSubarraySumEqualsK.java
================================================
// Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
// Note:
// The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
// Example 1:
// Given nums = [1, -1, 5, -2, 3], k = 3,
// return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
// Example 2:
// Given nums = [-2, -1, 2, 1], k = 1,
// return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
// Follow Up:
// Can you do it in O(n) time?
public class MaximumSizeSubarraySumEqualsK {
public int maxSubArrayLen(int[] nums, int k) {
if(nums.length == 0) {
return 0;
}
HashMap map = new HashMap();
int maxLength = 0;
int total = 0;
map.put(0, -1);
for(int i = 0; i < nums.length; i++) {
total += nums[i];
if(map.containsKey(total - k)) {
maxLength = Math.max(maxLength, i - map.get(total - k));
}
if(!map.containsKey(total)) {
map.put(total, i);
}
}
return maxLength;
}
}
================================================
FILE: company/facebook/MeetingRooms.java
================================================
// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
// For example,
// Given [[0, 30],[5, 10],[15, 20]],
// return false.
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class MeetingRooms {
public boolean canAttendMeetings(Interval[] intervals) {
if(intervals == null) {
return false;
}
// Sort the intervals by start time
Arrays.sort(intervals, new Comparator() {
public int compare(Interval a, Interval b) { return a.start - b.start; }
});
for(int i = 1; i < intervals.length; i++) {
if(intervals[i].start < intervals[i - 1].end) {
return false;
}
}
return true;
}
}
================================================
FILE: company/facebook/MergeIntervals.java
================================================
// Given a collection of intervals, merge all overlapping intervals.
// For example,
// Given [1,3],[2,6],[8,10],[15,18],
// return [1,6],[8,10],[15,18].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class MergeIntervals {
public List merge(List intervals) {
List result = new ArrayList();
if(intervals == null || intervals.size() == 0) {
return result;
}
Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]);
Arrays.sort(allIntervals, new Comparator() {
public int compare(Interval a, Interval b) {
if(a.start == b.start) {
return a.end - b.end;
}
return a.start - b.start;
}
});
for(Interval i: allIntervals) {
if (result.size() == 0 || result.get(result.size() - 1).end < i.start) {
result.add(i);
} else {
result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end);
}
}
return result;
}
}
================================================
FILE: company/facebook/MergeKSortedLists.java
================================================
// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) {
return null;
}
PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val= 0 && j >= 0) {
A[k--] = A[i] > B[j] ? A[i--] : B[j--];
}
while(j >= 0) {
A[k--] = B[j--];
}
}
}
================================================
FILE: company/facebook/MinStack.java
================================================
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
================================================
FILE: company/facebook/MinimumSizeSubarraySum.java
================================================
// Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
// For example, given the array [2,3,1,2,4,3] and s = 7,
// the subarray [4,3] has the minimal length under the problem constraint.
public class MinimumSizeSubarraySum {
public int minSubArrayLen(int s, int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int i = 0;
int j = 0;
int result = Integer.MAX_VALUE;
int total = 0;
while(i < nums.length) {
total += nums[i++];
while(total >= s) {
result = Math.min(result, i - j);
total -= nums[j++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
================================================
FILE: company/facebook/MinimumWindowSubstring.java
================================================
// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
// For example,
// S = "ADOBECODEBANC"
// T = "ABC"
// Minimum window is "BANC".
// Note:
// If there is no such window in S that covers all characters in T, return the empty string "".
// If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
public class MinimumWindowSubstring {
public String minWindow(String s, String t) {
HashMap map = new HashMap<>();
for(char c : s.toCharArray()) {
map.put(c, 0);
}
for(char c : t.toCharArray()) {
if(map.containsKey(c)) {
map.put(c, map.get(c)+ 1);
} else {
return "";
}
}
int start = 0;
int end = 0;
int minStart = 0;
int minLength = Integer.MAX_VALUE;
int counter = t.length();
while(end < s.length()) {
char c1 = s.charAt(end);
if(map.get(c1) > 0) {
counter--;
}
map.put(c1, map.get(c1) - 1);
end++;
while(counter == 0) {
if(minLength > end - start) {
minLength = end - start;
minStart = start;
}
char c2 = s.charAt(start);
map.put(c2, map.get(c2) + 1);
if(map.get(c2) > 0) {
counter++;
}
start++;
}
}
return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength);
}
}
================================================
FILE: company/facebook/MoveZeros.java
================================================
// Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
// For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
// Note:
// You must do this in-place without making a copy of the array.
// Minimize the total number of operations.
public class MoveZeros {
public void moveZeroes(int[] nums) {
if(nums == null || nums.length == 0) {
return;
}
int index = 0;
for(int num : nums) {
if(num != 0) {
nums[index] = num;
index++;
}
}
while(index < nums.length) {
nums[index] = 0;
index++;
}
}
}
================================================
FILE: company/facebook/MultiplyStrings.java
================================================
// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
// Note:
// The length of both num1 and num2 is < 110.
// Both num1 and num2 contains only digits 0-9.
// Both num1 and num2 does not contain any leading zero.
// You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class MultiplyStrings {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j;
int p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) {
if(!(sb.length() == 0 && p == 0)) {
sb.append(p);
}
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
================================================
FILE: company/facebook/NumberOfIslands.java
================================================
// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
// Example 1:
// 11110
// 11010
// 11000
// 00000
// Answer: 1
// Example 2:
// 11000
// 11000
// 00100
// 00011
// Answer: 3
public class NumberOfIslands {
char[][] gridCopy;
public int numIslands(char[][] grid) {
//set grid copy to the current grid
gridCopy = grid;
//initialize number of islands to zero
int numberOfIslands = 0;
//iterate through every index of the grid
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
//attempt to "sink" the current index of the grid
numberOfIslands += sink(gridCopy, i, j);
}
}
//return the total number of islands
return numberOfIslands;
}
int sink(char[][] grid, int i, int j) {
//check the bounds of i and j and if the current index is an island or not (1 or 0)
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
return 0;
}
//set current index to 0
grid[i][j] = '0';
// sink all neighbors of current index
sink(grid, i + 1, j);
sink(grid, i - 1, j);
sink(grid, i, j + 1);
sink(grid, i, j - 1);
//increment number of islands
return 1;
}
}
================================================
FILE: company/facebook/OneEditDistance.java
================================================
// Given two strings S and T, determine if they are both one edit distance apart.
public class OneEditDistance {
public boolean isOneEditDistance(String s, String t) {
//iterate through the length of the smaller string
for(int i = 0; i < Math.min(s.length(), t.length()); i++) {
//if the current characters of the two strings are not equal
if(s.charAt(i) != t.charAt(i)) {
//return true if the remainder of the two strings are equal, false otherwise
if(s.length() == t.length()) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else if(s.length() < t.length()) {
//return true if the strings would be the same if you deleted a character from string t
return s.substring(i).equals(t.substring(i + 1));
} else {
//return true if the strings would be the same if you deleted a character from string s
return t.substring(i).equals(s.substring(i + 1));
}
}
}
//if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1
return Math.abs(s.length() - t.length()) == 1;
}
}
================================================
FILE: company/facebook/PaintHouseII.java
================================================
// There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
// The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
// Note:
// All costs are positive integers.
// Follow up:
// Could you solve it in O(nk) runtime?
public class PaintHouseII {
public int minCostII(int[][] costs) {
if(costs == null|| costs.length == 0) {
return 0;
}
int m = costs.length;
int n = costs[0].length;
int min1 = -1;
int min2 = -1;
for(int i = 0; i < m; i++) {
int last1 = min1;
int last2 = min2;
min1 = -1;
min2 = -1;
for(int j = 0; j < n; j++) {
if(j != last1) {
costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1];
} else {
costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2];
}
if(min1 < 0 || costs[i][j] < costs[i][min1]) {
min2 = min1;
min1 = j;
} else if(min2 < 0 || costs[i][j] < costs[i][min2]) {
min2 = j;
}
}
}
return costs[m - 1][min1];
}
}
================================================
FILE: company/facebook/PalindromeLinkedList.java
================================================
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
Stack stack = new Stack();
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
stack.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
if(stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
================================================
FILE: company/facebook/PalindromicSubstrings.java
================================================
//Given a string, your task is to count how many palindromic substrings in this string.
//The substrings with different start indexes or end indexes are counted as different substrings
//even they consist of same characters.
//Example 1:
//Input: "abc"
//Output: 3
//Explanation: Three palindromic strings: "a", "b", "c".
//Example 2:
//Input: "aaa"
//Output: 6
//Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
//Note:
//The input string length won't exceed 1000.
class PalindromicSubstrings {
int result = 0;
public int countSubstrings(String s) {
if(s == null || s.length() == 0) {
return 0;
}
for(int i = 0; i < s.length(); i++) {
extendPalindrome(s, i, i);
extendPalindrome(s, i, i + 1);
}
return result;
}
public void extendPalindrome(String s, int left, int right) {
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
result++;
left--;
right++;
}
}
}
================================================
FILE: company/facebook/PowerOfXToTheN.java
================================================
// Implement pow(x, n).
public class PowerOfXToTheN {
public double myPow(double x, int n) {
if(n == 0) {
return 1;
}
if(Double.isInfinite(x)) {
return 0;
}
if(n < 0) {
n = -n;
x = 1 / x;
}
return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
}
================================================
FILE: company/facebook/ProductOfArrayExceptSelf.java
================================================
// Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// Solve it without division and in O(n).
// For example, given [1,2,3,4], return [24,12,8,6].
// Follow up:
// Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
public class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 1;
for(int i = 0; i < nums.length; i++) {
if(i > 0) {
left *= nums[i - 1];
}
result[i] = left;
}
int right = 1;
for(int i = n - 1; i >= 0; i--) {
if(i < n - 1) {
right *= nums[i + 1];
}
result[i] *= right;
}
return result;
}
}
================================================
FILE: company/facebook/RegularExpressionMatching.java
================================================
// Implement regular expression matching with support for '.' and '*'.
// '.' Matches any single character.
// '*' Matches zero or more of the preceding element.
// The matching should cover the entire input string (not partial).
// The function prototype should be:
// bool isMatch(const char *s, const char *p)
// Some examples:
// isMatch("aa","a") → false
// isMatch("aa","aa") → true
// isMatch("aaa","aa") → false
// isMatch("aa", "a*") → true
// isMatch("aa", ".*") → true
// isMatch("ab", ".*") → true
// isMatch("aab", "c*a*b") → true
public class RegularExpressionMatching {
public boolean isMatch(String s, String p) {
if(s == null || p == null) {
return false;
}
boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
dp[0][0] = true;
for(int i = 0; i < p.length(); i++) {
if(p.charAt(i) == '*' && dp[0][i - 1]) {
dp[0][i + 1] = true;
}
}
for(int i = 0; i < s.length(); i++) {
for(int j = 0; j < p.length(); j++) {
if(p.charAt(j) == '.') {
dp[i + 1][j + 1] = dp[i][j];
}
if(p.charAt(j) == s.charAt(i)) {
dp[i + 1][j + 1] = dp[i][j];
}
if(p.charAt(j) == '*') {
if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') {
dp[i + 1][j + 1] = dp[i + 1][j - 1];
} else {
dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]);
}
}
}
}
return dp[s.length()][p.length()];
}
}
================================================
FILE: company/facebook/RemoveDuplicatesFromSortedArray.java
================================================
// Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
// Do not allocate extra space for another array, you must do this in place with constant memory.
// For example,
// Given input array nums = [1,1,2],
// Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
public class RemoveDuplicatesFromSortedArray {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums == null) {
return 0;
}
if(nums.length < 2) {
return nums.length;
}
int index = 1;
for(int i = 1; i < nums.length; i++) {
if(nums[i] != nums[i - 1]) {
nums[index++] = nums[i];
}
}
return index;
}
}
================================================
FILE: company/facebook/RemoveInvalidParentheses.java
================================================
// Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
// Note: The input string may contain letters other than the parentheses ( and ).
// Examples:
// "()())()" -> ["()()()", "(())()"]
// "(a)())()" -> ["(a)()()", "(a())()"]
// ")(" -> [""]
public class RemoveInvalidParentheses {
public List removeInvalidParentheses(String s) {
List result = new ArrayList<>();
remove(s, result, 0, 0, new char[]{'(', ')'});
return result;
}
public void remove(String s, List result, int last_i, int last_j, char[] par) {
for (int stack = 0, i = last_i; i < s.length(); i++) {
if (s.charAt(i) == par[0]) {
stack++;
}
if (s.charAt(i) == par[1]) {
stack--;
}
if (stack >= 0) {
continue;
}
for (int j = last_j; j <= i; j++) {
if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) {
remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par);
}
}
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (par[0] == '(') {
// finished left to right
remove(reversed, result, 0, 0, new char[]{')', '('});
} else {
// finished right to left
result.add(reversed);
}
}
}
================================================
FILE: company/facebook/ReverseLinkedList.java
================================================
// Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
================================================
FILE: company/facebook/RomanToInteger.java
================================================
// Given a roman numeral, convert it to an integer.
// Input is guaranteed to be within the range from 1 to 3999
public class RomanToInteger {
public int romanToInt(String s) {
HashMap map = new HashMap();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int total = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
total -= map.get(s.charAt(i));
} else {
total += map.get(s.charAt(i));
}
}
total += map.get(s.charAt(s.length() - 1));
return total;
}
}
================================================
FILE: company/facebook/SearchInRotatedSortedArray.java
================================================
// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
// (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
// You are given a target value to search. If found in the array return its index, otherwise return -1.
// You may assume no duplicate exists in the array.
public class SearchInRotatedSortedArray {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) {
return mid;
}
if(nums[left] <= nums[mid]) {
if(target < nums[mid] && target >= nums[left]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if(nums[mid] <= nums[right]) {
if(target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
}
================================================
FILE: company/facebook/SortColors.java
================================================
// Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
// Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
// Note:
// You are not suppose to use the library's sort function for this problem.
public class SortColors {
public void sortColors(int[] nums) {
int wall = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] < 1) {
int temp = nums[i];
nums[i] = nums[wall];
nums[wall] = temp;
wall++;
}
}
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 1) {
int temp = nums[i];
nums[i] = nums[wall];
nums[wall] = temp;
wall++;
}
}
}
}
================================================
FILE: company/facebook/SparseMatrixMultiplication.java
================================================
// Given two sparse matrices A and B, return the result of AB.
// You may assume that A's column number is equal to B's row number.
// Example:
// A = [
// [ 1, 0, 0],
// [-1, 0, 3]
// ]
// B = [
// [ 7, 0, 0 ],
// [ 0, 0, 0 ],
// [ 0, 0, 1 ]
// ]
// | 1 0 0 | | 7 0 0 | | 7 0 0 |
// AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
// | 0 0 1 |
public class SparseMatrixMultiplication {
public int[][] multiply(int[][] A, int[][] B) {
int m = A.length;
int n = A[0].length;
int nB = B[0].length;
int[][] C = new int[m][nB];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(A[i][j] != 0) {
for(int k = 0; k < nB; k++) {
if(B[j][k] != 0) {
C[i][k] += A[i][j] * B[j][k];
}
}
}
}
}
return C;
}
}
================================================
FILE: company/facebook/SquareRootX.java
================================================
// Implement int sqrt(int x).
// Compute and return the square root of x.
public class SquareRootX {
public int mySqrt(int x) {
if(x == 0) {
return 0;
}
int left = 1;
int right = x;
while(left <= right) {
int mid = left + (right - left) / 2;
if(mid == x / mid) {
return mid;
} else if(mid > x / mid) {
right = mid - 1;
} else if(mid < x / mid) {
left = mid + 1;
}
}
return right;
}
}
================================================
FILE: company/facebook/Subsets.java
================================================
// Given a set of distinct integers, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
public class Subsets {
public List> subsets(int[] nums) {
List> result = new ArrayList<>();
recurse(result, nums, new Stack<>(), 0);
return result;
}
private void recurse(List> result, int[] nums, Stack path, int position) {
if(position == nums.length) {
result.add(new ArrayList<>(path));
return;
}
path.push(nums[position]);
recurse(result, nums, path, position + 1);
path.pop();
recurse(result, nums, path, position + 1);
}
}
================================================
FILE: company/facebook/SubsetsII.java
================================================
// Given a collection of integers that might contain duplicates, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,2], a solution is:
// [
// [2],
// [1],
// [1,2,2],
// [2,2],
// [1,2],
// []
// ]
public class SubsetsII {
public List> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List> result = new ArrayList>();
if(nums.length == 0 || nums == null) {
return result;
}
helper(nums, new ArrayList(), 0, result);
return result;
}
public void helper(int[] nums, ArrayList current, int index, List> result) {
result.add(current);
for(int i = index; i < nums.length; i++) {
if(i > index && nums[i] == nums[i - 1]) {
continue;
}
ArrayList newCurrent = new ArrayList(current);
newCurrent.add(nums[i]);
helper(nums, newCurrent, i + 1, result);
}
}
}
================================================
FILE: company/facebook/SumOfLeftLeaves.java
================================================
// Find the sum of all left leaves in a given binary tree.
// Example:
// 3
// / \
// 9 20
// / \
// 15 7
// There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class SumOfLeftLeaves {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) {
return 0;
}
int total = 0;
if(root.left != null) {
if(root.left.left == null && root.left.right == null) {
total += root.left.val;
} else {
total += sumOfLeftLeaves(root.left);
}
}
total += sumOfLeftLeaves(root.right);
return total;
}
}
================================================
FILE: company/facebook/TwoSum.java
================================================
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
================================================
FILE: company/facebook/ValidPalindrome.java
================================================
public class ValidPalindrome {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while(left < right) {
while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) {
left++;
}
while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) {
right--;
}
if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}
================================================
FILE: company/facebook/ValidParentheses.java
================================================
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack stack = new Stack();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
================================================
FILE: company/facebook/ValidateBinarySearchTree.java
================================================
// Given a binary tree, determine if it is a valid binary search tree (BST).
// Assume a BST is defined as follows:
// The left subtree of a node contains only nodes with keys less than the node's key.
// The right subtree of a node contains only nodes with keys greater than the node's key.
// Both the left and right subtrees must also be binary search trees.
// Example 1:
// 2
// / \
// 1 3
// Binary tree [2,1,3], return true.
// Example 2:
// 1
// / \
// 2 3
// Binary tree [1,2,3], return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ValidateBinarySearchTree {
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) {
if(root == null) {
return true;
} else if(root.val >= maxValue || root.val <= minValue) {
return false;
} else {
return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue);
}
}
}
================================================
FILE: company/facebook/WallsAndGates.java
================================================
// You are given a m x n 2D grid initialized with these three possible values.
// -1 - A wall or an obstacle.
// 0 - A gate.
// INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
// Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
// For example, given the 2D grid:
// INF -1 0 INF
// INF INF INF -1
// INF -1 INF -1
// 0 -1 INF INF
// After running your function, the 2D grid should be:
// 3 -1 0 1
// 2 2 1 -1
// 1 -1 2 -1
// 0 -1 3 4
public class WallsAndGates {
public void wallsAndGates(int[][] rooms) {
//iterate through the matrix calling dfs on all indices that contain a zero
for(int i = 0; i < rooms.length; i++) {
for(int j = 0; j < rooms[0].length; j++) {
if(rooms[i][j] == 0) {
dfs(rooms, i, j, 0);
}
}
}
}
void dfs(int[][] rooms, int i, int j, int distance) {
//if you have gone out of the bounds of the array or you have run into a wall/obstacle, return
// room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance
if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) {
return;
}
//set current index's distance to distance
rooms[i][j] = distance;
//recurse on all adjacent neighbors of rooms[i][j]
dfs(rooms, i + 1, j, distance + 1);
dfs(rooms, i - 1, j, distance + 1);
dfs(rooms, i, j + 1, distance + 1);
dfs(rooms, i, j - 1, distance + 1);
}
}
================================================
FILE: company/facebook/WordBreak.java
================================================
// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
// For example, given
// s = "leetcode",
// dict = ["leet", "code"].
// Return true because "leetcode" can be segmented as "leet code".
public class WordBreak {
public boolean wordBreak(String s, Set wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
================================================
FILE: company/facebook/WordSearch.java
================================================
// Given a 2D board and a word, find if the word exists in the grid.
// The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
// For example,
// Given board =
// [
// ['A','B','C','E'],
// ['S','F','C','S'],
// ['A','D','E','E']
// ]
// word = "ABCCED", -> returns true,
// word = "SEE", -> returns true,
// word = "ABCB", -> returns false.
public class WordSearch {
public boolean exist(char[][] board, String word) {
char[] w = word.toCharArray();
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(search(board, i, j, w, 0)) {
return true;
}
}
}
return false;
}
public boolean search(char[][] board, int i, int j, char[] w, int index) {
if(index == w.length) {
return true;
}
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
}
if(board[i][j] != w[index]) {
return false;
}
board[i][j] ^= 256;
boolean exist = search(board, i + 1, j, w, index + 1) ||
search(board, i - 1, j, w, index + 1) ||
search(board, i, j + 1, w, index + 1) ||
search(board, i, j - 1, w, index + 1);
board[i][j] ^= 256;
return exist;
}
}
================================================
FILE: company/google/3SumSmaller.java
================================================
// Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
// For example, given nums = [-2, 0, 1, 3], and target = 2.
// Return 2. Because there are two triplets which sums are less than 2:
// [-2, 0, 1]
// [-2, 0, 3]
// Follow up:
// Could you solve it in O(n2) runtime?
public class 3SumSmaller {
public int threeSumSmaller(int[] nums, int target) {
//initialize total count to zero
int count = 0;
//sort the array
Arrays.sort(nums);
//loop through entire array
for(int i = 0; i < nums.length - 2; i++) {
//set left to i + 1
int left = i + 1;
//set right to end of array
int right = nums.length - 1;
//while left index < right index
while(left < right) {
//if the 3 indices add to less than the target increment count
if(nums[i] + nums[left] + nums[right] < target) {
//increment the count by the distance between left and right because the array is sorted
count += right - left;
//increment left pointer
left++;
} else {
//if they sum to a value greater than target...
//decrement right pointer
right--;
}
}
}
return count;
}
}
================================================
FILE: company/google/AndroidUnlockPatterns.java
================================================
// Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
// Rules for a valid pattern:
// Each pattern must connect at least m keys and at most n keys.
// All the keys must be distinct.
// If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
// The order of keys used matters.
// Explanation:
// | 1 | 2 | 3 |
// | 4 | 5 | 6 |
// | 7 | 8 | 9 |
// Invalid move: 4 - 1 - 3 - 6
// Line 1 - 3 passes through key 2 which had not been selected in the pattern.
// Invalid move: 4 - 1 - 9 - 2
// Line 1 - 9 passes through key 5 which had not been selected in the pattern.
// Valid move: 2 - 4 - 1 - 3 - 6
// Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
// Valid move: 6 - 5 - 4 - 1 - 9 - 2
// Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
// Example:
// Given m = 1, n = 1, return 9.
public class AndroidUnlockPatterns {
public int numberOfPatterns(int m, int n) {
//initialize a 10x10 matrix
int skip[][] = new int[10][10];
//initialize indices of skip matrix (all other indices in matrix are 0 by default)
skip[1][3] = skip[3][1] = 2;
skip[1][7] = skip[7][1] = 4;
skip[3][9] = skip[9][3] = 6;
skip[7][9] = skip[9][7] = 8;
skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip [7][3] = skip[6][4] = skip[4][6] = 5;
//initialize visited array
boolean visited[] = new boolean[10];
//initialize total number to 0
int totalNumber = 0;
//run DFS for each length from m to n
for(int i = m; i <= n; ++i) {
totalNumber += DFS(visited, skip, 1, i - 1) * 4; //1, 3, 7, and 9 are symmetric so multiply this result by 4
totalNumber += DFS(visited, skip, 2, i - 1) * 4; //2, 4, 6, and 8 are symmetric so multiply this result by 4
totalNumber += DFS(visited, skip, 5, i - 1); //do not multiply by 4 because 5 is unique
}
return totalNumber;
}
int DFS(boolean visited[], int[][] skip, int current, int remaining) {
//base cases
if(remaining < 0) {
return 0;
}
if(remaining == 0) {
return 1;
}
//mark the current node as visited
visited[current] = true;
//initialize total number to 0
int totalNumber = 0;
for(int i = 1; i <= 9; ++i) {
//if the current node has not been visited and (two numbers are adjacent or skip number has already been visited)
if(!visited[i] && (skip[current][i] == 0 || visited[skip[current][i]])) {
totalNumber += DFS(visited, skip, i, remaining - 1);
}
}
//mark the current node as not visited
visited[current] = false;
//return total number
return totalNumber;
}
}
================================================
FILE: company/google/BinarySearchTreeIterator.java
================================================
// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
// Calling next() will return the next smallest number in the BST.
// Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinarySearchTreeIterator {
Stack stack;
public BSTIterator(TreeNode root) {
stack = new Stack();
while(root != null) {
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return stack.isEmpty() ? false : true;
}
/** @return the next smallest number */
public int next() {
TreeNode nextSmallest = stack.pop();
TreeNode addToStack = nextSmallest.right;
while(addToStack != null) {
stack.add(addToStack);
addToStack = addToStack.left;
}
return nextSmallest.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
================================================
FILE: company/google/BinaryTreePaths.java
================================================
// Given a binary tree, return all root-to-leaf paths.
// For example, given the following binary tree:
// 1
// / \
// 2 3
// \
// 5
// All root-to-leaf paths are:
// ["1->2->5", "1->3"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths {
public List binaryTreePaths(TreeNode root) {
List result = new ArrayList();
if(root == null) {
return result;
}
helper(new String(), root, result);
return result;
}
public void helper(String current, TreeNode root, List result) {
if(root.left == null && root.right == null) {
result.add(current + root.val);
}
if(root.left != null) {
helper(current + root.val + "->", root.left, result);
}
if(root.right != null) {
helper(current + root.val + "->", root.right, result);
}
}
}
================================================
FILE: company/google/BinaryTreeVerticalOrderTraversal.java
================================================
// Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
// If two nodes are in the same row and column, the order should be from left to right.
// Examples:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// /\
// / \
// 9 20
// /\
// / \
// 15 7
// return its vertical order traversal as:
// [
// [9],
// [3,15],
// [20],
// [7]
// ]
// Given binary tree [3,9,8,4,0,1,7],
// 3
// /\
// / \
// 9 8
// /\ /\
// / \/ \
// 4 01 7
// return its vertical order traversal as:
// [
// [4],
// [9],
// [3,0,1],
// [8],
// [7]
// ]
// Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
// 3
// /\
// / \
// 9 8
// /\ /\
// / \/ \
// 4 01 7
// /\
// / \
// 5 2
// return its vertical order traversal as:
// [
// [4],
// [9,5],
// [3,0,1],
// [8,2],
// [7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeVerticalOrderTraversal {
public List> verticalOrder(TreeNode root) {
List> result = new ArrayList<>();
if(root == null) {
return result;
}
Map> map = new HashMap<>();
Queue q = new LinkedList<>();
Queue cols = new LinkedList<>();
q.add(root);
cols.add(0);
int min = 0;
int max = 0;
while(!q.isEmpty()) {
TreeNode node = q.poll();
int col = cols.poll();
if(!map.containsKey(col)) {
map.put(col, new ArrayList());
}
map.get(col).add(node.val);
if(node.left != null) {
q.add(node.left);
cols.add(col - 1);
min = Math.min(min, col - 1);
}
if(node.right != null) {
q.add(node.right);
cols.add(col + 1);
max = Math.max(max, col + 1);
}
}
for(int i = min; i <= max; i++) {
result.add(map.get(i));
}
return result;
}
}
================================================
FILE: company/google/BinaryWatch.java
================================================
// A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
// Each LED represents a zero or one, with the least significant bit on the right.
// For example, the above binary watch reads "3:25".
// Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
// Example:
// Input: n = 1
// Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
// Note:
// The order of output does not matter.
// The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
// The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
public class BinaryWatch {
public List readBinaryWatch(int num) {
ArrayList allTimes = new ArrayList();
//iterate through all possible time combinations
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 60; j++) {
//if the current number and n have the same number of bits the time is possible
if(Integer.bitCount(i * 64 + j) == num) {
//add the current time to all times arraylist
allTimes.add(String.format("%d:%02d", i, j));
}
}
}
return allTimes;
}
}
================================================
FILE: company/google/BombEnemy.java
================================================
// Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb.
// The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed.
// Note that you can only put the bomb at an empty cell.
// Example:
// For the given grid
// 0 E 0 0
// E 0 W E
// 0 E 0 0
// return 3. (Placing a bomb at (1,1) kills 3 enemies)
public class BombEnemy {
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int max = 0;
int row = 0;
int[] col = new int[grid[0].length];
for(int i = 0; i max) ? row + col[j] : max;
}
}
}
return max;
}
//calculate killed enemies for row i from column j
private int killedEnemiesRow(char[][] grid, int i, int j) {
int num = 0;
while(j <= grid[0].length-1 && grid[i][j] != 'W') {
if(grid[i][j] == 'E') {
num++;
}
j++;
}
return num;
}
//calculate killed enemies for column j from row i
private int killedEnemiesCol(char[][] grid, int i, int j) {
int num = 0;
while(i <= grid.length -1 && grid[i][j] != 'W'){
if(grid[i][j] == 'E') {
num++;
}
i++;
}
return num;
}
}
================================================
FILE: company/google/BullsAndCows.java
================================================
//You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
//
//Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
//
//Please note that both secret number and friend's guess may contain duplicate digits.
//
//Example 1:
//
//Input: secret = "1807", guess = "7810"
//
//Output: "1A3B"
//
//Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
//Example 2:
//
//Input: secret = "1123", guess = "0111"
//
//Output: "1A1B"
//
//Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
//Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
class BullsAndCows {
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] counts = new int[10];
for(int i = 0; i < secret.length(); i++) {
if(secret.charAt(i) == guess.charAt(i)) {
bulls++;
} else {
if(counts[secret.charAt(i) - '0']++ < 0) {
cows++;
}
if(counts[guess.charAt(i) - '0']-- > 0) {
cows++;
}
}
}
return bulls + "A" + cows + "B";
}
}
================================================
FILE: company/google/CloneGraph.java
================================================
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
// OJ's undirected graph serialization:
// Nodes are labeled uniquely.
// We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
// As an example, consider the serialized graph {0,1,2#1,2#2,2}.
// The graph has a total of three nodes, and therefore contains three parts as separated by #.
// First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
// Second node is labeled as 1. Connect node 1 to node 2.
// Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
// Visually, the graph looks like the following:
// 1
// / \
// / \
// 0 --- 2
// / \
// \_/
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
* };
*/
public class CloneGraph {
public HashMap map = new HashMap();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) {
return null;
}
if(map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(newNode.label, newNode);
for(UndirectedGraphNode neighbor : node.neighbors) {
newNode.neighbors.add(cloneGraph(neighbor));
}
return newNode;
}
}
================================================
FILE: company/google/ClosestBinarySearchTreeValue.java
================================================
// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
// Note:
// Given target value is a floating point.
// You are guaranteed to have only one unique value in the BST that is closest to the target.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ClosestBinarySearchTreeValue {
public int closestValue(TreeNode root, double target) {
int value = root.val;
TreeNode child = root.val < target ? root.right : root.left;
if(child == null) {
return value;
}
int childValue = closestValue(child, target);
return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue;
}
}
================================================
FILE: company/google/CombinationSumIV.java
================================================
// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
// Example:
// nums = [1, 2, 3]
// target = 4
// The possible combination ways are:
// (1, 1, 1, 1)
// (1, 1, 2)
// (1, 2, 1)
// (1, 3)
// (2, 1, 1)
// (2, 2)
// (3, 1)
// Note that different sequences are counted as different combinations.
// Therefore the output is 7.
// Follow up:
// What if negative numbers are allowed in the given array?
// How does it change the problem?
// What limitation we need to add to the question to allow negative numbers?
public class CombinationSumIV {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for(int i = 1; i < dp.length; i++) {
for(int j = 0; j < nums.length; j++) {
if(i - nums[j] >= 0) {
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
}
================================================
FILE: company/google/DailyTemperatures.java
================================================
//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
//
//For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
//
//Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
class DailyTemperatures {
public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[temperatures.length];
Stack stack = new Stack();
for(int i = 0; i < temperatures.length; i++) {
while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int index = stack.pop();
result[index] = i - index;
}
stack.push(i);
}
return result;
}
}
================================================
FILE: company/google/DecodeString.java
================================================
// Given an encoded string, return it's decoded string.
// The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
// You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
// Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
public class DecodeString {
public String decodeString(String s) {
//declare empty string
String decoded = "";
//initialize stack to hold counts
Stack countStack = new Stack();
//initalize stack to hold decoded string
Stack decodedStack = new Stack();
//initialize index to zero
int index = 0;
//iterate through entire string
while(index < s.length()) {
//if the current character is numeric...
if(Character.isDigit(s.charAt(index))) {
int count = 0;
//determine the number
while(Character.isDigit(s.charAt(index))) {
count = 10 * count + (s.charAt(index) - '0');
index++;
}
//push the number onto the count stack
countStack.push(count);
} else if(s.charAt(index) == '[') {
//if the current character is an opening bracket
decodedStack.push(decoded);
decoded = "";
index++;
} else if(s.charAt(index) == ']') {
//if the current character is a closing bracket
StringBuilder temp = new StringBuilder(decodedStack.pop());
int repeatTimes = countStack.pop();
for(int i = 0; i < repeatTimes; i++) {
temp.append(decoded);
}
decoded = temp.toString();
index++;
} else {
//otherwise, append the current character to the decoded string
decoded += s.charAt(index);
index++;
}
}
//return the decoded string
return decoded;
}
}
================================================
FILE: company/google/EncodeAndDecodeTinyURL.java
================================================
//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
//and it returns a short URL such as http://tinyurl.com/4e9iAk.
//
//Design the encode and decode methods for the TinyURL service. There is no restriction on how your
//encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL
//and the tiny URL can be decoded to the original URL.
public class EncodeAndDecodeTinyURL {
HashMap map = new HashMap();
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 1;
public String getKey() {
String key = "";
while(count > 0) {
count--;
key += characters.charAt(count);
count /= characters.length();
}
return key;
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
map.put(key, longUrl);
count++;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
================================================
FILE: company/google/ExpressionAddOperators.java
================================================
// Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
// Examples:
// "123", 6 -> ["1+2+3", "1*2*3"]
// "232", 8 -> ["2*3+2", "2+3*2"]
// "105", 5 -> ["1*0+5","10-5"]
// "00", 0 -> ["0+0", "0-0", "0*0"]
// "3456237490", 9191 -> []
public class ExpressionAddOperator {
public List addOperators(String num, int target) {
List result = new ArrayList();
if(num == null || num.length() == 0) {
return result;
}
helper(result, "", num, target, 0, 0, 0);
return result;
}
public void helper(List result, String path, String num, int target, int pos, long eval, long multed) {
if(pos == num.length()) {
if(eval == target) {
result.add(path);
}
return;
}
for(int i = pos; i < num.length(); i++) {
if(i != pos && num.charAt(pos) == '0') {
break;
}
long cur = Long.parseLong(num.substring(pos, i + 1));
if(pos == 0) {
helper(result, path + cur, num, target, i + 1, cur, cur);
} else {
helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur);
helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur);
helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur);
}
}
}
}
================================================
FILE: company/google/FindAllNumbersDisappearedInAnArray.java
================================================
//Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
//
//Find all the elements of [1, n] inclusive that do not appear in this array.
//
//Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
//
//Example:
//
//Input:
//[4,3,2,7,8,2,3,1]
//
//Output:
//[5,6]
class FindAllNumbersDisappearedInAnArray {
public List findDisappearedNumbers(int[] nums) {
List result = new ArrayList();
HashMap map = new HashMap();
for(int i = 1; i <= nums.length; i++) {
map.put(i, 1);
}
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) {
map.put(nums[i], -1);
}
}
for(int i: map.keySet()) {
if(map.get(i) != -1) {
result.add(i);
}
}
return result;
}
}
================================================
FILE: company/google/FindTheDifference.java
================================================
// Given two strings s and t which consist of only lowercase letters.
// String t is generated by random shuffling string s and then add one more letter at a random position.
// Find the letter that was added in t.
// Example:
// Input:
// s = "abcd"
// t = "abcde"
// Output:
// e
// Explanation:
// 'e' is the letter that was added.
public class FindTheDifference {
public char findTheDifference(String s, String t) {
int charCodeS = 0;
int charCodeT = 0;
for(int i = 0; i < s.length(); i++) {
charCodeS += (int)(s.charAt(i));
}
for(int i = 0; i < t.length(); i++) {
charCodeT += (int)(t.charAt(i));
}
return (char)(charCodeT - charCodeS);
}
}
================================================
FILE: company/google/FirstUniqueCharacterInAString.java
================================================
//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//
//Examples:
//
//s = "leetcode"
//return 0.
//
//s = "loveleetcode",
//return 2.
//Note: You may assume the string contain only lowercase letters.
class FirstUniqueCharacterInAString {
public int firstUniqChar(String s) {
HashMap characters = new HashMap();
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if(characters.containsKey(current)) {
characters.put(current, -1);
} else {
characters.put(current, i);
}
}
int min = Integer.MAX_VALUE;
for(char c: characters.keySet()) {
if(characters.get(c) > -1 && characters.get(c) < min) {
min = characters.get(c);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
================================================
FILE: company/google/FlattenNestedListIterator.java
================================================
// Given a nested list of integers, implement an iterator to flatten it.
// Each element is either an integer, or a list -- whose elements may also be integers or other lists.
// Example 1:
// Given the list [[1,1],2,[1,1]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
// Example 2:
// Given the list [1,[4,[6]]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List getList();
* }
*/
public class FlattenNestedListIterator implements Iterator {
Stack stack = new Stack();
public NestedIterator(List nestedList) {
for(int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!stack.isEmpty()) {
NestedInteger current = stack.peek();
if(current.isInteger()) {
return true;
}
stack.pop();
for(int i = current.getList().size() - 1; i >= 0; i--) {
stack.push(current.getList().get(i));
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
================================================
FILE: company/google/GameOfLife.java
================================================
// According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
// Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
// Any live cell with fewer than two live neighbors dies, as if caused by under-population.
// Any live cell with two or three live neighbors lives on to the next generation.
// Any live cell with more than three live neighbors dies, as if by over-population..
// Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
// Write a function to compute the next state (after one update) of the board given its current state.
// Follow up:
// Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
// In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
public class GameOfLife {
public void gameOfLife(int[][] board) {
if(board == null || board.length == 0) {
return;
}
int m = board.length;
int n = board[0].length;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
int lives = liveNeighbors(board, m, n, i, j);
if(board[i][j] == 1 && lives >= 2 && lives <= 3) {
board[i][j] = 3;
}
if(board[i][j] == 0 && lives == 3) {
board[i][j] = 2;
}
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
board[i][j] >>= 1;
}
}
}
private int liveNeighbors(int[][] board, int m, int n, int i, int j) {
int lives = 0;
for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
lives += board[x][y] & 1;
}
}
lives -= board[i][j] & 1;
return lives;
}
}
================================================
FILE: company/google/GeneralizedAbbreviation.java
================================================
// Write a function to generate the generalized abbreviations of a word.
// Example:
// Given word = "word", return the following list (order does not matter):
// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
public class GeneralizedAbbreviation {
public List generateAbbreviations(String word) {
List result = new ArrayList();
backtrack(result, word, 0, "", 0);
return result;
}
void backtrack(List result, String word, int position, String current, int count) {
if(position == word.length()) {
if(count > 0) {
current += count;
}
result.add(current);
} else {
backtrack(result, word, position + 1, current, count + 1);
backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0);
}
}
}
================================================
FILE: company/google/GenerateParentheses.java
================================================
//Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
//
//For example, given n = 3, a solution set is:
//
//[
//"((()))",
//"(()())",
//"(())()",
//"()(())",
//"()()()"
//]
class GenerateParentheses {
public List generateParenthesis(int n) {
List result = new ArrayList();
generateParenthesisRecursive(result, "", 0, 0, n);
return result;
}
public void generateParenthesisRecursive(List result, String current, int open, int close, int n) {
if(current.length() == n * 2) {
result.add(current);
return;
}
if(open < n) {
generateParenthesisRecursive(result, current + "(", open + 1, close, n);
}
if(close < open) {
generateParenthesisRecursive(result, current + ")", open, close + 1, n);
}
}
}
================================================
FILE: company/google/GroupShiftedStrings.java
================================================
// Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
// "abc" -> "bcd" -> ... -> "xyz"
// Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
// For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
// A solution is:
// [
// ["abc","bcd","xyz"],
// ["az","ba"],
// ["acef"],
// ["a","z"]
// ]
public class GroupShiftedStrings {
public List> groupStrings(String[] strings) {
List> result = new ArrayList>();
HashMap> map = new HashMap>();
for(String s : strings) {
int offset = s.charAt(0) - 'a';
String key = "";
for(int i = 0; i < s.length(); i++) {
char current = (char)(s.charAt(i) - offset);
if(current < 'a') {
current += 26;
}
key += current;
}
if(!map.containsKey(key)) {
List list = new ArrayList();
map.put(key, list);
}
map.get(key).add(s);
}
for(String key : map.keySet()) {
List list = map.get(key);
Collections.sort(list);
result.add(list);
}
return result;
}
}
================================================
FILE: company/google/GuessNumberHigherOrLower.java
================================================
// We are playing the Guess Game. The game is as follows:
// I pick a number from 1 to n. You have to guess which number I picked.
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
// -1 : My number is lower
// 1 : My number is higher
// 0 : Congrats! You got it!
// Example:
// n = 10, I pick 6.
// Return 6.
/* The guess API is defined in the parent class GuessGame.
@param num, your guess
@return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); */
public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
================================================
FILE: company/google/ImplementTrie.java
================================================
// Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap();
this.character = character;
this.last = false;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
================================================
FILE: company/google/InsertDeleteGetRandomO1.java
================================================
//Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap map;
ArrayList values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap();
values = new ArrayList();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
================================================
FILE: company/google/InsertInterval.java
================================================
// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
// You may assume that the intervals were initially sorted according to their start times.
// Example 1:
// Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
// Example 2:
// Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
// This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class InsertInterval {
public List insert(List intervals, Interval newInterval) {
int i = 0;
while(i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}
while(i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end));
intervals.remove(i);
}
intervals.add(i, newInterval);
return intervals;
}
}
================================================
FILE: company/google/IslandPerimeter.java
================================================
// You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
// Example:
// [[0,1,0,0],
// [1,1,1,0],
// [0,1,0,0],
// [1,1,0,0]]
// Answer: 16
class IslandPerimeter {
public int islandPerimeter(int[][] grid) {
int perimeter = 0;
if(grid == null || grid.length == 0) {
return perimeter;
}
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 1) {
perimeter += numNeighbors(grid, i, j);
return perimeter;
}
}
}
return perimeter;
}
public int numNeighbors(int[][] grid, int x, int y) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] == 0) {
return 1;
}
if(grid[x][y] == -1) {
return 0;
}
grid[x][y] = -1;
return numNeighbors(grid, x + 1, y) +
numNeighbors(grid, x - 1, y) +
numNeighbors(grid, x, y + 1) +
numNeighbors(grid, x, y - 1);
}
}
================================================
FILE: company/google/JudgeRouteCircle.java
================================================
//Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
//
//The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
//
//Example 1:
//Input: "UD"
//Output: true
//Example 2:
//Input: "LL"
//Output: false
class JudgeRouteCircle {
public boolean judgeCircle(String moves) {
int UD = 0;
int LR = 0;
for(int i = 0; i < moves.length(); i++) {
if(moves.charAt(i) == 'U') {
UD++;
} else if(moves.charAt(i) == 'D') {
UD--;
} else if(moves.charAt(i) == 'L') {
LR++;
} else if(moves.charAt(i) == 'R') {
LR--;
}
}
return UD == 0 && LR == 0;
}
}
================================================
FILE: company/google/LetterCombinationsOfAPhoneNumber.java
================================================
// Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// 2 - abc
// 3 - def
// 4 - ghi
// 5 - jkl
// 6 - mno
// 7 - pqrs
// 8 - tuv
// 9 - wxyz
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class LetterCombinationsOfAPhoneNumber {
public List letterCombinations(String digits) {
List result = new ArrayList();
if(digits == null || digits.length() == 0) {
return result;
}
String[] mapping = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
letterCombinationsRecursive(result, digits, "", 0, mapping);
return result;
}
public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) {
if(index == digits.length()) {
result.add(current);
return;
}
String letters = mapping[digits.charAt(index) - '0'];
for(int i = 0; i < letters.length(); i++) {
letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
}
}
}
================================================
FILE: company/google/LoggerRateLimiter.java
================================================
// Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.
// Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.
// It is possible that several messages arrive roughly at the same time.
// Example:
// Logger logger = new Logger();
// // logging string "foo" at timestamp 1
// logger.shouldPrintMessage(1, "foo"); returns true;
// // logging string "bar" at timestamp 2
// logger.shouldPrintMessage(2,"bar"); returns true;
// // logging string "foo" at timestamp 3
// logger.shouldPrintMessage(3,"foo"); returns false;
// // logging string "bar" at timestamp 8
// logger.shouldPrintMessage(8,"bar"); returns false;
// // logging string "foo" at timestamp 10
// logger.shouldPrintMessage(10,"foo"); returns false;
// // logging string "foo" at timestamp 11
// logger.shouldPrintMessage(11,"foo"); returns true;
public class LoggerRateLimiter {
HashMap messages;
/** Initialize your data structure here. */
public Logger() {
this.messages = new HashMap();
}
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
public boolean shouldPrintMessage(int timestamp, String message) {
if(messages.containsKey(message)) {
if(timestamp - messages.get(message) >= 10) {
messages.put(message, timestamp);
return true;
} else {
return false;
}
} else {
messages.put(message, timestamp);
return true;
}
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/
================================================
FILE: company/google/LongestConsecutiveSequence.java
================================================
// Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
// For example,
// Given [100, 4, 200, 1, 3, 2],
// The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
// Your algorithm should run in O(n) complexity.
class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Set set = new HashSet();
for(int n: nums) {
set.add(n);
}
int maxLength = 0;
for(int n: set) {
if(!set.contains(n - 1)) {
int current = n;
int currentMax = 1;
while(set.contains(n + 1)) {
currentMax++;
n++;
}
maxLength = Math.max(maxLength, currentMax);
}
}
return maxLength;
}
}
================================================
FILE: company/google/LongestSubstringWithAtMostKDistinctCharacters.java
================================================
// Given a string, find the length of the longest substring T that contains at most k distinct characters.
// For example, Given s = “eceba” and k = 2,
// T is "ece" which its length is 3.
public class LongestSubstringWithAtMostKDistinctCharacters {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[256]; // there are 256 ASCII characters in the world
int i = 0; // i will be behind j
int num = 0;
int res = 0;
for (int j = 0; j < s.length(); j++) {
if (count[s.charAt(j)] == 0) { // if count[s.charAt(j)] == 0, we know that it is a distinct character
num++;
}
count[s.charAt(j)]++;
while (num > k && i < s.length()) { // sliding window
count[s.charAt(i)]--;
if (count[s.charAt(i)] == 0){
num--;
}
i++;
}
res = Math.max(res, j - i + 1);
}
return res;
}
}
================================================
FILE: company/google/MaximumProductOfWordLengths.java
================================================
// Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
// Example 1:
// Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
// Return 16
// The two words can be "abcw", "xtfn".
// Example 2:
// Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
// Return 4
// The two words can be "ab", "cd".
// Example 3:
// Given ["a", "aa", "aaa", "aaaa"]
// Return 0
// No such pair of words.
public class MaximumProductOfWordLengths {
public int maxProduct(String[] words) {
if(words.length == 0 || words == null) {
return 0;
}
int length = words.length;
int[] value = new int[length];
int max = 0;
for(int i = 0; i < length; i++) {
String temp = words[i];
value[i] = 0;
for(int j = 0; j < temp.length(); j++) {
value[i] |= 1 << (temp.charAt(j) - 'a');
}
}
for(int i = 0; i < length; i++) {
for(int j = 1; j < length; j++) {
if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length()) > max) {
max = words[i].length() * words[j].length();
}
}
}
return max;
}
}
================================================
FILE: company/google/MergeIntervals.java
================================================
// Given a collection of intervals, merge all overlapping intervals.
// For example,
// Given [1,3],[2,6],[8,10],[15,18],
// return [1,6],[8,10],[15,18].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class MergeIntervals {
public List merge(List intervals) {
List result = new ArrayList();
if(intervals == null || intervals.size() == 0) {
return result;
}
Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]);
Arrays.sort(allIntervals, new Comparator() {
public int compare(Interval a, Interval b) {
if(a.start == b.start) {
return a.end - b.end;
}
return a.start - b.start;
}
});
for(Interval i: allIntervals) {
if (result.size() == 0 || result.get(result.size() - 1).end < i.start) {
result.add(i);
} else {
result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end);
}
}
return result;
}
}
================================================
FILE: company/google/MinStack.java
================================================
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
================================================
FILE: company/google/MissingRanges.java
================================================
// Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
// For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
public class MissingRanges {
public List findMissingRanges(int[] nums, int lower, int upper) {
ArrayList result = new ArrayList();
for(int i = 0; i <= nums.length; i++) {
long start = i == 0 ? lower : (long)nums[i - 1] + 1;
long end = i == nums.length ? upper : (long)nums[i] - 1;
addMissing(result, start, end);
}
return result;
}
void addMissing(ArrayList result, long start, long end) {
if(start > end) {
return;
} else if(start == end) {
result.add(start + "");
} else {
result.add(start + "->" + end);
}
}
}
================================================
FILE: company/google/MovingAverageFromDataStream.java
================================================
// Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
// For example,
// MovingAverage m = new MovingAverage(3);
// m.next(1) = 1
// m.next(10) = (1 + 10) / 2
// m.next(3) = (1 + 10 + 3) / 3
// m.next(5) = (10 + 3 + 5) / 3
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
public class MovingAverageFromDataStream {
double previousSum = 0.0;
int maxSize;
Queue window;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.maxSize = size;
window = new LinkedList();
}
public double next(int val) {
if(window.size() == maxSize) {
previousSum -= window.remove();
}
window.add(val);
previousSum += val;
return previousSum / window.size();
}
}
================================================
FILE: company/google/NumberOfIslands.java
================================================
// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
// Example 1:
// 11110
// 11010
// 11000
// 00000
// Answer: 1
// Example 2:
// 11000
// 11000
// 00100
// 00011
// Answer: 3
public class NumberOfIslands {
char[][] gridCopy;
public int numIslands(char[][] grid) {
//set grid copy to the current grid
gridCopy = grid;
//initialize number of islands to zero
int numberOfIslands = 0;
//iterate through every index of the grid
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
//attempt to "sink" the current index of the grid
numberOfIslands += sink(gridCopy, i, j);
}
}
//return the total number of islands
return numberOfIslands;
}
int sink(char[][] grid, int i, int j) {
//check the bounds of i and j and if the current index is an island or not (1 or 0)
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
return 0;
}
//set current index to 0
grid[i][j] = '0';
// sink all neighbors of current index
sink(grid, i + 1, j);
sink(grid, i - 1, j);
sink(grid, i, j + 1);
sink(grid, i, j - 1);
//increment number of islands
return 1;
}
}
================================================
FILE: company/google/PacificAtlanticWaterFlow.java
================================================
// Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
// Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
// Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
// Note:
// The order of returned grid coordinates does not matter.
// Both m and n are less than 150.
// Example:
// Given the following 5x5 matrix:
// Pacific ~ ~ ~ ~ ~
// ~ 1 2 2 3 (5) *
// ~ 3 2 3 (4) (4) *
// ~ 2 4 (5) 3 1 *
// ~ (6) (7) 1 4 5 *
// ~ (5) 1 1 2 4 *
// * * * * * Atlantic
// Return:
// [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
public class PacificAtlanticWaterFlow {
public List pacificAtlantic(int[][] matrix) {
List result = new LinkedList<>();
//error checking
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int n = matrix.length;
int m = matrix[0].length;
boolean[][] pacific = new boolean[n][m];
boolean[][] atlantic = new boolean[n][m];
for(int i = 0; i < n; i++) {
dfs(matrix, pacific, Integer.MIN_VALUE, i, 0);
dfs(matrix, atlantic, Integer.MIN_VALUE, i, m - 1);
}
for(int i = 0; i < m; i++) {
dfs(matrix, pacific, Integer.MIN_VALUE, 0, i);
dfs(matrix, atlantic, Integer.MIN_VALUE, n - 1, i);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(pacific[i][j] && atlantic[i][j]) {
result.add(new int[] {i, j});
}
}
}
return result;
}
public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) {
int n = matrix.length;
int m = matrix[0].length;
if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < height) {
return;
}
visited[x][y] = true;
dfs(matrix, visited, matrix[x][y], x + 1, y);
dfs(matrix, visited, matrix[x][y], x - 1, y);
dfs(matrix, visited, matrix[x][y], x, y + 1);
dfs(matrix, visited, matrix[x][y], x, y - 1);
}
}
================================================
FILE: company/google/PaintFence.java
================================================
// There is a fence with n posts, each post can be painted with one of the k colors.
// You have to paint all the posts such that no more than two adjacent fence posts have the same color.
// Return the total number of ways you can paint the fence.
// Note:
// n and k are non-negative integers.
public class PaintFence {
public int numWays(int n, int k) {
if(n <= 0) {
return 0;
}
int sameColorCounts = 0;
int differentColorCounts = k;
for(int i = 2; i <= n; i++) {
int temp = differentColorCounts;
differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1);
sameColorCounts = temp;
}
return sameColorCounts + differentColorCounts;
}
}
================================================
FILE: company/google/PlusOne.java
================================================
//Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
//
//The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
//
//You may assume the integer does not contain any leading zero, except the number 0 itself.
//
//Example 1:
//
//Input: [1,2,3]
//Output: [1,2,4]
//Explanation: The array represents the integer 123.
//Example 2:
//
//Input: [4,3,2,1]
//Output: [4,3,2,2]
//Explanation: The array represents the integer 4321.
class Solution {
public int[] plusOne(int[] digits) {
for(int i = digits.length - 1; i >= 0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
}
================================================
FILE: company/google/PlusOneLinkedList.java
================================================
// Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
// You may assume the integer do not contain any leading zero, except the number 0 itself.
// The digits are stored such that the most significant digit is at the head of the list.
// Example:
// Input:
// 1->2->3
// Output:
// 1->2->4
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PlusOneLinkedList {
public ListNode plusOne(ListNode head) {
if(plusOneRecursive(head) == 0) {
return head;
} else {
ListNode newHead = new ListNode(1);
newHead.next = head;
return newHead;
}
}
private int plusOneRecursive(ListNode head) {
if(head == null) {
return 1;
}
int carry = plusOneRecursive(head.next);
if(carry == 0) {
return 0;
}
int value = head.val + 1;
head.val = value % 10;
return value/10;
}
}
================================================
FILE: company/google/PowerOfTwo.java
================================================
//Given an integer, write a function to determine if it is a power of two.
//
//Example 1:
//
//Input: 1
//Output: true
//Example 2:
//
//Input: 16
//Output: true
//Example 3:
//
//Input: 218
//Output: false
class PowerOfTwo {
public boolean isPowerOfTwo(int n) {
long i = 1;
while(i < n) {
i <<= 1;
}
return i == n;
}
}
================================================
FILE: company/google/PowerOfXToTheN.java
================================================
// Implement pow(x, n).
public class PowerOfXToTheN {
public double myPow(double x, int n) {
if(n == 0) {
return 1;
}
if(Double.isInfinite(x)) {
return 0;
}
if(n < 0) {
n = -n;
x = 1 / x;
}
return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
}
================================================
FILE: company/google/RegularExpressionMatching.javaa
================================================
// Implement regular expression matching with support for '.' and '*'.
// '.' Matches any single character.
// '*' Matches zero or more of the preceding element.
// The matching should cover the entire input string (not partial).
// The function prototype should be:
// bool isMatch(const char *s, const char *p)
// Some examples:
// isMatch("aa","a") → false
// isMatch("aa","aa") → true
// isMatch("aaa","aa") → false
// isMatch("aa", "a*") → true
// isMatch("aa", ".*") → true
// isMatch("ab", ".*") → true
// isMatch("aab", "c*a*b") → true
public class RegularExpressionMatching {
public boolean isMatch(String s, String p) {
if(s == null || p == null) {
return false;
}
boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
dp[0][0] = true;
for(int i = 0; i < p.length(); i++) {
if(p.charAt(i) == '*' && dp[0][i - 1]) {
dp[0][i + 1] = true;
}
}
for(int i = 0; i < s.length(); i++) {
for(int j = 0; j < p.length(); j++) {
if(p.charAt(j) == '.') {
dp[i + 1][j + 1] = dp[i][j];
}
if(p.charAt(j) == s.charAt(i)) {
dp[i + 1][j + 1] = dp[i][j];
}
if(p.charAt(j) == '*') {
if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') {
dp[i + 1][j + 1] = dp[i + 1][j - 1];
} else {
dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]);
}
}
}
}
return dp[s.length()][p.length()];
}
}
================================================
FILE: company/google/ReverseVowelsOfAString.java
================================================
// Write a function that takes a string as input and reverse only the vowels of a string.
// Example 1:
// Given s = "hello", return "holle".
// Example 2:
// Given s = "leetcode", return "leotcede".
// Note:
// The vowels does not include the letter "y".
public class ReverseVowelsOfAString {
public String reverseVowels(String s) {
if(s == null || s.length() == 0) {
return s;
}
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while(start < end) {
while(start < end && !vowels.contains(chars[start] + "")) {
start++;
}
while(start < end && !vowels.contains(chars[end] + "")) {
end--;
}
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
return new String(chars);
}
}
================================================
FILE: company/google/SentenceScreenFitting.java
================================================
// Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
// Note:
// A word cannot be split into two lines.
// The order of words in the sentence must remain unchanged.
// Two consecutive words in a line must be separated by a single space.
// Total words in the sentence won't exceed 100.
// Length of each word is greater than 0 and won't exceed 10.
// 1 ≤ rows, cols ≤ 20,000.
// Example 1:
// Input:
// rows = 2, cols = 8, sentence = ["hello", "world"]
// Output:
// 1
// Explanation:
// hello---
// world---
// The character '-' signifies an empty space on the screen.
// Example 2:
// Input:
// rows = 3, cols = 6, sentence = ["a", "bcd", "e"]
// Output:
// 2
// Explanation:
// a-bcd-
// e-a---
// bcd-e-
// The character '-' signifies an empty space on the screen.
// Example 3:
// Input:
// rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]
// Output:
// 1
// Explanation:
// I-had
// apple
// pie-I
// had--
// The character '-' signifies an empty space on the screen.
public class SentenceScreenFitting {
public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int start = 0;
int l = s.length();
for(int i = 0; i < rows; i++) {
start += cols;
if(s.charAt(start % l) == ' ') {
start++;
} else {
while(start > 0 && s.charAt((start - 1) % l) != ' ') {
start--;
}
}
}
return start / s.length();
}
}
================================================
FILE: company/google/ShortestDistanceFromAllBuildings.java
================================================
// You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
// Each 0 marks an empty land which you can pass by freely.
// Each 1 marks a building which you cannot pass through.
// Each 2 marks an obstacle which you cannot pass through.
// For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
// 1 - 0 - 2 - 0 - 1
// | | | | |
// 0 - 0 - 0 - 0 - 0
// | | | | |
// 0 - 0 - 1 - 0 - 0
// The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
// Note:
// There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
public class ShortestDistanceFromAllBuildings {
public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return -1;
}
final int[] shift = {0, 1, 0, -1, 0};
int rows = grid.length;
int columns = grid[0].length;
int[][] distance = new int[rows][columns];
int[][] reach = new int[rows][columns];
int numberOfBuildings = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(grid[i][j] == 1) {
numberOfBuildings++;
Queue