Full Code of kdn251/interviews for AI

master 03fdcb2703ce cached
526 files
696.0 KB
196.9k tokens
1317 symbols
1 requests
Download .txt
Showing preview only (810K chars total). Download the full file or copy to clipboard to get everything.
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>interviews</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
	</buildSpec>
	<natures>
	</natures>
</projectDescription>


================================================
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))`

<img src="/images/BST.png?raw=true" alt="Binary Search Tree" width="400" height="500">

### Trie
* 字典树,又称基数树或者前缀树,能够用于存储键为字符串的动态集合或者关联数组的搜索树。树中的节点并没有直接存储关联键值,而是该节点在树中的挂载位置决定了其关联键值。某个节点的所有子节点都拥有相同的前缀,整棵树的根节点则是空字符串。

![Alt text](/images/trie.png?raw=true "Trie")

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

![Alt text](/images/fenwickTree.png?raw=true "Fenwick Tree")

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

![Alt text](/images/segmentTree.png?raw=true "Segment Tree")

### Heap
* 堆是一种特殊的基于树的满足某些特性的数据结构,整个堆中的所有父子节点的键值都会满足相同的排序条件。堆更准确地可以分为最大堆与最小堆,在最大堆中,父节点的键值永远大于或者等于子节点的值,并且整个堆中的最大值存储于根节点;而最小堆中,父节点的键值永远小于或者等于其子节点的键值,并且整个堆中的最小值存储于根节点。
* 时间复杂度:
  * 访问最大值 / 最小值: `O(1)`
  * 插入: `O(log(n))`
  * 移除最大值 / 最小值: `O(log(n))`

<img src="/images/heap.png?raw=true" alt="Max Heap" width="400" height="500">


### Hashing
* 哈希能够将任意长度的数据映射到固定长度的数据。哈希函数返回的即是哈希值,如果两个不同的键得到相同的哈希值,即将这种现象称为碰撞。
* **Hash Map**: Hash Map 是一种能够建立起键与值之间关系的数据结构,Hash Map 能够使用哈希函数将键转化为桶或者槽中的下标,从而优化对于目标值的搜索速度。
* 碰撞解决
  * **链地址法(Separate Chaining)**: 链地址法中,每个桶是相互独立的,包含了一系列索引的列表。搜索操作的时间复杂度即是搜索桶的时间(固定时间)与遍历列表的时间之和。
  * **开地址法(Open Addressing)**: 在开地址法中,当插入新值时,会判断该值对应的哈希桶是否存在,如果存在则根据某种算法依次选择下一个可能的位置,直到找到一个尚未被占用的地址。所谓开地址法也是指某个元素的位置并不永远由其哈希值决定。

![Alt text](/images/hash.png?raw=true "Hashing")

### Graph
* 图是一种数据元素间为多对多关系的数据结构,加上一组基本操作构成的抽象数据类型。
    * **无向图(Undirected Graph)**: 无向图具有对称的邻接矩阵,因此如果存在某条从节点 u 到节点 v 的边,反之从 v 到 u 的边也存在。
    * **有向图(Directed Graph)**: 有向图的邻接矩阵是非对称的,即如果存在从 u 到 v 的边并不意味着一定存在从 v 到 u 的边。

<img src="/images/graph.png?raw=true" alt="Graph" width="400" height="500">

## 算法

### 排序

#### 快速排序
* 稳定: 否
* 时间复杂度:
  * 最优时间: `O(nlog(n))`
  * 最坏时间: `O(n^2)`
  * 平均时间: `O(nlog(n))`

![Alt text](/images/quicksort.gif?raw=true "Quicksort")

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

![Alt text](/images/mergesort.gif?raw=true "Mergesort")

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


![Alt text](/images/bucketsort.png?raw=true "Bucket Sort")

#### 基数排序
* 基数排序类似于桶排序,将数组分割到有限数目的桶中;不过其在分割之后并没有让每个桶单独地进行排序,而是直接进行了合并操作。
* 时间复杂度:
  * 最优时间: `Ω(nk)`
  * 最坏时间: `O(nk)`
  * 平均时间: `Θ(nk)`

### 图算法

#### 深度优先搜索
* 深度优先算法是一种优先遍历子节点而不是回溯的算法。
* 时间复杂度: `O(|V| + |E|)`

![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal")

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

![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal")

#### 拓扑排序
* 拓扑排序是对于有向图节点的线性排序,如果存在某条从 u 到 v 的边,则认为 u 的下标先于 v。
* 时间复杂度: `O(|V| + |E|)`

#### Dijkstra 算法
* **Dijkstra 算法** 用于计算有向图中单源最短路径问题。
* 时间复杂度: `O(|V|^2)`

![Alt text](/images/dijkstra.gif?raw=true "Dijkstra's")

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

![Alt text](/images/bellman-ford.gif?raw=true "Bellman-Ford")

#### Floyd-Warshall 算法
* **Floyd-Warshall 算法** 能够用于在无环带权图中寻找任意节点的最短路径。
* 时间复杂度:
  * 最优时间: `O(|V|^3)`
  * 最坏时间: `O(|V|^3)`
  * 平均时间: `O(|V|^3)`

#### Prim 算法
* **Prim 算法**是用于在带权无向图中计算最小生成树的贪婪算法。换言之,Prim 算法能够在图中抽取出连接所有节点的边的最小代价子集。
* 时间复杂度: `O(|V|^2)`

![Alt text](/images/prim.gif?raw=true "Prim's Algorithm")

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

![Alt text](/images/kruskal.gif?raw=true "Kruskal's Algorithm")

## 位运算
* 位运算即是在位级别进行操作的技术,合适的位运算能够帮助我们得到更快地运算速度与更小的内存使用。
* 测试第 k 位: `s & (1 << k)`
* 设置第 k 位: `s |= (1 << k)`
* 第 k 位置零: `s &= ~(1 << k)`
* 切换第 k 位值: `s ^= ~(1 << k)`
* 乘以 2<sup>n</sup>: `s << n`
* 除以 2<sup>n</sup>: `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 表示** 用于表示某个算法的上限,往往用于描述最坏的情况。

![Alt text](/images/bigO.png?raw=true "Theta Notation")

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

#### 大 Ω 表示
* **大 Ω 表示**用于描述某个算法的渐进下界。

![Alt text](/images/bigOmega.png?raw=true "Theta Notation")

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

#### Theta Θ 表示
* **Theta Notation**用于描述某个确定算法的确界。

![Alt text](/images/theta.png?raw=true "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).
<a href="" style="display:block;"><img src="/images/the-daily-byte.png?raw=true"></a>
>
> 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))`

<img src="/images/BST.png?raw=true" alt="Binary Search Tree" width="400" height="500">

### 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.

![Alt text](/images/trie.png?raw=true "Trie")

### 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))`

![Alt text](/images/fenwickTree.png?raw=true "Fenwick Tree")

### 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))`

![Alt text](/images/segmentTree.png?raw=true "Segment Tree")

### 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))`

<img src="/images/heap.png?raw=true" alt="Max Heap" width="400" height="500">


### 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


![Alt text](/images/hash.png?raw=true "Hashing")

### 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)


<img src="/images/graph.png?raw=true" alt="Graph" width="400" height="500">

## Algorithms

### Sorting

#### Quicksort
* Stable: `No`
* Time Complexity:
  * Best Case: `O(nlog(n))`
  * Worst Case: `O(n^2)`
  * Average Case: `O(nlog(n))`

![Alt text](/images/quicksort.gif?raw=true "Quicksort")

#### 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))`

![Alt text](/images/mergesort.gif?raw=true "Mergesort")

#### 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)`

![Alt text](/images/bucketsort.png?raw=true "Bucket Sort")

#### 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|)`

![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal")

#### 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|)`

![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal")

#### 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)`

![Alt text](/images/dijkstra.gif?raw=true "Dijkstra's")

#### 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|)`

![Alt text](/images/bellman-ford.gif?raw=true "Bellman-Ford")

#### 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)`

![Alt text](/images/prim.gif?raw=true "Prim's Algorithm")

#### 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|)`

![Alt text](/images/kruskal.gif?raw=true "Kruskal's Algorithm")

## 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 2<sup>n</sup>: `s << n;`
* Divide by 2<sup>n</sup>: `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

![Alt text](/images/bigO.png?raw=true "Theta Notation")

#### 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

![Alt text](/images/bigOmega.png?raw=true "Theta Notation")

#### 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

![Alt text](/images/theta.png?raw=true "Theta Notation")

## 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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/Airbnb" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/Amazon" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/Facebook" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/Google" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/LinkedIn" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/Twitter" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/Uber" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>

================================================
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<Integer, Integer> map = new HashMap<Integer, Integer>();
        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<Integer, Integer> map = new HashMap<Integer, Integer>();
        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<Integer, Integer> map = new HashMap<Integer, Integer>();
        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<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val) {
                    return -1;
                } else if (o1.val==o2.val) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        
        ListNode dummy = new ListNode(0);
        ListNode tail=dummy;
        
        for (ListNode node:lists) {
            if (node!=null) {
                queue.add(node);
            }
        }

        while (!queue.isEmpty()) {
            tail.next=queue.poll();
            tail=tail.next;

            if (tail.next!=null) {
                queue.add(tail.next);
            }

        }
        return dummy.next;

    }
}


================================================
FILE: company/airbnb/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/airbnb/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<Integer, Integer> 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<Character> stack = new Stack<Character>();
        
        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<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>>  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<Integer> temp = new ArrayList<Integer>();
                    
                    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<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();

        if(root == null) {
            return result;
        }
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        queue.add(root);
        
        List<Integer> tempList = new ArrayList<Integer>();
        tempList.add(root.val);
        result.add(tempList);
        
        while(!queue.isEmpty()) {
            Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
            
            List<Integer> list = new ArrayList<Integer>();
            
            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<String, String> map = new HashMap<String, String>();
    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<Character, Integer> characters = new HashMap<Character, Integer>();
        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<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0) {
            return new ArrayList<List<String>>();
        }
        
        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        
        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<String>());
            }
            
            map.get(key).add(s);
        }
        
        return new ArrayList<List<String>>(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<Integer, Integer> map;
    ArrayList<Integer> values;

    /** Initialize your data structure here. */
    public RandomizedSet() {
        map = new HashMap<Integer, Integer>();
        values = new ArrayList<Integer>();
    }
    
    /** 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<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        
        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<String> 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<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val) {
                    return -1;
                } else if (o1.val==o2.val) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        
        ListNode dummy = new ListNode(0);
        ListNode tail=dummy;
        
        for (ListNode node:lists) {
            if (node!=null) {
                queue.add(node);
            }
        }

        while (!queue.isEmpty()){
            tail.next=queue.poll();
            tail=tail.next;

            if (tail.next!=null) {
                queue.add(tail.next);
            }
        }

        return dummy.next;
    }
}


================================================
FILE: company/amazon/MinCostClimbingStairs.java
================================================
//On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
//
//Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
//
//Example 1:
//Input: cost = [10, 15, 20]
//Output: 15
//Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
//Example 2:
//Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
//Output: 6
//Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
//Note:
//cost will have a length in the range [2, 1000].
//Every cost[i] will be an integer in the range [0, 999].

class MinCostClimbingStairs {
    public int minCostClimbingStairs(int[] cost) {
        if(cost == null || cost.length == 0) {
            return 0;
        }
        if(cost.length == 1) {
            return cost[0];
        }
        if(cost.length == 2) {
            return Math.min(cost[0], cost[1]);
        }
        
        int[] dp = new int[cost.length];
        dp[0] = cost[0];
        dp[1] = cost[1];
        for(int i = 2; i < cost.length; i++) {
            dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]);
        }
        
        return Math.min(dp[cost.length - 1], dp[cost.length -2]);
    }
}


================================================
FILE: company/amazon/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/amazon/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/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<Integer> stack = new Stack<Integer>();
        
        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<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        
        recurse(result, nums, new Stack<>(), 0);
        
        return result;
    }
    
    
    private void recurse(List<List<Integer>> 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<Integer, Integer> 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<Character> stack = new Stack<Character>();
        
        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<String> 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<Character> rows = new HashSet<Character>();
            HashSet<Character> columns = new HashSet<Character>();
            HashSet<Character> box = new HashSet<Character>();
            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<Character, Integer> characters = new HashMap<Character, Integer>();
        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<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>>  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<Integer> temp = new ArrayList<Integer>();
                    
                    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<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        
        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<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if(root == null) {
            return result;
        }
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        queue.add(root);
        
        List<Integer> tempList = new ArrayList<Integer>();
        tempList.add(root.val);
        result.add(tempList);
        
        while(!queue.isEmpty()) {
            Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
            
            List<Integer> list = new ArrayList<Integer>();
            
            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<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        
        if(root == null) {
            return result;
        }
        
        helper(new String(), root, result);
        
        return result;
    }
    
    public void helper(String current, TreeNode root, List<String> 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<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();

        if(root == null) {
            return result;
        }
        
        Map<Integer, ArrayList<Integer>> map = new HashMap<>();
        Queue<TreeNode> q = new LinkedList<>();
        Queue<Integer> 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<Integer>());
            }
            
            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<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class CloneGraph {
    public HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
    
    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<String, String> map = new HashMap<String, String>();
    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<String> logs) {
        Stack<Integer> stack = new Stack <Integer>();
        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<String> addOperators(String num, int target) {
        List<String> result = new ArrayList<String>();

        if(num == null || num.length() == 0) {
            return result;
        }

        helper(result, "", num, target, 0, 0, 0);

        return result;
    }
    
    public void helper(List<String> 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<NestedInteger> getList();
 * }
 */
public class FlattenNestedListIterator implements Iterator<Integer> {
    Stack<NestedInteger> stack = new Stack<NestedInteger>();

    public NestedIterator(List<NestedInteger> 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<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0) {
            return new ArrayList<List<String>>();
        }
        
        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        
        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<String>());
            }
            
            map.get(key).add(s);
        }
        
        return new ArrayList<List<String>>(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<Character, TrieNode> map;
    char character;
    boolean last;
    
    // Initialize your data structure here.
    public TrieNode(char character) {
        this.map = new HashMap<Character, TrieNode>();
        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<Integer, Integer> map;
    ArrayList<Integer> values;

    /** Initialize your data structure here. */
    public RandomizedSet() {
        map = new HashMap<Integer, Integer>();
        values = new ArrayList<Integer>();
    }
    
    /** 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<Interval> insert(List<Interval> 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<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        
        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<String> 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<Integer> set = new HashSet<Integer>();
        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<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        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<Interval>() {
            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<Interval> merge(List<Interval> intervals) {
        List<Interval> result = new ArrayList<Interval>();
        if(intervals == null || intervals.size() == 0) {
            return result;
        }
        
        Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]);
        Arrays.sort(allIntervals, new Comparator<Interval>() {
           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<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val) {
                    return -1;
                } else if (o1.val==o2.val) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        
        ListNode dummy = new ListNode(0);
        ListNode tail=dummy;
        
        for (ListNode node:lists) {
            if (node!=null) {
                queue.add(node);
            }
        }

        while (!queue.isEmpty()){
            tail.next=queue.poll();
            tail=tail.next;

            if (tail.next!=null) {
                queue.add(tail.next);
            }
        }

        return dummy.next;
    }
}


================================================
FILE: company/facebook/MergeSortedArray.java
================================================
// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

// Note:
// You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

public class MergeSortedArray {
    public void merge(int[] A, int m, int[] B, int n) {
        int i = m - 1;
        int j = n - 1;
        int k = m + n - 1;
        
        while(i >= 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<Character, Integer> 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<Integer> stack = new Stack<Integer>();
        
        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<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<>();

        remove(s, result, 0, 0, new char[]{'(', ')'});

        return result;
    }

    public void remove(String s, List<String> 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<Character, Integer> map = new HashMap<Character, Integer>();
        
        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<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        
        recurse(result, nums, new Stack<>(), 0);
        
        return result;
    }
    
    
    private void recurse(List<List<Integer>> 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<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if(nums.length == 0 || nums == null) {
            return result;
        }
        
        helper(nums, new ArrayList<Integer>(), 0, result);
        
        return result;
    }
    
    
    public void helper(int[] nums, ArrayList<Integer> current, int index, List<List<Integer>> result) {
        result.add(current);
        
        for(int i = index; i < nums.length; i++) {
            if(i > index && nums[i] == nums[i - 1]) {
                continue;
            }
            
            ArrayList<Integer> newCurrent = new ArrayList<Integer>(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<Integer, Integer> 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<Character> stack = new Stack<Character>();
        
        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<String> 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<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        
        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<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        
        if(root == null) {
            return result;
        }
        
        helper(new String(), root, result);
        
        return result;
    }
    
    public void helper(String current, TreeNode root, List<String> 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<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        
        if(root == null) {
            return result;
        }
        
        Map<Integer, ArrayList<Integer>> map = new HashMap<>();
        Queue<TreeNode> q = new LinkedList<>();
        Queue<Integer> 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<Integer>());
            }
            
            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<String> readBinaryWatch(int num) {
        ArrayList<String> allTimes = new ArrayList<String>();
        
        //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<grid.length; i++) {
            for(int j = 0; j<grid[0].length;j++) {
                if(grid[i][j] == 'W') {
                    continue;
                }

                if(j == 0 || grid[i][j-1] == 'W') {
                     row = killedEnemiesRow(grid, i, j);
                }

                if(i == 0 || grid[i-1][j] == 'W') {
                     col[j] = killedEnemiesCol(grid,i,j);
                }

                if(grid[i][j] == '0') {
                    max = (row + col[j] > 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
Download .txt
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
Download .txt
SYMBOL INDEX (1317 symbols across 515 files)

FILE: company/adobe/AddDigits.java
  class AddDigits (line 9) | class AddDigits {
    method addDigits (line 10) | public int addDigits(int num) {

FILE: company/adobe/MajorityElement.java
  class MajorityElement (line 4) | class MajorityElement {
    method majorityElement (line 5) | public int majorityElement(int[] nums) {

FILE: company/airbnb/AddTwoNumbers.java
  class AddTwoNumbers (line 16) | public class AddTwoNumbers {
    method addTwoNumbers (line 17) | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

FILE: company/airbnb/ContainsDuplicate.java
  class ContainsDuplicate (line 4) | class ContainsDuplicate {
    method containsDuplicate (line 5) | public boolean containsDuplicate(int[] nums) {

FILE: company/airbnb/ContainsDuplicatesII.java
  class ContainsDuplicatesII (line 4) | class ContainsDuplicatesII {
    method containsNearbyDuplicate (line 5) | public boolean containsNearbyDuplicate(int[] nums, int k) {

FILE: company/airbnb/ConvertSortedArrayToBinarySearchTree.java
  class Solution (line 12) | public class Solution {
    method sortedArrayToBST (line 13) | public TreeNode sortedArrayToBST(int[] nums) {
    method helper (line 23) | private TreeNode helper(int[] nums, int start, int end) {

FILE: company/airbnb/HouseRobber.java
  class HouseRobber (line 5) | public class HouseRobber {
    method rob (line 6) | public int rob(int[] nums) {

FILE: company/airbnb/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/airbnb/RegularExpressionMatching.java
  class RegularExpressionMatching (line 20) | public class RegularExpressionMatching {
    method isMatch (line 21) | public boolean isMatch(String s, String p) {

FILE: company/airbnb/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: company/airbnb/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: company/amazon/3Sum.java
  class Sum (line 13) | public class 3Sum {
    method threeSum (line 14) | public List<List<Integer>> threeSum(int[] nums) {

FILE: company/amazon/AddTwoNumbers.java
  class AddTwoNumbers (line 16) | public class AddTwoNumbers {
    method addTwoNumbers (line 17) | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

FILE: company/amazon/BestTimeToBuyAndSellStock.java
  class BestTimeToBuyAndSellStock (line 16) | public class BestTimeToBuyAndSellStock {
    method maxProfit (line 17) | public int maxProfit(int[] prices) {

FILE: company/amazon/BinaryTreeLevelOrderTraversal.java
  class BinaryTreeLevelOrderTraversal (line 26) | public class BinaryTreeLevelOrderTraversal {
    method levelOrder (line 27) | public List<List<Integer>> levelOrder(TreeNode root) {

FILE: company/amazon/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: company/amazon/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: company/amazon/GroupAnagrams.java
  class GroupAnagrams (line 13) | public class GroupAnagrams {
    method groupAnagrams (line 14) | public List<List<String>> groupAnagrams(String[] strs) {

FILE: company/amazon/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/amazon/KthLargestElementInAnArray.java
  class KthLargestElementInAnArray (line 9) | public class KthLargestElementInAnArray {
    method findKthLargest (line 10) | public int findKthLargest(int[] nums, int k) {

FILE: company/amazon/LetterCombinationsOfAPhoneNumber.java
  class LetterCombinationsOfAPhoneNumber (line 17) | class LetterCombinationsOfAPhoneNumber {
    method letterCombinations (line 18) | public List<String> letterCombinations(String digits) {
    method letterCombinationsRecursive (line 43) | public void letterCombinationsRecursive(List<String> result, String di...

FILE: company/amazon/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: company/amazon/LongestPalindromicSubstring.java
  class LongestPalindromicSubstring (line 13) | class LongestPalindromicSubstring {
    method longestPalindrome (line 14) | public String longestPalindrome(String s) {
    method isPalindrome (line 31) | public boolean isPalindrome(String s) {

FILE: company/amazon/LowestCommonAncestorOfABinaryTree.java
  class LowestCommonAncestorOfABinaryTree (line 23) | public class LowestCommonAncestorOfABinaryTree {
    method lowestCommonAncestor (line 24) | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNo...

FILE: company/amazon/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/amazon/MinCostClimbingStairs.java
  class MinCostClimbingStairs (line 17) | class MinCostClimbingStairs {
    method minCostClimbingStairs (line 18) | public int minCostClimbingStairs(int[] cost) {

FILE: company/amazon/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: company/amazon/NumberOfIslands.java
  class NumberOfIslands (line 19) | public class NumberOfIslands {
    method numIslands (line 22) | public int numIslands(char[][] grid) {
    method sink (line 42) | int sink(char[][] grid, int i, int j) {

FILE: company/amazon/PalindromeLinkedList.java
  class PalindromeLinkedList (line 9) | public class PalindromeLinkedList {
    method isPalindrome (line 10) | public boolean isPalindrome(ListNode head) {

FILE: company/amazon/ProductOfArrayExceptSelf.java
  class ProductOfArrayExceptSelf (line 10) | public class ProductOfArrayExceptSelf {
    method productExceptSelf (line 11) | public int[] productExceptSelf(int[] nums) {

FILE: company/amazon/ReverseLinkedList.java
  class ReverseLinkedList (line 11) | public class ReverseLinkedList {
    method reverseList (line 12) | public ListNode reverseList(ListNode head) {

FILE: company/amazon/RotateImage.java
  class RotateImage (line 8) | public class RotateImage {
    method rotate (line 9) | public void rotate(int[][] matrix) {

FILE: company/amazon/Subsets.java
  class Subsets (line 19) | public class Subsets {
    method subsets (line 20) | public List<List<Integer>> subsets(int[] nums) {
    method recurse (line 29) | private void recurse(List<List<Integer>> result, int[] nums, Stack pat...

FILE: company/amazon/TrappingRainWater.java
  class TrappingRainWater (line 6) | public class TrappingRainWater {
    method trap (line 7) | public int trap(int[] height) {

FILE: company/amazon/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: company/amazon/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: company/amazon/ValidateBinarySearchTree.java
  class ValidateBinarySearchTree (line 28) | public class ValidateBinarySearchTree {
    method isValidBST (line 29) | public boolean isValidBST(TreeNode root) {
    method validBSTRecursive (line 37) | public boolean validBSTRecursive(TreeNode root, long minValue, long ma...

FILE: company/amazon/WordBreak.java
  class WordBreak (line 9) | public class WordBreak {
    method wordBreak (line 10) | public boolean wordBreak(String s, Set<String> wordDict) {

FILE: company/apple/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: company/apple/ValidSudoku.java
  class ValidSudoku (line 8) | class ValidSudoku {
    method isValidSudoku (line 9) | public boolean isValidSudoku(char[][] board) {

FILE: company/bloomberg/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: company/bloomberg/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: company/bloomberg/LongestPalindromicSubstring.java
  class LongestPalindromicSubstring (line 13) | class LongestPalindromicSubstring {
    method longestPalindrome (line 14) | public String longestPalindrome(String s) {
    method isPalindrome (line 31) | public boolean isPalindrome(String s) {

FILE: company/bloomberg/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: company/bloomberg/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: company/bloomberg/UniquePaths.java
  class UniquePaths (line 7) | class UniquePaths {
    method uniquePaths (line 8) | public int uniquePaths(int m, int n) {

FILE: company/facebook/3Sum.java
  class Sum (line 13) | public class 3Sum {
    method threeSum (line 14) | public List<List<Integer>> threeSum(int[] nums) {

FILE: company/facebook/AddAndSearchWordDataStructureDesign.java
  class AddAndSearchWordDataStructure (line 20) | public class AddAndSearchWordDataStructure {
    class TrieNode (line 21) | public class TrieNode {
    method addWord (line 28) | public void addWord(String word) {
    method search (line 42) | public boolean search(String word) {
    method match (line 46) | private boolean match(char[] chs, int k, TrieNode node) {

FILE: company/facebook/AddBinary.java
  class AddBinary (line 8) | public class AddBinary {
    method addBinary (line 9) | public String addBinary(String a, String b) {

FILE: company/facebook/BestTimeToBuyAndSellStock.java
  class BestTimeToBuyAndSellStock (line 16) | public class BestTimeToBuyAndSellStock {
    method maxProfit (line 17) | public int maxProfit(int[] prices) {

FILE: company/facebook/BinarySearchTreeIterator.java
  class BinarySearchTreeIterator (line 17) | public class BinarySearchTreeIterator {
    method BSTIterator (line 20) | public BSTIterator(TreeNode root) {
    method hasNext (line 30) | public boolean hasNext() {
    method next (line 35) | public int next() {

FILE: company/facebook/BinaryTreeLevelOrderTraversal.java
  class BinaryTreeLevelOrderTraversal (line 26) | public class BinaryTreeLevelOrderTraversal {
    method levelOrder (line 27) | public List<List<Integer>> levelOrder(TreeNode root) {

FILE: company/facebook/BinaryTreePaths.java
  class BinaryTreePaths (line 23) | public class BinaryTreePaths {
    method binaryTreePaths (line 24) | public List<String> binaryTreePaths(TreeNode root) {
    method helper (line 36) | public void helper(String current, TreeNode root, List<String> result) {

FILE: company/facebook/BinaryTreeVerticalOrderTraversal.java
  class BinaryTreeVerticalOrderTraversal (line 67) | public class BinaryTreeVerticalOrderTraversal {
    method verticalOrder (line 68) | public List<List<Integer>> verticalOrder(TreeNode root) {

FILE: company/facebook/CloneGraph.java
  class CloneGraph (line 31) | public class CloneGraph {
    method cloneGraph (line 34) | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {

FILE: company/facebook/CombinationSumIV.java
  class Solution (line 26) | public class Solution {
    method combinationSum4 (line 28) | public int combinationSum4(int[] nums, int target) {

FILE: company/facebook/CountAndSay.java
  class Solution (line 11) | public class Solution {
    method countAndSay (line 13) | public String countAndSay(int n) {
    method helper (line 27) | public String helper(String s) {

FILE: company/facebook/DecodeWays.java
  class DecodeWays (line 15) | public class DecodeWays {
    method numDecodings (line 16) | public int numDecodings(String s) {

FILE: company/facebook/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: company/facebook/ExclusiveTimeOfFunctions.java
  class ExclusiveTimeOfFunctions (line 30) | class ExclusiveTimeOfFunctions {
    method exclusiveTime (line 31) | public int[] exclusiveTime(int n, List<String> logs) {

FILE: company/facebook/ExpressionAddOperators.java
  class ExpressionAddOperators (line 10) | public class ExpressionAddOperators {
    method addOperators (line 11) | public List<String> addOperators(String num, int target) {
    method helper (line 23) | public void helper(List<String> result, String path, String num, int t...

FILE: company/facebook/FindTheCelebrity.java
  class FindTheCelebrity (line 12) | public class FindTheCelebrity extends Relation {
    method findCelebrity (line 13) | public int findCelebrity(int n) {

FILE: company/facebook/FirstBadVersion.java
  class FirstBadVersion (line 10) | public class FirstBadVersion extends VersionControl {
    method firstBadVersion (line 11) | public int firstBadVersion(int n) {

FILE: company/facebook/FlattenNestedListIterator.java
  class FlattenNestedListIterator (line 32) | public class FlattenNestedListIterator implements Iterator<Integer> {
    method NestedIterator (line 35) | public NestedIterator(List<NestedInteger> nestedList) {
    method next (line 41) | @Override
    method hasNext (line 46) | @Override

FILE: company/facebook/GroupAnagrams.java
  class GroupAnagrams (line 13) | public class GroupAnagrams {
    method groupAnagrams (line 14) | public List<List<String>> groupAnagrams(String[] strs) {

FILE: company/facebook/HammingDistance.java
  class HammingDistance (line 21) | public class HammingDistance {
    method hammingDistance (line 22) | public int hammingDistance(int x, int y) {

FILE: company/facebook/ImplementTrie.java
  class TrieNode (line 11) | class TrieNode {
    method TrieNode (line 17) | public TrieNode(char character) {
  class ImplementTrie (line 24) | public class ImplementTrie {
    method Trie (line 27) | public Trie() {
    method insert (line 32) | public void insert(String word) {
    method search (line 47) | public boolean search(String word) {
    method startsWith (line 67) | public boolean startsWith(String prefix) {

FILE: company/facebook/InorderSuccessorInBST.java
  class InorderSuccessorInBST (line 14) | public class InorderSuccessorInBST {
    method inorderSuccessor (line 15) | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {

FILE: company/facebook/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/facebook/InsertInterval.java
  class InsertInterval (line 22) | public class InsertInterval {
    method insert (line 23) | public List<Interval> insert(List<Interval> intervals, Interval newInt...

FILE: company/facebook/IntegerToEnglishWords.java
  class IntegerToEnglishWords (line 9) | public class IntegerToEnglishWords {
    method numberToWords (line 14) | public String numberToWords(int num) {
    method helper (line 35) | private String helper(int num) {

FILE: company/facebook/KthLargestElementInAnArray.java
  class KthLargestElementInAnArray (line 9) | public class KthLargestElementInAnArray {
    method findKthLargest (line 10) | public int findKthLargest(int[] nums, int k) {

FILE: company/facebook/LetterCombinationsOfAPhoneNumber.java
  class LetterCombinationsOfAPhoneNumber (line 17) | class LetterCombinationsOfAPhoneNumber {
    method letterCombinations (line 18) | public List<String> letterCombinations(String digits) {
    method letterCombinationsRecursive (line 43) | public void letterCombinationsRecursive(List<String> result, String di...

FILE: company/facebook/LongestConsecutiveSequence.java
  class LongestConsecutiveSequence (line 9) | class LongestConsecutiveSequence {
    method longestConsecutive (line 10) | public int longestConsecutive(int[] nums) {

FILE: company/facebook/LowestCommonAncestorOfABinaryTree.java
  class LowestCommonAncestorsOfABinaryTree (line 23) | public class LowestCommonAncestorsOfABinaryTree {
    method lowestCommonAncestor (line 24) | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNo...

FILE: company/facebook/MaximumSizeSubarraySumEqualsK.java
  class MaximumSizeSubarraySumEqualsK (line 17) | public class MaximumSizeSubarraySumEqualsK {
    method maxSubArrayLen (line 18) | public int maxSubArrayLen(int[] nums, int k) {

FILE: company/facebook/MeetingRooms.java
  class MeetingRooms (line 16) | public class MeetingRooms {
    method canAttendMeetings (line 17) | public boolean canAttendMeetings(Interval[] intervals) {

FILE: company/facebook/MergeIntervals.java
  class MergeIntervals (line 16) | class MergeIntervals {
    method merge (line 17) | public List<Interval> merge(List<Interval> intervals) {

FILE: company/facebook/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/facebook/MergeSortedArray.java
  class MergeSortedArray (line 6) | public class MergeSortedArray {
    method merge (line 7) | public void merge(int[] A, int m, int[] B, int n) {

FILE: company/facebook/MinStack.java
  class MinStack (line 9) | class MinStack {
    class Node (line 10) | class Node {
      method Node (line 15) | public Node(int data, int min) {
    method MinStack (line 24) | public MinStack() {
    method push (line 28) | public void push(int x) {
    method pop (line 38) | public void pop() {
    method top (line 42) | public int top() {
    method getMin (line 46) | public int getMin() {

FILE: company/facebook/MinimumSizeSubarraySum.java
  class MinimumSizeSubarraySum (line 6) | public class MinimumSizeSubarraySum {
    method minSubArrayLen (line 7) | public int minSubArrayLen(int s, int[] nums) {

FILE: company/facebook/MinimumWindowSubstring.java
  class MinimumWindowSubstring (line 13) | public class MinimumWindowSubstring {
    method minWindow (line 14) | public String minWindow(String s, String t) {

FILE: company/facebook/MoveZeros.java
  class MoveZeros (line 9) | public class MoveZeros {
    method moveZeroes (line 10) | public void moveZeroes(int[] nums) {

FILE: company/facebook/MultiplyStrings.java
  class MultiplyStrings (line 10) | public class MultiplyStrings {
    method multiply (line 11) | public String multiply(String num1, String num2) {

FILE: company/facebook/NumberOfIslands.java
  class NumberOfIslands (line 19) | public class NumberOfIslands {
    method numIslands (line 22) | public int numIslands(char[][] grid) {
    method sink (line 41) | int sink(char[][] grid, int i, int j) {

FILE: company/facebook/OneEditDistance.java
  class OneEditDistance (line 3) | public class OneEditDistance {
    method isOneEditDistance (line 4) | public boolean isOneEditDistance(String s, String t) {

FILE: company/facebook/PaintHouseII.java
  class PaintHouseII (line 11) | public class PaintHouseII {
    method minCostII (line 12) | public int minCostII(int[][] costs) {

FILE: company/facebook/PalindromeLinkedList.java
  class PalindromeLinkedList (line 9) | public class PalindromeLinkedList {
    method isPalindrome (line 10) | public boolean isPalindrome(ListNode head) {

FILE: company/facebook/PalindromicSubstrings.java
  class PalindromicSubstrings (line 16) | class PalindromicSubstrings {
    method countSubstrings (line 18) | public int countSubstrings(String s) {
    method extendPalindrome (line 31) | public void extendPalindrome(String s, int left, int right) {

FILE: company/facebook/PowerOfXToTheN.java
  class PowerOfXToTheN (line 3) | public class PowerOfXToTheN {
    method myPow (line 4) | public double myPow(double x, int n) {

FILE: company/facebook/ProductOfArrayExceptSelf.java
  class ProductOfArrayExceptSelf (line 10) | public class ProductOfArrayExceptSelf {
    method productExceptSelf (line 11) | public int[] productExceptSelf(int[] nums) {

FILE: company/facebook/RegularExpressionMatching.java
  class RegularExpressionMatching (line 20) | public class RegularExpressionMatching {
    method isMatch (line 21) | public boolean isMatch(String s, String p) {

FILE: company/facebook/RemoveDuplicatesFromSortedArray.java
  class RemoveDuplicatesFromSortedArray (line 10) | public class RemoveDuplicatesFromSortedArray {
    method removeDuplicates (line 11) | public int removeDuplicates(int[] nums) {

FILE: company/facebook/RemoveInvalidParentheses.java
  class RemoveInvalidParentheses (line 10) | public class RemoveInvalidParentheses {
    method removeInvalidParentheses (line 11) | public List<String> removeInvalidParentheses(String s) {
    method remove (line 19) | public void remove(String s, List<String> result, int last_i, int last...

FILE: company/facebook/ReverseLinkedList.java
  class ReverseLinkedList (line 11) | public class ReverseLinkedList {
    method reverseList (line 12) | public ListNode reverseList(ListNode head) {

FILE: company/facebook/RomanToInteger.java
  class RomanToInteger (line 5) | public class RomanToInteger {
    method romanToInt (line 6) | public int romanToInt(String s) {

FILE: company/facebook/SearchInRotatedSortedArray.java
  class SearchInRotatedSortedArray (line 9) | public class SearchInRotatedSortedArray {
    method search (line 10) | public int search(int[] nums, int target) {

FILE: company/facebook/SortColors.java
  class SortColors (line 8) | public class SortColors {
    method sortColors (line 9) | public void sortColors(int[] nums) {

FILE: company/facebook/SparseMatrixMultiplication.java
  class SparseMatrixMultiplication (line 23) | public class SparseMatrixMultiplication {
    method multiply (line 24) | public int[][] multiply(int[][] A, int[][] B) {

FILE: company/facebook/SquareRootX.java
  class SquareRootX (line 5) | public class SquareRootX {
    method mySqrt (line 6) | public int mySqrt(int x) {

FILE: company/facebook/Subsets.java
  class Subsets (line 19) | public class Subsets {
    method subsets (line 20) | public List<List<Integer>> subsets(int[] nums) {
    method recurse (line 29) | private void recurse(List<List<Integer>> result, int[] nums, Stack pat...

FILE: company/facebook/SubsetsII.java
  class SubsetsII (line 17) | public class SubsetsII {
    method subsetsWithDup (line 18) | public List<List<Integer>> subsetsWithDup(int[] nums) {
    method helper (line 33) | public void helper(int[] nums, ArrayList<Integer> current, int index, ...

FILE: company/facebook/SumOfLeftLeaves.java
  class SumOfLeftLeaves (line 22) | public class SumOfLeftLeaves {
    method sumOfLeftLeaves (line 23) | public int sumOfLeftLeaves(TreeNode root) {

FILE: company/facebook/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: company/facebook/ValidPalindrome.java
  class ValidPalindrome (line 1) | public class ValidPalindrome {
    method isPalindrome (line 2) | public boolean isPalindrome(String s) {

FILE: company/facebook/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: company/facebook/ValidateBinarySearchTree.java
  class ValidateBinarySearchTree (line 28) | public class ValidateBinarySearchTree {
    method isValidBST (line 29) | public boolean isValidBST(TreeNode root) {
    method validBSTRecursive (line 37) | public boolean validBSTRecursive(TreeNode root, long minValue, long ma...

FILE: company/facebook/WallsAndGates.java
  class WallsAndGates (line 19) | public class WallsAndGates {
    method wallsAndGates (line 20) | public void wallsAndGates(int[][] rooms) {
    method dfs (line 31) | void dfs(int[][] rooms, int i, int j, int distance) {

FILE: company/facebook/WordBreak.java
  class WordBreak (line 9) | public class WordBreak {
    method wordBreak (line 10) | public boolean wordBreak(String s, Set<String> wordDict) {

FILE: company/facebook/WordSearch.java
  class WordSearch (line 17) | public class WordSearch {
    method exist (line 18) | public boolean exist(char[][] board, String word) {
    method search (line 33) | public boolean search(char[][] board, int i, int j, char[] w, int inde...

FILE: company/google/3SumSmaller.java
  class SumSmaller (line 13) | public class 3SumSmaller {
    method threeSumSmaller (line 14) | public int threeSumSmaller(int[] nums, int target) {

FILE: company/google/AndroidUnlockPatterns.java
  class AndroidUnlockPatterns (line 28) | public class AndroidUnlockPatterns {
    method numberOfPatterns (line 29) | public int numberOfPatterns(int m, int n) {
    method DFS (line 56) | int DFS(boolean visited[], int[][] skip, int current, int remaining) {

FILE: company/google/BinarySearchTreeIterator.java
  class BinarySearchTreeIterator (line 17) | public class BinarySearchTreeIterator {
    method BSTIterator (line 20) | public BSTIterator(TreeNode root) {
    method hasNext (line 30) | public boolean hasNext() {
    method next (line 35) | public int next() {

FILE: company/google/BinaryTreePaths.java
  class BinaryTreePaths (line 23) | public class BinaryTreePaths {
    method binaryTreePaths (line 24) | public List<String> binaryTreePaths(TreeNode root) {
    method helper (line 36) | public void helper(String current, TreeNode root, List<String> result) {

FILE: company/google/BinaryTreeVerticalOrderTraversal.java
  class BinaryTreeVerticalOrderTraversal (line 67) | public class BinaryTreeVerticalOrderTraversal {
    method verticalOrder (line 68) | public List<List<Integer>> verticalOrder(TreeNode root) {

FILE: company/google/BinaryWatch.java
  class BinaryWatch (line 18) | public class BinaryWatch {
    method readBinaryWatch (line 19) | public List<String> readBinaryWatch(int num) {

FILE: company/google/BombEnemy.java
  class BombEnemy (line 14) | public class BombEnemy {
    method maxKilledEnemies (line 15) | public int maxKilledEnemies(char[][] grid) {
    method killedEnemiesRow (line 48) | private int killedEnemiesRow(char[][] grid, int i, int j) {
    method killedEnemiesCol (line 63) | private int killedEnemiesCol(char[][] grid, int i, int j) {

FILE: company/google/BullsAndCows.java
  class BullsAndCows (line 23) | class BullsAndCows {
    method getHint (line 24) | public String getHint(String secret, String guess) {

FILE: company/google/CloneGraph.java
  class CloneGraph (line 31) | public class CloneGraph {
    method cloneGraph (line 34) | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {

FILE: company/google/ClosestBinarySearchTreeValue.java
  class ClosestBinarySearchTreeValue (line 16) | public class ClosestBinarySearchTreeValue {
    method closestValue (line 17) | public int closestValue(TreeNode root, double target) {

FILE: company/google/CombinationSumIV.java
  class CombinationSumIV (line 26) | public class CombinationSumIV {
    method combinationSum4 (line 27) | public int combinationSum4(int[] nums, int target) {

FILE: company/google/DailyTemperatures.java
  class DailyTemperatures (line 7) | class DailyTemperatures {
    method dailyTemperatures (line 8) | public int[] dailyTemperatures(int[] temperatures) {

FILE: company/google/DecodeString.java
  class DecodeString (line 9) | public class DecodeString {
    method decodeString (line 10) | public String decodeString(String s) {

FILE: company/google/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: company/google/ExpressionAddOperators.java
  class ExpressionAddOperator (line 10) | public class ExpressionAddOperator {
    method addOperators (line 11) | public List<String> addOperators(String num, int target) {
    method helper (line 23) | public void helper(List<String> result, String path, String num, int t...

FILE: company/google/FindAllNumbersDisappearedInAnArray.java
  class FindAllNumbersDisappearedInAnArray (line 15) | class FindAllNumbersDisappearedInAnArray {
    method findDisappearedNumbers (line 16) | public List<Integer> findDisappearedNumbers(int[] nums) {

FILE: company/google/FindTheDifference.java
  class FindTheDifference (line 19) | public class FindTheDifference {
    method findTheDifference (line 20) | public char findTheDifference(String s, String t) {

FILE: company/google/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: company/google/FlattenNestedListIterator.java
  class FlattenNestedListIterator (line 32) | public class FlattenNestedListIterator implements Iterator<Integer> {
    method NestedIterator (line 35) | public NestedIterator(List<NestedInteger> nestedList) {
    method next (line 41) | @Override
    method hasNext (line 46) | @Override

FILE: company/google/GameOfLife.java
  class GameOfLife (line 15) | public class GameOfLife {
    method gameOfLife (line 16) | public void gameOfLife(int[][] board) {
    method liveNeighbors (line 45) | private int liveNeighbors(int[][] board, int m, int n, int i, int j) {

FILE: company/google/GeneralizedAbbreviation.java
  class GeneralizedAbbreviation (line 7) | public class GeneralizedAbbreviation {
    method generateAbbreviations (line 8) | public List<String> generateAbbreviations(String word) {
    method backtrack (line 16) | void backtrack(List result, String word, int position, String current,...

FILE: company/google/GenerateParentheses.java
  class GenerateParentheses (line 13) | class GenerateParentheses {
    method generateParenthesis (line 14) | public List<String> generateParenthesis(int n) {
    method generateParenthesisRecursive (line 21) | public void generateParenthesisRecursive(List<String> result, String c...

FILE: company/google/GroupShiftedStrings.java
  class GroupShiftedStrings (line 16) | public class GroupShiftedStrings {
    method groupStrings (line 17) | public List<List<String>> groupStrings(String[] strings) {

FILE: company/google/GuessNumberHigherOrLower.java
  class GuessNumberHigherOrLower (line 22) | public class GuessNumberHigherOrLower extends GuessGame {
    method guessNumber (line 23) | public int guessNumber(int n) {

FILE: company/google/ImplementTrie.java
  class TrieNode (line 11) | class TrieNode {
    method TrieNode (line 17) | public TrieNode(char character) {
  class Trie (line 24) | public class Trie {
    method Trie (line 27) | public Trie() {
    method insert (line 32) | public void insert(String word) {
    method search (line 47) | public boolean search(String word) {
    method startsWith (line 67) | public boolean startsWith(String prefix) {

FILE: company/google/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/google/InsertInterval.java
  class InsertInterval (line 22) | public class InsertInterval {
    method insert (line 23) | public List<Interval> insert(List<Interval> intervals, Interval newInt...

FILE: company/google/IslandPerimeter.java
  class IslandPerimeter (line 12) | class IslandPerimeter {
    method islandPerimeter (line 13) | public int islandPerimeter(int[][] grid) {
    method numNeighbors (line 31) | public int numNeighbors(int[][] grid, int x, int y) {

FILE: company/google/JudgeRouteCircle.java
  class JudgeRouteCircle (line 12) | class JudgeRouteCircle {
    method judgeCircle (line 13) | public boolean judgeCircle(String moves) {

FILE: company/google/LetterCombinationsOfAPhoneNumber.java
  class LetterCombinationsOfAPhoneNumber (line 17) | class LetterCombinationsOfAPhoneNumber {
    method letterCombinations (line 18) | public List<String> letterCombinations(String digits) {
    method letterCombinationsRecursive (line 43) | public void letterCombinationsRecursive(List<String> result, String di...

FILE: company/google/LoggerRateLimiter.java
  class LoggerRateLimiter (line 29) | public class LoggerRateLimiter {
    method Logger (line 33) | public Logger() {
    method shouldPrintMessage (line 40) | public boolean shouldPrintMessage(int timestamp, String message) {

FILE: company/google/LongestConsecutiveSequence.java
  class LongestConsecutiveSequence (line 9) | class LongestConsecutiveSequence {
    method longestConsecutive (line 10) | public int longestConsecutive(int[] nums) {

FILE: company/google/LongestSubstringWithAtMostKDistinctCharacters.java
  class LongestSubstringWithAtMostKDistinctCharacters (line 7) | public class LongestSubstringWithAtMostKDistinctCharacters {
    method lengthOfLongestSubstringKDistinct (line 8) | public int lengthOfLongestSubstringKDistinct(String s, int k) {

FILE: company/google/MaximumProductOfWordLengths.java
  class MaximumProductOfWordLengths (line 18) | public class MaximumProductOfWordLengths {
    method maxProduct (line 19) | public int maxProduct(String[] words) {

FILE: company/google/MergeIntervals.java
  class MergeIntervals (line 16) | class MergeIntervals {
    method merge (line 17) | public List<Interval> merge(List<Interval> intervals) {

FILE: company/google/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: company/google/MissingRanges.java
  class MissingRanges (line 5) | public class MissingRanges {
    method findMissingRanges (line 6) | public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    method addMissing (line 19) | void addMissing(ArrayList<String> result, long start, long end) {

FILE: company/google/MovingAverageFromDataStream.java
  class MovingAverageFromDataStream (line 16) | public class MovingAverageFromDataStream {
    method MovingAverage (line 22) | public MovingAverage(int size) {
    method next (line 27) | public double next(int val) {

FILE: company/google/NumberOfIslands.java
  class NumberOfIslands (line 19) | public class NumberOfIslands {
    method numIslands (line 22) | public int numIslands(char[][] grid) {
    method sink (line 41) | int sink(char[][] grid, int i, int j) {

FILE: company/google/PacificAtlanticWaterFlow.java
  class PacificAtlanticWaterFlow (line 27) | public class PacificAtlanticWaterFlow {
    method pacificAtlantic (line 28) | public List<int[]> pacificAtlantic(int[][] matrix) {
    method dfs (line 64) | public void dfs(int[][] matrix, boolean[][] visited, int height, int x...

FILE: company/google/PaintFence.java
  class PaintFence (line 10) | public class PaintFence {
    method numWays (line 11) | public int numWays(int n, int k) {

FILE: company/google/PlusOne.java
  class Solution (line 18) | class Solution {
    method plusOne (line 19) | public int[] plusOne(int[] digits) {

FILE: company/google/PlusOneLinkedList.java
  class PlusOneLinkedList (line 22) | public class PlusOneLinkedList {
    method plusOne (line 23) | public ListNode plusOne(ListNode head) {
    method plusOneRecursive (line 34) | private int plusOneRecursive(ListNode head) {

FILE: company/google/PowerOfTwo.java
  class PowerOfTwo (line 16) | class PowerOfTwo {
    method isPowerOfTwo (line 17) | public boolean isPowerOfTwo(int n) {

FILE: company/google/PowerOfXToTheN.java
  class PowerOfXToTheN (line 3) | public class PowerOfXToTheN {
    method myPow (line 4) | public double myPow(double x, int n) {

FILE: company/google/ReverseVowelsOfAString.java
  class ReverseVowelsOfAString (line 12) | public class ReverseVowelsOfAString {
    method reverseVowels (line 13) | public String reverseVowels(String s) {

FILE: company/google/SentenceScreenFitting.java
  class SentenceScreenFitting (line 54) | public class SentenceScreenFitting {
    method wordsTyping (line 55) | public int wordsTyping(String[] sentence, int rows, int cols) {

FILE: company/google/ShortestDistanceFromAllBuildings.java
  class ShortestDistanceFromAllBuildings (line 18) | public class ShortestDistanceFromAllBuildings {
    method shortestDistance (line 19) | public int shortestDistance(int[][] grid) {

FILE: company/google/SpiralMatrix.java
  class SpiralMatrix (line 22) | class SpiralMatrix {
    method spiralOrder (line 23) | public List<Integer> spiralOrder(int[][] matrix) {

FILE: company/google/StrobogrammaticNumber.java
  class StrobogrammaticNumber (line 7) | public class StrobogrammaticNumber {
    method isStrobogrammatic (line 8) | public boolean isStrobogrammatic(String num) {

FILE: company/google/SummaryRanges.java
  class SummaryRanges (line 5) | public class SummaryRanges {
    method summaryRanges (line 6) | public List<String> summaryRanges(int[] nums) {

FILE: company/google/TrappingRainWater.java
  class TrappingRainWater (line 6) | public class TrappingRainWater {
    method trap (line 7) | public int trap(int[] height) {

FILE: company/google/UniqueWordAbbreviation.java
  class UniqueWordAbbreviation (line 34) | public class UniqueWordAbbreviation {
    method ValidWordAbbr (line 37) | public ValidWordAbbr(String[] dictionary) {
    method isUnique (line 53) | public boolean isUnique(String word) {
    method getKey (line 57) | public String getKey(String word) {

FILE: company/google/Utf8Validation.java
  class Utf8Validation (line 34) | public class Utf8Validation {
    method validUtf8 (line 35) | public boolean validUtf8(int[] data) {

FILE: company/google/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: company/google/WallsAndGates.java
  class WallsAndGates (line 19) | public class WallsAndGates {
    method wallsAndGates (line 20) | public void wallsAndGates(int[][] rooms) {
    method dfs (line 31) | void dfs(int[][] rooms, int i, int j, int distance) {

FILE: company/google/WiggleSort.java
  class WiggleSort (line 5) | public class WiggleSort {
    method wiggleSort (line 6) | public void wiggleSort(int[] nums) {

FILE: company/google/WordBreak.java
  class WordBreak (line 9) | public class WordBreak {
    method wordBreak (line 10) | public boolean wordBreak(String s, Set<String> wordDict) {

FILE: company/google/WordSquares.java
  class WordSquares (line 18) | public class WordSquares {
    method wordSquares (line 19) | public List<List<String>> wordSquares(String[] words) {
    method helper (line 46) | public void helper(List<List<String>> ret, List<String> cur, int match...

FILE: company/google/ZigZagIterator.java
  class ZigZagIterator (line 17) | public class ZigZagIterator {
    method ZigzagIterator (line 22) | public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
    method next (line 27) | public int next() {
    method hasNext (line 38) | public boolean hasNext() {

FILE: company/linkedin/BinarySearchTreeIterator.java
  class BinarySearchTreeIterator (line 17) | public class BinarySearchTreeIterator {
    method BSTIterator (line 20) | public BSTIterator(TreeNode root) {
    method hasNext (line 30) | public boolean hasNext() {
    method next (line 35) | public int next() {

FILE: company/linkedin/BinaryTreeLevelOrderTraversal.java
  class BinaryTreeLevelOrderTraversal (line 26) | public class BinaryTreeLevelOrderTraversal {
    method levelOrder (line 27) | public List<List<Integer>> levelOrder(TreeNode root) {

FILE: company/linkedin/FindTheCelebrity.java
  class FindTheCelebrity (line 12) | public class FindTheCelebrity extends Relation {
    method findCelebrity (line 13) | public int findCelebrity(int n) {

FILE: company/linkedin/HouseRobber.java
  class HouseRobber (line 5) | public class HouseRobber {
    method rob (line 6) | public int rob(int[] nums) {

FILE: company/linkedin/InsertInterval.java
  class InsertInterval (line 22) | public class InsertInterval {
    method insert (line 23) | public List<Interval> insert(List<Interval> intervals, Interval newInt...

FILE: company/linkedin/LowestCommonAncestorOfABinaryTree.java
  class LowestCommonAncestorOfABinaryTree (line 23) | public class LowestCommonAncestorOfABinaryTree {
    method lowestCommonAncestor (line 24) | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNo...

FILE: company/linkedin/MaximumDepthOfABinaryTree.java
  class MaximumDepthOfABinaryTree (line 14) | public class MaximumDepthOfABinaryTree {
    method maxDepth (line 15) | public int maxDepth(TreeNode root) {

FILE: company/linkedin/MaximumProductSubarray.java
  class MaximumProductSubarray (line 6) | public class MaximumProductSubarray {
    method maxProduct (line 7) | public int maxProduct(int[] nums) {

FILE: company/linkedin/MaximumSubarray.java
  class MaximumSubarray (line 6) | public class MaximumSubarray {
    method maxSubArray (line 7) | public int maxSubArray(int[] nums) {

FILE: company/linkedin/MergeIntervals.java
  class MergeIntervals (line 16) | class MergeIntervals {
    method merge (line 17) | public List<Interval> merge(List<Interval> intervals) {

FILE: company/linkedin/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/linkedin/MinimumWindowSubstring.java
  class MinimumWindowSubstring (line 13) | public class MinimumWindowSubstring {
    method minWindow (line 14) | public String minWindow(String s, String t) {

FILE: company/linkedin/PaintHouse.java
  class PaintHouse (line 12) | class PaintHouse {
    method minCost (line 13) | public int minCost(int[][] costs) {

FILE: company/linkedin/PalindromicSubstrings.java
  class PalindromicSubstrings (line 16) | class PalindromicSubstrings {
    method countSubstrings (line 18) | public int countSubstrings(String s) {
    method extendPalindrome (line 31) | public void extendPalindrome(String s, int left, int right) {

FILE: company/linkedin/Permutations.java
  class Permutations (line 14) | class Permutations {
    method permute (line 15) | public List<List<Integer>> permute(int[] nums) {

FILE: company/linkedin/PowerOfXToTheN.java
  class PowerOfXToTheN (line 3) | public class PowerOfXToTheN {
    method myPow (line 4) | public double myPow(double x, int n) {

FILE: company/linkedin/ProductOfArrayExceptSelf.java
  class ProductOfArrayExceptSelf (line 10) | public class ProductOfArrayExceptSelf {
    method productExceptSelf (line 11) | public int[] productExceptSelf(int[] nums) {

FILE: company/linkedin/SearchInRotatedSortedArray.java
  class SearchInRotatedSortedArray (line 9) | public class SearchInRotatedSortedArray {
    method search (line 10) | public int search(int[] nums, int target) {

FILE: company/linkedin/SparseMatrixMultiplication.java
  class SparseMatrixMultiplication (line 23) | public class SparseMatrixMultiplication {
    method multiply (line 24) | public int[][] multiply(int[][] A, int[][] B) {

FILE: company/linkedin/SymmetricTree.java
  class SymmetricTree (line 26) | public class SymmetricTree {
    method isSymmetric (line 27) | public boolean isSymmetric(TreeNode root) {
    method helper (line 35) | public boolean helper(TreeNode left, TreeNode right) {

FILE: company/linkedin/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: company/microsoft/AddDigits.java
  class AddDigits (line 9) | class AddDigits {
    method addDigits (line 10) | public int addDigits(int num) {

FILE: company/microsoft/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: company/microsoft/HouseRobberII.java
  class HouseRobberII (line 9) | class HouseRobberII {
    method rob (line 10) | public int rob(int[] nums) {

FILE: company/microsoft/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: company/microsoft/LongestIncreasingSubsequence.java
  class LongestIncreasingSubsequence (line 11) | class LongestIncreasingSubsequence {
    method lengthOfLIS (line 12) | public int lengthOfLIS(int[] nums) {

FILE: company/microsoft/LongestPalindromicSubstring.java
  class LongestPalindromicSubstring (line 13) | class LongestPalindromicSubstring {
    method longestPalindrome (line 14) | public String longestPalindrome(String s) {
    method isPalindrome (line 31) | public boolean isPalindrome(String s) {

FILE: company/microsoft/Permutations.java
  class Permutations (line 14) | class Permutations {
    method permute (line 15) | public List<List<Integer>> permute(int[] nums) {

FILE: company/microsoft/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: company/microsoft/SpiralMatrix.java
  class SpiralMatrix (line 22) | class SpiralMatrix {
    method spiralOrder (line 23) | public List<Integer> spiralOrder(int[][] matrix) {

FILE: company/palantir/ContainsDuplicate.java
  class ContainsDuplicate (line 4) | class ContainsDuplicate {
    method containsDuplicate (line 5) | public boolean containsDuplicate(int[] nums) {

FILE: company/palantir/ContainsDuplicatesII.java
  class ContainsDuplicatesII (line 4) | class ContainsDuplicatesII {
    method containsNearbyDuplicate (line 5) | public boolean containsNearbyDuplicate(int[] nums, int k) {

FILE: company/snapchat/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: company/snapchat/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: company/snapchat/ValidSudoku.java
  class ValidSudoku (line 8) | class ValidSudoku {
    method isValidSudoku (line 9) | public boolean isValidSudoku(char[][] board) {

FILE: company/twitter/FlattenNestedListIterator.java
  class FlattenNestedListIterator (line 32) | public class FlattenNestedListIterator implements Iterator<Integer> {
    method NestedIterator (line 35) | public NestedIterator(List<NestedInteger> nestedList) {
    method next (line 41) | @Override
    method hasNext (line 46) | @Override

FILE: company/twitter/ImplementTrie.java
  class TrieNode (line 11) | class TrieNode {
    method TrieNode (line 17) | public TrieNode(char character) {
  class Trie (line 24) | public class Trie {
    method Trie (line 27) | public Trie() {
    method insert (line 32) | public void insert(String word) {
    method search (line 48) | public boolean search(String word) {
    method startsWith (line 68) | public boolean startsWith(String prefix) {

FILE: company/twitter/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/twitter/LowestCommonAncestorOfABinaryTree.java
  class LowestCommonAncestorOfABinaryTree (line 23) | public class LowestCommonAncestorOfABinaryTree {
    method lowestCommonAncestor (line 24) | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNo...

FILE: company/twitter/MergeIntervals.java
  class MergeIntervals (line 16) | class MergeIntervals {
    method merge (line 17) | public List<Interval> merge(List<Interval> intervals) {

FILE: company/twitter/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/twitter/MultiplyStrings.java
  class MultiplyStrings (line 10) | public class MultiplyStrings {
    method multiply (line 11) | public String multiply(String num1, String num2) {

FILE: company/twitter/OneEditDistance.java
  class OneEditDistance (line 3) | public class OneEditDistance {
    method isOneEditDistance (line 4) | public boolean isOneEditDistance(String s, String t) {

FILE: company/twitter/RegularExpressionMatching.java
  class RegularExpressionMatching (line 20) | public class RegularExpressionMatching {
    method isMatch (line 21) | public boolean isMatch(String s, String p) {

FILE: company/twitter/ReverseLinkedList.java
  class ReverseLinkedList (line 11) | public class ReverseLinkedList {
    method reverseList (line 12) | public ListNode reverseList(ListNode head) {

FILE: company/twitter/TrappingRainWater.java
  class TrappingRainWater (line 6) | public class TrappingRainWater {
    method trap (line 7) | public int trap(int[] height) {

FILE: company/twitter/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: company/uber/BestTimeToBuyOrSellStock.java
  class BestTimeToBuyAndSellStock (line 16) | public class BestTimeToBuyAndSellStock {
    method maxProfit (line 17) | public int maxProfit(int[] prices) {

FILE: company/uber/CloneGraph.java
  class CloneGraph (line 31) | public class CloneGraph {
    method cloneGraph (line 34) | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {

FILE: company/uber/DecodeWays.java
  class DecodeWays (line 15) | public class DecodeWays {
    method numDecodings (line 16) | public int numDecodings(String s) {

FILE: company/uber/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: company/uber/ExclusiveTimeOfFunctions.java
  class ExclusiveTimeOfFunctions (line 30) | class ExclusiveTimeOfFunctions {
    method exclusiveTime (line 31) | public int[] exclusiveTime(int n, List<String> logs) {

FILE: company/uber/GenerateParentheses.java
  class GenerateParentheses (line 1) | class GenerateParentheses {
    method generateParenthesis (line 2) | public List<String> generateParenthesis(int n) {
    method generateParenthesisRecursive (line 9) | public void generateParenthesisRecursive(List<String> result, String c...

FILE: company/uber/GroupAnagrams.java
  class GroupAnagrams (line 13) | public class GroupAnagrams {
    method groupAnagrams (line 14) | public List<List<String>> groupAnagrams(String[] strs) {

FILE: company/uber/GroupShiftedStrings.java
  class GroupShiftedStrings (line 16) | public class GroupShiftedStrings {
    method groupStrings (line 17) | public List<List<String>> groupStrings(String[] strings) {

FILE: company/uber/ImplementTrie.java
  class TrieNode (line 11) | class TrieNode {
    method TrieNode (line 17) | public TrieNode(char character) {
  class ImplementTrie (line 24) | public class ImplementTrie {
    method Trie (line 27) | public Trie() {
    method insert (line 32) | public void insert(String word) {
    method search (line 47) | public boolean search(String word) {
    method startsWith (line 67) | public boolean startsWith(String prefix) {

FILE: company/uber/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/uber/LetterCombinationsOfAPhoneNumber.java
  class LetterCombinationsOfAPhoneNumber (line 17) | class LetterCombinationsOfAPhoneNumber {
    method letterCombinations (line 18) | public List<String> letterCombinations(String digits) {
    method letterCombinationsRecursive (line 43) | public void letterCombinationsRecursive(List<String> result, String di...

FILE: company/uber/MaximumDepthOfABinaryTree.java
  class MaximumDepthOfABinaryTree (line 14) | public class MaximumDepthOfABinaryTree {
    method maxDepth (line 15) | public int maxDepth(TreeNode root) {

FILE: company/uber/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: company/uber/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: company/uber/MinimumWindowSubstring.java
  class MinimumWindowSubstring (line 13) | public class MinimumWindowSubstring {
    method minWindow (line 14) | public String minWindow(String s, String t) {

FILE: company/uber/OneEditDistance.java
  class OneEditDistance (line 3) | public class OneEditDistance {
    method isOneEditDistance (line 4) | public boolean isOneEditDistance(String s, String t) {

FILE: company/uber/PalindromePermutation.java
  class PalindromePermutation (line 1) | public class PalindromePermutation {
    method canPermutePalindrome (line 2) | public boolean canPermutePalindrome(String s) {

FILE: company/uber/RegularExpressionMatching.java
  class RegularExpressionMatching (line 20) | public class RegularExpressionMatching {
    method isMatch (line 21) | public boolean isMatch(String s, String p) {

FILE: company/uber/ReverseLinkedList.java
  class ReverseLinkedList (line 11) | public class ReverseLinkedList {
    method reverseList (line 12) | public ListNode reverseList(ListNode head) {

FILE: company/uber/RomanToInteger.java
  class RomanToInteger (line 5) | public class RomanToInteger {
    method romanToInt (line 6) | public int romanToInt(String s) {

FILE: company/uber/SearchInRotatedSortedArray.java
  class SearchInRotatedSortedArray (line 9) | public class SearchInRotatedSortedArray {
    method search (line 10) | public int search(int[] nums, int target) {

FILE: company/uber/SpiralMatrix.java
  class SpiralMatrix (line 22) | class SpiralMatrix {
    method spiralOrder (line 23) | public List<Integer> spiralOrder(int[][] matrix) {

FILE: company/uber/Subsets.java
  class Subsets (line 19) | public class Subsets {
    method subsets (line 20) | public List<List<Integer>> subsets(int[] nums) {
    method recurse (line 29) | private void recurse(List<List<Integer>> result, int[] nums, Stack pat...

FILE: company/uber/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: company/uber/ValidPalindrome.java
  class ValidPalindrome (line 1) | public class ValidPalindrome {
    method isPalindrome (line 2) | public boolean isPalindrome(String s) {

FILE: company/uber/ValidSudoku.java
  class ValidSudoku (line 8) | class ValidSudoku {
    method isValidSudoku (line 9) | public boolean isValidSudoku(char[][] board) {

FILE: company/uber/WordBreak.java
  class WordBreak (line 9) | public class WordBreak {
    method wordBreak (line 10) | public boolean wordBreak(String s, Set<String> wordDict) {

FILE: company/yahoo/ContainsDuplicate.java
  class ContainsDuplicate (line 4) | class ContainsDuplicate {
    method containsDuplicate (line 5) | public boolean containsDuplicate(int[] nums) {

FILE: company/yahoo/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: company/yelp/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: company/yelp/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/BinaryRepresentation.java
  class BinaryRepresentation (line 5) | public class BinaryRepresentation {
    method printBinary (line 6) | public static String printBinary(double num) {

FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/FindMissingInteger.java
  class FindMissingInteger (line 7) | public class FindMissingInteger {
    method findMissing (line 8) | public int findMissing(ArrayList<BigInteger> array) {
    method findMissing (line 13) | public int findMissing(ArrayList<BigInteger> input, int column) {

FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/InsertMIntoN.java
  class InsertMIntoN (line 10) | public class InsertMIntoN {
    method updateBits (line 11) | int updateBits(int n, int m, int i, int j) {

FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/SwapBits.java
  class SwapBits (line 4) | public class SwapBits {
    method swapOddEvenBits (line 5) | public int swapOddEvenBits(int x) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/BinaryTreeIsBalanced.java
  class BinaryTreeIsBalanaced (line 5) | public class BinaryTreeIsBalanaced {
    method getHeight (line 6) | public static int getHeight(TreeNode root) {
    method isBalanced (line 13) | public static boolean isBalanced(TreeNode root) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateBinarySearchTree.java
  class CreateBinarySearchTree (line 4) | public class CreateBinarySearchTree {
    method createMinimalBST (line 5) | TreeNode createMinimalBST(int arr[], int start, int end) {
    method createMinimalBST (line 16) | TreeNode createMinimalBST(int array[]) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateLinkedListForEachLevel.java
  class CreateLinkedListForEachLevel (line 4) | public class CreateLinkedListForEachLevel {
    method createLinkedList (line 5) | ArrayList<LinkedList<TreeNode>> createLinkedList(TreeNode root) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/FindPath.java
  class FindPath (line 3) | public class FindPath {
    type State (line 4) | public enum State {
    method search (line 8) | public static boolean search(Graph g, Node start, Node end) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/IsSubtree.java
  class IsSubtree (line 6) | public class IsSubtree {
    method containsTree (line 7) | boolean containsTree(TreeNode t1, TreeNode t2) {
    method subTree (line 14) | boolean subTree(TreeNode r1, TreeNode r2) {
    method matchTree (line 24) | boolean matchTree(TreeNode r1, TreeNode r2) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/PrintPaths.java
  class PrintPaths (line 5) | public class PrintPaths {
    method findSum (line 6) | void findSum(TreeNode node, int sum, int[] path, int level) {
    method findSum (line 32) | void findSum(TreeNode node, int sum) {
    method print (line 38) | void print(int[] path, int start, int end) {
    method depth (line 45) | int depth(TreeNode node) {

FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/ValidBinarySearchTree.java
  class ValidBinarySearchTree (line 3) | public class ValidBinarySearchTree {
    method checkBST (line 4) | boolean checkBST(TreeNode n) {
    method checkBST (line 8) | boolean checkBST(TreeNode n, Integer min, Integer max) {

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllPermutations.java
  class AllPermutations (line 3) | public class AllPermutations {
    method getPerms (line 4) | public static ArrayList<String> getPerms(String str) {
    method insertCharAt (line 26) | public static String insertCharAt(String word, char c, int i) {

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllSubsets.java
  class AllSubsets (line 3) | public class AllSubsets {
    method getSubsets (line 4) | ArrayList<ArrayList<Integer>> getSubsets(ArrayList<Integer> set, int i...

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/EightQueens.java
  class EightQueens (line 5) | public class EightQueens {
    method placeQueens (line 8) | void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> resu...
    method checkValid (line 26) | boolean checkValid(Integer[] columns, int row1, int column1) {

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/MagicIndex.java
  class MagicIndex (line 4) | public class MagicIndex {
    method magicFast (line 5) | public static int magicFast(int[] array, int start, int end) {
    method magicFast (line 21) | public static int magicFast(int[] array) {

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/RepresentingNCents.java
  class RepresentingNCents (line 4) | public class RepresentingNCents {
    method makeChange (line 5) | int makeChange(int n) {
    method makeChange (line 11) | int makeChange(int amount, int[] denoms, int index, int[][] map) {

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/StackBoxes.java
  class StackBoxes (line 6) | public class StackBoxes {
    method createStackDP (line 7) | public ArrayList<Box> createStackDP(Box[] boxes, Box bottom, HashMap<B...

FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/Staircase.java
  class Staircase (line 4) | public class Staircase {
    method countWaysDP (line 5) | public static int countWaysDP(int n, int[] map) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java
  class RemoveDups (line 3) | public class RemoveDups {
    method deleteDups (line 4) | void deleteDups(LinkedListNode n) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/IsRotation.java
  class IsRotation (line 5) | public class IsRotation {
    method isRotation (line 6) | public boolean isRotation(String s1, String s2) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/IsUniqueChars.java
  class IsUniqueChars (line 3) | public class IsUniqueChars {
    method isUniqueChars (line 4) | public boolean isUniqueChars(String str) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/NthToLast.java
  class NthToLast (line 3) | public class NthToLast {
    method nthToLast (line 4) | LinkedListNode nthToLast(LinkedListNode head, int k) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/Permutation.java
  class Permutation (line 3) | public class Permutation {
    method permutation (line 4) | public boolean permutation(String s, String t) {

FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java
  class ReplaceSpaces (line 6) | public class ReplaceSpaces {
    method replaceSpaces (line 7) | public void replaceSpaces(char[] str, int length) {

FILE: cracking-the-coding-interview/chapter-seven-mathematics-and-probability/Operations.java
  class Operations (line 3) | public class Operations {
    method negate (line 5) | public static int negate(int a) {
    method minus (line 16) | public static int minus(int a, int b) {
    method multiply (line 21) | public static int multiply(int a, int b) {
    method abs (line 36) | public static int abs(int a) {
    method divide (line 45) | public int divide(int a, int b) throws ArithmeticException {

FILE: cracking-the-coding-interview/chapter-seven-mathematics-and-probability/WouldIntersect.java
  class WouldIntersect (line 3) | public class WouldIntersect {
  class Line (line 7) | class Line {
    method Line (line 12) | public Line(double s, double y) {
    method Intersect (line 17) | public boolean Intersect(Line line2) {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/BinaryTreeIsBalanced.java
  class BinaryTreeIsBalanaced (line 5) | public class BinaryTreeIsBalanaced {
    method getHeight (line 6) | public static int getHeight(TreeNode root) {
    method isBalanced (line 13) | public static boolean isBalanced(TreeNode root) {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQUeue.java
  class MyQueue (line 3) | public class MyQueue<T> {
    method MyQueue (line 6) | public MyQueue() {
    method size (line 11) | public int size() {
    method add (line 15) | public void add(T value) {
    method shiftStacks (line 23) | private void shiftStacks() {
    method peek (line 31) | public T peek() {
    method remove (line 36) | public T remove() {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQueue.java
  class MyQueue (line 3) | public class MyQueue<T> {
    method MyQueue (line 6) | public MyQueue() {
    method size (line 11) | public int size() {
    method add (line 15) | public void add(T value) {
    method shiftStacks (line 23) | private void shiftStacks() {
    method peek (line 31) | public T peek() {
    method remove (line 36) | public T remove() {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java
  class QueueUsingTwoStacks (line 3) | public class QueueUsingTwoStacks {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/SetOfStacks.java
  class SetOfStacks (line 10) | public class SetOfStacks {
    method push (line 15) | public void push(int v) {
    method pop (line 27) | public void pop() {
    method getLastStack (line 36) | public Stack getLastStack() {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/SortStack.java
  class SortStack (line 6) | public class SortStack {
    method sort (line 7) | public static Stack<Integer> sort(Stack<Integer> s) {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/StackWithMin.java
  class StackWithMin (line 3) | public class StackWithMin extends Stack<NodeWithMin> {
    method push (line 4) | public void push(int value) {
    method min (line 9) | public int min() {
  class NodeWithMin (line 19) | class NodeWithMin {
    method NodeWithMin (line 22) | public NodeWithMin(int v, int min) {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/ThreeStacks.java
  class ThreeStacks (line 3) | public class ThreeStacks {
    method push (line 8) | void push(int stackNum, int value) throws Exception {
    method pop (line 18) | int pop(int stackNum) throws Exception {
    method peek (line 28) | int peek(int stackNum) {
    method isEmpty (line 36) | boolean isEmpty(int stackNum) {
    method absTopOfStack (line 41) | int absTopOfStack(int stasckNum) {

FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/TowersOfHanoi.java
  class TowersOfHanoi (line 10) | public class TowersOfHanoi {
    method main (line 11) | public static void main(String args[]) {
  class Tower (line 25) | public class Tower {
    method Tower (line 28) | public Tower(int i) {
    method index (line 33) | public int index() {
    method add (line 37) | public void add(int d) {
    method moveTopTo (line 46) | public void moveTopTo(Tower t) {
    method moveDisks (line 52) | public void moveDisks(int n, Tower destination, Tower buffer) {

FILE: cracking-the-coding-interview/chapter-two-linked-lists/DeleteDups.java
  class RemoveDups (line 3) | public class RemoveDups {
    method deleteDups (line 4) | void deleteDups(LinkedListNode n) {

FILE: cracking-the-coding-interview/chapter-two-linked-lists/DeleteNode.java
  class DeleteNode (line 3) | public class DeleteNode {
    method deleteNode (line 4) | public static boolean deleteNode(LinkedListNode n) {

FILE: cracking-the-coding-interview/chapter-two-linked-lists/FindBeginning.java
  class FindBeginning (line 4) | public class FindBeginning {
    method findBeginning (line 5) | LinkedListNode findBeginning(LinkedListNode head) {

FILE: cracking-the-coding-interview/chapter-two-linked-lists/IsPalindrome.java
  class IsPalindrome (line 4) | public class IsPalindrome {
    method isPalindrome (line 5) | boolean isPalindrome(LinkedListNode head) {

FILE: cracking-the-coding-interview/chapter-two-linked-lists/Partition.java
  class Partition (line 4) | public class Partition {
    method partition (line 5) | LinkedListNode partition(LinkedListNode node, int x) {

FILE: leetcode/array/BestTimeToBuyAndSellStock.java
  class BestTimeToBuyAndSellStock (line 16) | public class BestTimeToBuyAndSellStock {
    method maxProfit (line 17) | public int maxProfit(int[] prices) {

FILE: leetcode/array/ContainsDuplicatesII.java
  class ContainsDuplicatesII (line 4) | class ContainsDuplicatesII {
    method containsNearbyDuplicate (line 5) | public boolean containsNearbyDuplicate(int[] nums, int k) {

FILE: leetcode/array/FindAllNumbersDisappearedInAnArray.java
  class FindAllNumbersDisappearedInAnArray (line 15) | class FindAllNumbersDisappearedInAnArray {
    method findDisappearedNumbers (line 16) | public List<Integer> findDisappearedNumbers(int[] nums) {

FILE: leetcode/array/FindTheCelebrity.java
  class FindTheCelebrity (line 12) | public class FindTheCelebrity extends Relation {
    method findCelebrity (line 13) | public int findCelebrity(int n) {

FILE: leetcode/array/GameOfLife.java
  class GameOfLife (line 15) | public class GameOfLife {
    method gameOfLife (line 16) | public void gameOfLife(int[][] board) {
    method liveNeighbors (line 45) | private int liveNeighbors(int[][] board, int m, int n, int i, int j) {

FILE: leetcode/array/IncreasingTripletSubsequence.java
  class IncreasingTripletSequence (line 15) | public class IncreasingTripletSequence {
    method increasingTriplet (line 16) | public boolean increasingTriplet(int[] nums) {

FILE: leetcode/array/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: leetcode/array/InsertInterval.java
  class InsertInterval (line 22) | public class InsertInterval {
    method insert (line 23) | public List<Interval> insert(List<Interval> intervals, Interval newInt...

FILE: leetcode/array/LongestConsecutiveSequence.java
  class LongestConsecutiveSequence (line 9) | class LongestConsecutiveSequence {
    method longestConsecutive (line 10) | public int longestConsecutive(int[] nums) {

FILE: leetcode/array/MajorityElement.java
  class MajorityElement (line 4) | class MajorityElement {
    method majorityElement (line 5) | public int majorityElement(int[] nums) {

FILE: leetcode/array/MaximumProductSubarray.java
  class MaximumProductSubarray (line 6) | public class MaximumProductSubarray {
    method maxProduct (line 7) | public int maxProduct(int[] nums) {

FILE: leetcode/array/MaximumSubarray.java
  class Solution (line 6) | public class Solution {
    method maxSubArray (line 8) | public int maxSubArray(int[] nums) {

FILE: leetcode/array/MergeIntervals.java
  class MergeIntervals (line 16) | class MergeIntervals {
    method merge (line 17) | public List<Interval> merge(List<Interval> intervals) {

FILE: leetcode/array/MinCostClimbingStairs.java
  class MinCostClimbingStairs (line 17) | class MinCostClimbingStairs {
    method minCostClimbingStairs (line 18) | public int minCostClimbingStairs(int[] cost) {

FILE: leetcode/array/MinimumPathSum.java
  class MinimumPathSum (line 10) | class MinimumPathSum {
    method minPathSum (line 11) | public int minPathSum(int[][] grid) {

FILE: leetcode/array/MissingRanges.java
  class MissingRanges (line 5) | public class MissingRanges {
    method findMissingRanges (line 6) | public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    method addMissing (line 17) | void addMissing(ArrayList<String> result, long start, long end) {

FILE: leetcode/array/PlusOne.java
  class Solution (line 18) | class Solution {
    method plusOne (line 19) | public int[] plusOne(int[] digits) {

FILE: leetcode/array/ProductofArrayExceptSelf.java
  class ProductOfArrayExceptSelf (line 10) | public class ProductOfArrayExceptSelf {
    method productExceptSelf (line 11) | public int[] productExceptSelf(int[] nums) {

FILE: leetcode/array/RemoveElement.java
  class RemoveElement (line 9) | class RemoveElement {
    method removeElement (line 10) | public int removeElement(int[] nums, int val) {

FILE: leetcode/array/RotateImage.java
  class RotateImage (line 8) | public class RotateImage {
    method rotate (line 9) | public void rotate(int[][] matrix) {

FILE: leetcode/array/SearchInRotatedSortedArray.java
  class SearchInRotatedSortedArray (line 9) | public class SearchInRotatedSortedArray {
    method search (line 10) | public int search(int[] nums, int target) {

FILE: leetcode/array/SpiralMatrix.java
  class SpiralMatrix (line 22) | class SpiralMatrix {
    method spiralOrder (line 23) | public List<Integer> spiralOrder(int[][] matrix) {

FILE: leetcode/array/SpiralMatrixII.java
  class SpiralMatrix (line 13) | public class SpiralMatrix {
    method generateMatrix (line 14) | public int[][] generateMatrix(int n) {

FILE: leetcode/array/Subsets.java
  class Subsets (line 19) | public class Subsets {
    method subsets (line 20) | public List<List<Integer>> subsets(int[] nums) {
    method recurse (line 28) | private void recurse(List<List<Integer>> result, int[] nums, Stack pat...

FILE: leetcode/array/SubsetsII.java
  class SubsetsII (line 17) | public class SubsetsII {
    method subsetsWithDup (line 18) | public List<List<Integer>> subsetsWithDup(int[] nums) {
    method helper (line 33) | public void helper(int[] nums, ArrayList<Integer> current, int index, ...

FILE: leetcode/array/SummaryRanges.java
  class SummaryRanges (line 5) | public class SummaryRanges {
    method summaryRanges (line 6) | public List<String> summaryRanges(int[] nums) {

FILE: leetcode/array/UniquePaths.java
  class UniquePaths (line 7) | class UniquePaths {
    method uniquePaths (line 8) | public int uniquePaths(int m, int n) {

FILE: leetcode/array/WiggleSort.java
  class WiggleSort (line 5) | public class WiggleSort {
    method wiggleSort (line 6) | public void wiggleSort(int[] nums) {

FILE: leetcode/array/WordSearch.java
  class WordSearch (line 17) | public class WordSearch {
    method exist (line 18) | public boolean exist(char[][] board, String word) {
    method search (line 32) | public boolean search(char[][] board, int i, int j, char[] w, int inde...

FILE: leetcode/backtracking/AndroidUnlockPatterns.java
  class AndroidUnlockPatterns (line 28) | public class AndroidUnlockPatterns {
    method numberOfPatterns (line 29) | public int numberOfPatterns(int m, int n) {
    method DFS (line 56) | int DFS(boolean visited[], int[][] skip, int current, int remaining) {

FILE: leetcode/backtracking/GeneralizedAbbreviation.java
  class GeneralizedAbbreviation (line 7) | public class GeneralizedAbbreviation {
    method generateAbbreviations (line 8) | public List<String> generateAbbreviations(String word) {
    method backtrack (line 16) | void backtrack(List result, String word, int position, String current,...

FILE: leetcode/backtracking/GenerateParentheses.java
  class GenerateParentheses (line 13) | class GenerateParentheses {
    method generateParenthesis (line 14) | public List<String> generateParenthesis(int n) {
    method generateParenthesisRecursive (line 21) | public void generateParenthesisRecursive(List<String> result, String c...

FILE: leetcode/backtracking/LetterCombinationsOfAPhoneNumber.java
  class LetterCombinationsOfAPhoneNumber (line 17) | class LetterCombinationsOfAPhoneNumber {
    method letterCombinations (line 18) | public List<String> letterCombinations(String digits) {
    method letterCombinationsRecursive (line 43) | public void letterCombinationsRecursive(List<String> result, String di...

FILE: leetcode/backtracking/Permutations.java
  class Permutations (line 14) | class Permutations {
    method permute (line 15) | public List<List<Integer>> permute(int[] nums) {

FILE: leetcode/binary-search/ClosestBinarySearchTreeValue.java
  class ClosestBinarySearchTreeValue (line 16) | public class ClosestBinarySearchTreeValue {
    method closestValue (line 17) | public int closestValue(TreeNode root, double target) {

FILE: leetcode/binary-search/FirstBadVersion.java
  class FirstBadVersion (line 10) | public class FirstBadVersion extends VersionControl {
    method firstBadVersion (line 11) | public int firstBadVersion(int n) {

FILE: leetcode/binary-search/GuessNumberHigherOrLower.java
  class GuessNumberHigherOrLower (line 17) | public class GuessNumberHigherOrLower extends GuessGame {
    method guessNumber (line 18) | public int guessNumber(int n) {

FILE: leetcode/binary-search/PowerOfXToTheN.java
  class PowerOfXToTheN (line 3) | public class PowerOfXToTheN {
    method myPow (line 4) | public double myPow(double x, int n) {

FILE: leetcode/binary-search/SquareRootX.java
  class Solution (line 5) | public class Solution {
    method mySqrt (line 6) | public int mySqrt(int x) {

FILE: leetcode/bit-manipulation/BinaryWatch.java
  class BinaryWatch (line 18) | public class BinaryWatch {
    method readBinaryWatch (line 19) | public List<String> readBinaryWatch(int num) {

FILE: leetcode/bit-manipulation/CountingBits.java
  class CountingBits (line 6) | public class CountingBits {
    method countBits (line 7) | public int[] countBits(int num) {

FILE: leetcode/bit-manipulation/HammingDistance.java
  class HammingDistance (line 21) | public class HammingDistance {
    method hammingDistance (line 22) | public int hammingDistance(int x, int y) {

FILE: leetcode/bit-manipulation/MaximumProductOfWordLengths.java
  class MaximumProductOfWordLengths (line 18) | public class MaximumProductOfWordLengths {
    method maxProduct (line 19) | public int maxProduct(String[] words) {

FILE: leetcode/bit-manipulation/NumberOfOneBits.java
  class NumberOfOneBits (line 5) | public class NumberOfOneBits {
    method hammingWeight (line 7) | public int hammingWeight(int n) {

FILE: leetcode/bit-manipulation/PowerOfTwo.java
  class PowerOfTwo (line 16) | class PowerOfTwo {
    method isPowerOfTwo (line 17) | public boolean isPowerOfTwo(int n) {

FILE: leetcode/bit-manipulation/SumOfTwoInteger.java
  class SumOfTwoIntegers (line 6) | public class SumOfTwoIntegers {
    method getSum (line 7) | public int getSum(int a, int b) {

FILE: leetcode/bit-manipulation/Utf8Validation.java
  class Utf8Validation (line 34) | public class Utf8Validation {
    method validUtf8 (line 35) | public boolean validUtf8(int[] data) {

FILE: leetcode/brainteaser/BulbSwitcher.java
  class BulbSwitcher (line 12) | class BulbSwitcher {
    method bulbSwitch (line 13) | public int bulbSwitch(int n) {

FILE: leetcode/breadth-first-search/BinaryTreeLevelOrderTraversal.java
  class BinarySearchTreeLevelOrderTraversal (line 26) | public class BinarySearchTreeLevelOrderTraversal {
    method levelOrder (line 27) | public List<List<Integer>> levelOrder(TreeNode root) {

FILE: leetcode/breadth-first-search/CloneGraph.java
  class CloneGraph (line 31) | public class CloneGraph {
    method cloneGraph (line 34) | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {

FILE: leetcode/breadth-first-search/PacificAtlanticWaterFlow.java
  class PacificAtlanticWaterFlow (line 27) | public class PacificAtlanticWaterFlow {
    method pacificAtlantic (line 28) | public List<int[]> pacificAtlantic(int[][] matrix) {
    method dfs (line 63) | public void dfs(int[][] matrix, boolean[][] visited, int height, int x...

FILE: leetcode/breadth-first-search/RemoveInvalidParentheses.java
  class RemoveInvalidParentheses (line 10) | public class RemoveInvalidParentheses {
    method removeInvalidParentheses (line 11) | public List<String> removeInvalidParentheses(String s) {
    method remove (line 17) | public void remove(String s, List<String> result, int last_i, int last...

FILE: leetcode/breadth-first-search/ShortestDistanceFromAllBuildings.java
  class Shortest (line 18) | public class Shortest {
    method shortestDistance (line 19) | public int shortestDistance(int[][] grid) {

FILE: leetcode/breadth-first-search/SymmetricTree.java
  class SymmetricTree (line 26) | public class SymmetricTree {
    method isSymmetric (line 27) | public boolean isSymmetric(TreeNode root) {
    method helper (line 35) | public boolean helper(TreeNode left, TreeNode right) {

FILE: leetcode/breadth-first-search/WallsAndGates.java
  class Solution (line 19) | public class Solution {
    method wallsAndGates (line 20) | public void wallsAndGates(int[][] rooms) {
    method dfs (line 31) | void dfs(int[][] rooms, int i, int j, int distance) {

FILE: leetcode/depth-first-search/BalancedBinaryTree.java
  class BalancedBinaryTree (line 14) | public class BalancedBinaryTree {
    method isBalanced (line 17) | public boolean isBalanced(TreeNode root) {
    method height (line 22) | private int height(TreeNode root) {

FILE: leetcode/depth-first-search/BattleshipsInABoard.java
  class BattleshipsInABoard (line 22) | public class BattleshipsInABoard {
    method countBattleships (line 23) | public int countBattleships(char[][] board) {
    method sink (line 38) | public void sink(char[][] board, int i, int j, int numberOfShips) {

FILE: leetcode/depth-first-search/ConvertSortedArrayToBinarySearchTree.java
  class ConvertSortedArrayToBinarySearchTree (line 12) | public class ConvertSortedArrayToBinarySearchTree {
    method sortedArrayToBST (line 13) | public TreeNode sortedArrayToBST(int[] nums) {
    method helper (line 23) | private TreeNode helper(int[] nums, int start, int end) {

FILE: leetcode/depth-first-search/MaximumDepthOfABinaryTree.java
  class MaximumDepthOfABinaryTree (line 14) | public class MaximumDepthOfABinaryTree {
    method maxDepth (line 15) | public int maxDepth(TreeNode root) {

FILE: leetcode/depth-first-search/NumberOfIslands.java
  class NumberOfIslands (line 19) | public class NumberOfIslands {
    method numIslands (line 22) | public int numIslands(char[][] grid) {
    method sink (line 41) | int sink(char[][] grid, int i, int j) {

FILE: leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java
  class PopulatingNextRightPointersInEachNode (line 38) | public class PopulatingNextRightPointersInEachNode {
    method connect (line 39) | public void connect(TreeLinkNode root) {

FILE: leetcode/depth-first-search/SameTree.java
  class SameTree (line 14) | public class SameTree {
    method isSameTree (line 15) | public boolean isSameTree(TreeNode p, TreeNode q) {

FILE: leetcode/design/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: leetcode/design/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: leetcode/design/ZigZagIterator.java
  class ZigZagIterator (line 17) | public class ZigZagIterator {
    method ZigzagIterator (line 22) | public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
    method next (line 27) | public int next() {
    method hasNext (line 37) | public boolean hasNext() {

FILE: leetcode/divide-and-conquer/ExpressionAddOperators.java
  class ExpressionAddOperators (line 10) | public class ExpressionAddOperators {
    method addOperators (line 11) | public List<String> addOperators(String num, int target) {
    method helper (line 22) | public void helper(List<String> result, String path, String num, int t...

FILE: leetcode/divide-and-conquer/KthLargestElementInAnArray.java
  class KthLargestElementInAnArray (line 9) | public class KthLargestElementInAnArray {
    method findKthLargest (line 10) | public int findKthLargest(int[] nums, int k) {

FILE: leetcode/dynamic-programming/BombEnemy.java
  class BombEnemy (line 14) | public class BombEnemy {
    method maxKilledEnemies (line 15) | public int maxKilledEnemies(char[][] grid) {
    method killedEnemiesRow (line 48) | private int killedEnemiesRow(char[][] grid, int i, int j) {
    method killedEnemiesCol (line 63) | private int killedEnemiesCol(char[][] grid, int i, int j) {

FILE: leetcode/dynamic-programming/ClimbingStairs.java
  class ClimbingStairs (line 7) | public class ClimbingStairs {
    method climbStairs (line 8) | public int climbStairs(int n) {

FILE: leetcode/dynamic-programming/CoinChange.java
  class CoinChange (line 14) | class CoinChange {
    method coinChange (line 15) | public int coinChange(int[] coins, int amount) {
    method coinChangeRecursive (line 23) | public int coinChangeRecursive(int[] coins, int amount, int[] dp) {

FILE: leetcode/dynamic-programming/CombinationSumIV.java
  class CombinationSumIV (line 26) | public class CombinationSumIV {
    method combinationSum4 (line 27) | public int combinationSum4(int[] nums, int target) {

FILE: leetcode/dynamic-programming/CountingBits.java
  class CountingBits (line 11) | public class CountingBits {
    method countBits (line 12) | public int[] countBits(int num) {

FILE: leetcode/dynamic-programming/EditDistance.java
  class EditDistance (line 9) | public class EditDistance {
    method minDistance (line 10) | public int minDistance(String word1, String word2) {

FILE: leetcode/dynamic-programming/HouseRobber.java
  class Solution (line 5) | public class Solution {
    method rob (line 6) | public int rob(int[] nums) {

FILE: leetcode/dynamic-programming/HouseRobberII.java
  class HouseRobberII (line 9) | class HouseRobberII {
    method rob (line 10) | public int rob(int[] nums) {

FILE: leetcode/dynamic-programming/LongestIncreasingSubsequence.java
  class LongestIncreasingSubsequence (line 11) | class LongestIncreasingSubsequence {
    method lengthOfLIS (line 12) | public int lengthOfLIS(int[] nums) {

FILE: leetcode/dynamic-programming/MinCostClimbingStairs.java
  class MinCostClimbingStairs (line 17) | class MinCostClimbingStairs {
    method minCostClimbingStairs (line 18) | public int minCostClimbingStairs(int[] cost) {

FILE: leetcode/dynamic-programming/MinimumPathSum.java
  class MinimumPathSum (line 10) | class MinimumPathSum {
    method minPathSum (line 11) | public int minPathSum(int[][] grid) {

FILE: leetcode/dynamic-programming/PaintFence.java
  class PaintFence (line 10) | public class PaintFence {
    method numWays (line 11) | public int numWays(int n, int k) {

FILE: leetcode/dynamic-programming/PaintHouse.java
  class PaintHouse (line 12) | class PaintHouse {
    method minCost (line 13) | public int minCost(int[][] costs) {

FILE: leetcode/dynamic-programming/PaintHouseII.java
  class PaintHouseII (line 11) | public class PaintHouseII {
    method minCostII (line 12) | public int minCostII(int[][] costs) {

FILE: leetcode/dynamic-programming/PalindromicSubstrings.java
  class PalindromicSubstrings (line 16) | class PalindromicSubstrings {
    method countSubstrings (line 18) | public int countSubstrings(String s) {
    method extendPalindrome (line 31) | public void extendPalindrome(String s, int left, int right) {

FILE: leetcode/dynamic-programming/RegularExpressionMatching.java
  class RegularExpressionMatching (line 20) | public class RegularExpressionMatching {
    method isMatch (line 21) | public boolean isMatch(String s, String p) {

FILE: leetcode/dynamic-programming/SentenceScreenFitting.java
  class SentenceScreenFitting (line 54) | public class SentenceScreenFitting {
    method wordsTyping (line 55) | public int wordsTyping(String[] sentence, int rows, int cols) {

FILE: leetcode/dynamic-programming/UniqueBinarySearchTrees.java
  class UniqueBinarySearchTree (line 12) | public class UniqueBinarySearchTree {
    method numTrees (line 13) | public int numTrees(int n) {

FILE: leetcode/dynamic-programming/UniquePaths.java
  class UniquePaths (line 7) | class UniquePaths {
    method uniquePaths (line 8) | public int uniquePaths(int m, int n) {

FILE: leetcode/dynamic-programming/WordBreak.java
  class WordBreak (line 9) | public class WordBreak {
    method wordBreak (line 10) | public boolean wordBreak(String s, Set<String> wordDict) {

FILE: leetcode/greedy/BestTimeToBuyAndSellStockII.java
  class BestTimeToBuyAndSellStockII (line 6) | class BestTimeToBuyAndSellStockII {
    method maxProfit (line 7) | public int maxProfit(int[] prices) {

FILE: leetcode/hash-table/BinaryTreeVerticalOrderTraversal.java
  class BinaryTreeVerticalOrderTraversal (line 67) | public class BinaryTreeVerticalOrderTraversal {
    method verticalOrder (line 68) | public List<List<Integer>> verticalOrder(TreeNode root) {

FILE: leetcode/hash-table/BullsAndCows.java
  class BullsAndCows (line 23) | class BullsAndCows {
    method getHint (line 24) | public String getHint(String secret, String guess) {

FILE: leetcode/hash-table/ContainsDuplicate.java
  class ContainsDuplicate (line 4) | class ContainsDuplicate {
    method containsDuplicate (line 5) | public boolean containsDuplicate(int[] nums) {

FILE: leetcode/hash-table/ContainsDuplicatesII.java
  class ContainsDuplicatesII (line 4) | class ContainsDuplicatesII {
    method containsNearbyDuplicate (line 5) | public boolean containsNearbyDuplicate(int[] nums, int k) {

FILE: leetcode/hash-table/DailyTemperatures.java
  class DailyTemperatures (line 7) | class DailyTemperatures {
    method dailyTemperatures (line 8) | public int[] dailyTemperatures(int[] temperatures) {

FILE: leetcode/hash-table/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: leetcode/hash-table/FindAnagramMappings.java
  class FindAnagramMappings (line 13) | class FindAnagramMappings {
    method anagramMappings (line 14) | public int[] anagramMappings(int[] A, int[] B) {

FILE: leetcode/hash-table/FindTheDifference.java
  class FindTheDifference (line 19) | public class FindTheDifference {
    method findTheDifference (line 20) | public char findTheDifference(String s, String t) {

FILE: leetcode/hash-table/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: leetcode/hash-table/GroupAnagrams.java
  class GroupAnagrams (line 13) | public class GroupAnagrams {
    method groupAnagrams (line 14) | public List<List<String>> groupAnagrams(String[] strs) {

FILE: leetcode/hash-table/GroupShiftedStrings.java
  class GroupShiftedStrings (line 16) | public class GroupShiftedStrings {
    method groupStrings (line 17) | public List<List<String>> groupStrings(String[] strings) {

FILE: leetcode/hash-table/InsertDeleteGetRandomO1.java
  class RandomizedSet (line 32) | class RandomizedSet {
    method RandomizedSet (line 37) | public RandomizedSet() {
    method insert (line 43) | public boolean insert(int val) {
    method remove (line 55) | public boolean remove(int val) {
    method getRandom (line 65) | public int getRandom() {

FILE: leetcode/hash-table/IslandPerimeter.java
  class IslandPerimeter (line 12) | class IslandPerimeter {
    method islandPerimeter (line 13) | public int islandPerimeter(int[][] grid) {
    method numNeighbors (line 31) | public int numNeighbors(int[][] grid, int x, int y) {

FILE: leetcode/hash-table/JewelsAndStones.java
  class JewelsAndStones (line 7) | class JewelsAndStones {
    method numJewelsInStones (line 8) | public int numJewelsInStones(String J, String S) {

FILE: leetcode/hash-table/LoggerRateLimiter.java
  class LoggerRateLimiter (line 29) | public class LoggerRateLimiter {
    method Logger (line 33) | public Logger() {
    method shouldPrintMessage (line 40) | public boolean shouldPrintMessage(int timestamp, String message) {

FILE: leetcode/hash-table/MaximumSizeSubarraySumEqualsK.java
  class MaximumSizeSubarraySumEqualsK (line 17) | public class MaximumSizeSubarraySumEqualsK {
    method maxSubArrayLen (line 18) | public int maxSubArrayLen(int[] nums, int k) {

FILE: leetcode/hash-table/MinimumWindowSubstring.java
  class MinimumWindowSubstring (line 13) | public class MinimumWindowSubstring {
    method minWindow (line 14) | public String minWindow(String s, String t) {

FILE: leetcode/hash-table/SingleNumberII.java
  class SingleNumberII (line 7) | class SingleNumberII {
    method singleNumber (line 8) | public int singleNumber(int[] nums) {

FILE: leetcode/hash-table/SparseMatrixMultiplication.java
  class SparseMatrixMultiplication (line 23) | public class SparseMatrixMultiplication {
    method multiply (line 24) | public int[][] multiply(int[][] A, int[][] B) {

FILE: leetcode/hash-table/StrobogrammaticNumber.java
  class StrobogrammaticNumber (line 7) | public class StrobogrammaticNumber {
    method isStrobogrammatic (line 8) | public boolean isStrobogrammatic(String num) {

FILE: leetcode/hash-table/TwoSum.java
  class TwoSum (line 11) | public class TwoSum {
    method twoSum (line 12) | public int[] twoSum(int[] nums, int target) {

FILE: leetcode/hash-table/UniqueWordAbbreviation.java
  class UniqueWordAbbreviation (line 34) | public class UniqueWordAbbreviation {
    method ValidWordAbbr (line 37) | public ValidWordAbbr(String[] dictionary) {
    method isUnique (line 53) | public boolean isUnique(String word) {
    method getKey (line 57) | public String getKey(String word) {

FILE: leetcode/hash-table/ValidAnagram.java
  class ValidAnagram (line 1) | class ValidAnagram {
    method isAnagram (line 2) | public boolean isAnagram(String s, String t) {

FILE: leetcode/hash-table/ValidSudoku.java
  class ValidSudoku (line 8) | class ValidSudoku {
    method isValidSudoku (line 9) | public boolean isValidSudoku(char[][] board) {

FILE: leetcode/linked-list/AddTwoNumbers.java
  class AddTwoNumbers (line 16) | public class AddTwoNumbers {
    method addTwoNumbers (line 17) | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

FILE: leetcode/linked-list/DeleteNodeInALinkedList.java
  class DeleteNodeInALinkedList (line 13) | public class DeleteNodeInALinkedList {
    method deleteNode (line 14) | public void deleteNode(ListNode node) {

FILE: leetcode/linked-list/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: leetcode/linked-list/MergeKSortedLists.java
  class MergeKSortedLists (line 11) | public class MergeKSortedLists {
    method mergeKLists (line 12) | public ListNode mergeKLists(ListNode[] lists) {

FILE: leetcode/linked-list/PalindromeLinkedList.java
  class PalindromeLinkedList (line 9) | public class PalindromeLinkedList {
    method isPalindrome (line 10) | public boolean isPalindrome(ListNode head) {

FILE: leetcode/linked-list/PlusOneLinkedList.java
  class PlusOneLinkedList (line 22) | public class PlusOneLinkedList {
    method plusOne (line 23) | public ListNode plusOne(ListNode head) {
    method plusOneRecursive (line 34) | private int plusOneRecursive(ListNode head) {

FILE: leetcode/linked-list/ReverseLinkedList.java
  class ReverseLinkedList (line 11) | public class ReverseLinkedList {
    method reverseList (line 12) | public ListNode reverseList(ListNode head) {

FILE: leetcode/math/AddDigits.java
  class AddDigits (line 9) | class AddDigits {
    method addDigits (line 10) | public int addDigits(int num) {

FILE: leetcode/math/BulbSwitcher.java
  class BulbSwitcher (line 12) | class BulbSwitcher {
    method bulbSwitch (line 13) | public int bulbSwitch(int n) {

FILE: leetcode/math/EncodeAndDecodeTinyURL.java
  class EncodeAndDecodeTinyURL (line 8) | public class EncodeAndDecodeTinyURL {
    method getKey (line 13) | public String getKey() {
    method encode (line 25) | public String encode(String longUrl) {
    method decode (line 34) | public String decode(String shortUrl) {

FILE: leetcode/math/PalindromeNumber.java
  class PalindromeNumber (line 3) | class PalindromeNumber {
    method isPalindrome (line 4) | public boolean isPalindrome(int x) {

FILE: leetcode/math/PlusOne.java
  class Solution (line 18) | class Solution {
    method plusOne (line 19) | public int[] plusOne(int[] digits) {

FILE: leetcode/math/PoorPigs.java
  class PoorPigs (line 11) | class PoorPigs {
    method poorPigs (line 12) | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {

FILE: leetcode/math/PowerOfTwo.java
  class PowerOfTwo (line 16) | class PowerOfTwo {
    method isPowerOfTwo (line 17) | public boolean isPowerOfTwo(int n) {

FILE: leetcode/queue/MovingAverageFromDataStream.java
  class MovingAverageFromDataStream (line 16) | public class MovingAverageFromDataStream {
    method MovingAverage (line 22) | public MovingAverage(int size) {
    method next (line 27) | public double next(int val) {

FILE: leetcode/sort/MeetingRooms.java
  class MeetingRooms (line 16) | public class MeetingRooms {
    method canAttendMeetings (line 17) | public boolean canAttendMeetings(Interval[] intervals) {

FILE: leetcode/sort/MeetingRoomsII.java
  class MeetingRoomsII (line 16) | public class MeetingRoomsII {
    method minMeetingRooms (line 17) | public int minMeetingRooms(Interval[] intervals) {

FILE: leetcode/stack/BinarySearchTreeIterator.java
  class BinarySearchTreeIterator (line 17) | public class BinarySearchTreeIterator {
    method BSTIterator (line 20) | public BSTIterator(TreeNode root) {
    method hasNext (line 30) | public boolean hasNext() {
    method next (line 35) | public int next() {

FILE: leetcode/stack/DailyTemperatures.java
  class DailyTemperatures (line 7) | class DailyTemperatures {
    method dailyTemperatures (line 8) | public int[] dailyTemperatures(int[] temperatures) {

FILE: leetcode/stack/DecodeString.java
  class DecodeString (line 9) | public class DecodeString {
    method decodeString (line 10) | public String decodeString(String s) {

FILE: leetcode/stack/ExclusiveTimeOfFunctions.java
  class ExclusiveTimeOfFunctions (line 30) | class ExclusiveTimeOfFunctions {
    method exclusiveTime (line 31) | public int[] exclusiveTime(int n, List<String> logs) {

FILE: leetcode/stack/FlattenNestedListIterator.java
  class FlattenNestedListIterator (line 32) | public class FlattenNestedListIterator implements Iterator<Integer> {
    method NestedIterator (line 35) | public NestedIterator(List<NestedInteger> nestedList) {
    method next (line 41) | @Override
    method hasNext (line 46) | @Override

FILE: leetcode/stack/MinStack.java
  class MinStack (line 15) | class MinStack {
    class Node (line 16) | class Node {
      method Node (line 21) | public Node(int data, int min) {
    method MinStack (line 30) | public MinStack() {
    method push (line 34) | public void push(int x) {
    method pop (line 44) | public void pop() {
    method top (line 48) | public int top() {
    method getMin (line 52) | public int getMin() {

FILE: leetcode/stack/TrappingRainWater.java
  class TrappingRainWater (line 6) | public class TrappingRainWater {
    method trap (line 7) | public int trap(int[] height) {

FILE: leetcode/string/AddBinary.java
  class AddBinary (line 8) | public class AddBinary {
    method addBinary (line 9) | public String addBinary(String a, String b) {

FILE: leetcode/string/CountAndSay.java
  class CountAndSay (line 11) | public class CountAndSay {
    method countAndSay (line 12) | public String countAndSay(int n) {
    method helper (line 22) | public String helper(String s) {

FILE: leetcode/string/DecodeWays.java
  class DecodeWays (line 15) | public class DecodeWays {
    method numDecodings (line 16) | public int numDecodings(String s) {

FILE: leetcode/string/EditDistance.java
  class EditDistance (line 9) | public class EditDistance {
    method minDistance (line 10) | public int minDistance(String word1, String word2) {

FILE: leetcode/string/FirstUniqueCharacterInAString.java
  class FirstUniqueCharacterInAString (line 12) | class FirstUniqueCharacterInAString {
    method firstUniqChar (line 13) | public int firstUniqChar(String s) {

FILE: leetcode/string/GenerateParentheses.java
  class GenerateParentheses (line 13) | class GenerateParentheses {
    method generateParenthesis (line 14) | public List<String> generateParenthesis(int n) {
    method generateParenthesisRecursive (line 21) | public void generateParenthesisRecursive(List<String> result, String c...

FILE: leetcode/string/IntegerToEnglishWords.java
  class IntegerToEnglishWords (line 9) | public class IntegerToEnglishWords {
    method numberToWords (line 14) | public String numberToWords(int num) {
    method helper (line 34) | private String helper(int num) {

FILE: leetcode/string/JudgeRouteCircle.java
  class JudgeRouteCircle (line 12) | class JudgeRouteCircle {
    method judgeCircle (line 13) | public boolean judgeCircle(String moves) {

FILE: leetcode/string/LongestCommonPrefix.java
  class LongestCommonPrefix (line 1) | class LongestCommonPrefix {
    method longestCommonPrefix (line 2) | public String longestCommonPrefix(String[] strs) {

FILE: leetcode/string/LongestPalindrome.java
  class LongestPalindrome (line 1) | public class LongestPalindrome {
    method longestPalindrome (line 2) | public int longestPalindrome(String s) {

FILE: leetcode/string/LongestPalindromicSubstring.java
  class LongestPalindromicSubstring (line 13) | class LongestPalindromicSubstring {
    method longestPalindrome (line 14) | public String longestPalindrome(String s) {
    method isPalindrome (line 31) | public boolean isPalindrome(String s) {

FILE: leetcode/string/LongestSubstringWithAtMostKDistinctCharacters.java
  class LongestSubstringWithAtMostKDistinctCharacters (line 7) | public class LongestSubstringWithAtMostKDistinctCharacters {
    method lengthOfLongestSubstringKDistinct (line 8) | public int lengthOfLongestSubstringKDistinct(String s, int k) {

FILE: leetcode/string/MinimumWindowSubstring.java
  class MinimumWindowSubstring (line 12) | public class MinimumWindowSubstring {
    method minWindow (line 13) | public String minWindow(String s, String t) {

FILE: leetcode/string/MultiplyStrings.java
  class MultiplyStrings (line 10) | public class MultiplyStrings {
    method multiply (line 11) | public String multiply(String num1, String num2) {

FILE: leetcode/string/OneEditDistance.java
  class OneEditDistance (line 3) | public class OneEditDistance {
    method isOneEditDistance (line 4) | public boolean isOneEditDistance(String s, String t) {

FILE: leetcode/string/PalindromePermutation.java
  class PalindromePermutation (line 1) | public class PalindromePermutation {
    method canPermutePalindrome (line 2) | public boolean canPermutePalindrome(String s) {

FILE: leetcode/string/PalindromicSubstrings.java
  class PalindromicSubstrings (line 16) | class PalindromicSubstrings {
    method countSubstrings (line 18) | public int countSubstrings(String s) {
    method extendPalindrome (line 31) | public void extendPalindrome(String s, int left, int right) {

FILE: leetcode/string/ReverseVowelsOfAString.java
  class ReverseVowelsOfAString (line 12) | public class ReverseVowelsOfAString {
    method reverseVowels (line 13) | public String reverseVowels(String s) {

FILE: leetcode/string/ReverseWordsInAString.java
  class ReverseWordsInAString (line 6) | public class ReverseWordsInAString {
    method reverseWords (line 7) | public String reverseWords(String s) {

FILE: leetcode/string/RomanToInteger.java
  class RomanToInteger (line 5) | public class RomanToInteger {
    method romanToInt (line 6) | public int romanToInt(String s) {

FILE: leetcode/string/ValidPalindrome.java
  class ValidPalindrome (line 1) | public class ValidPalindrome {
    method isPalindrome (line 2) | public boolean isPalindrome(String s) {

FILE: leetcode/string/ValidParentheses.java
  class ValidParentheses (line 5) | public class ValidParentheses {
    method isValid (line 6) | public boolean isValid(String s) {

FILE: leetcode/tree/BinaryTreeMaximumPathSum.java
  class BinaryTreeMaximumPathSum (line 22) | public class BinaryTreeMaximumPathSum {
    method maxPathSum (line 25) | public int maxPathSum(TreeNode root) {
    method maxPathSumRecursive (line 30) | private int maxPathSumRecursive(TreeNode root) {

FILE: leetcode/tree/BinaryTreePaths.java
  class BinaryTreePaths (line 23) | public class BinaryTreePaths {
    method binaryTreePaths (line 24) | public List<String> binaryTreePaths(TreeNode root) {
    method helper (line 36) | public void helper(String current, TreeNode root, List<String> result) {

FILE: leetcode/tree/InorderSuccessorInBST.java
  class InorderSuccessorInBST (line 14) | public class InorderSuccessorInBST {
    method inorderSuccessor (line 15) | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {

FILE: leetcode/tree/InvertBinaryTree.java
  class InvertBinaryTree (line 26) | public class InvertBinaryTree {
    method invertTree (line 27) | public TreeNode invertTree(TreeNode root) {

FILE: leetcode/tree/LowestCommonAncestorOfABinaryTree.java
  class LowestCommonAncestorOfABinaryTree (line 23) | public class LowestCommonAncestorOfABinaryTree {
    method lowestCommonAncestor (line 24) | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNo...

FILE: leetcode/tree/SumOfLeftLeaves.java
  class SumOfLeftLeaves (line 22) | public class SumOfLeftLeaves {
    method sumOfLeftLeaves (line 23) | public int sumOfLeftLeaves(TreeNode root) {

FILE: leetcode/tree/TrimABinarySearchTree.java
  class TrimABinarySearchTree (line 14) | class TrimABinarySearchTree {
    method trimBST (line 15) | public TreeNode trimBST(TreeNode root, int L, int R) {

FILE: leetcode/tree/ValidateBinarySearchTree.java
  class ValidateBinarySearchTree (line 28) | public class ValidateBinarySearchTree {
    method isValidBST (line 29) | public boolean isValidBST(TreeNode root) {
    method validBSTRecursive (line 37) | public boolean validBSTRecursive(TreeNode root, long minValue, long ma...

FILE: leetcode/trie/AddAndSearchWordDataStructureDesign.java
  class AddAndSearchWordDataStructure (line 20) | public class AddAndSearchWordDataStructure {
    class TrieNode (line 21) | public class TrieNode {
    method addWord (line 28) | public void addWord(String word) {
    method search (line 42) | public boolean search(String word) {
    method match (line 46) | private boolean match(char[] chs, int k, TrieNode node) {

FILE: leetcode/trie/ImplementTrie.java
  class TrieNode (line 11) | class TrieNode {
    method TrieNode (line 18) | public TrieNode(char character) {
  class ImplementTrie (line 28) | public class ImplementTrie {
    method Trie (line 31) | public Trie() {
    method insert (line 36) | public void insert(String word) {
    method search (line 51) | public boolean search(String word) {
    method startsWith (line 71) | public boolean startsWith(String prefix) {

FILE: leetcode/trie/WordSquares.java
  class WordSquares (line 18) | public class WordSquares {
    method wordSquares (line 19) | public List<List<String>> wordSquares(String[] words) {
    method helper (line 46) | public void helper(List<List<String>> ret, List<String> cur, int match...

FILE: leetcode/two-pointers/3Sum.java
  class Sum (line 13) | public class 3Sum {
    method threeSum (line 14) | public List<List<Integer>> threeSum(int[] nums) {

FILE: leetcode/two-pointers/3SumSmaller.java
  class SumSmaller (line 13) | public class 3SumSmaller {
    method threeSumSmaller (line 14) | public int threeSumSmaller(int[] nums, int target) {

FILE: leetcode/two-pointers/LinkedListCycle.java
  class Solution (line 15) | public class Solution {
    method hasCycle (line 16) | public boolean hasCycle(ListNode head) {

FILE: leetcode/two-pointers/MergeSortedArray.java
  class MergeSortedArray (line 6) | public class MergeSortedArray {
    method merge (line 7) | public void merge(int[] A, int m, int[] B, int n) {

FILE: leetcode/two-pointers/MinimumSizeSubarraySum.java
  class MinimumSizeSubarraySum (line 6) | public class MinimumSizeSubarraySum {
    method minSubArrayLen (line 7) | public int minSubArrayLen(int s, int[] nums) {

FILE: leetcode/two-pointers/MoveZeros.java
  class MoveZeros (line 9) | public class MoveZeros {
    method moveZeroes (line 10) | public void moveZeroes(int[] nums) {

FILE: leetcode/two-pointers/RemoveDuplicatesFromSortedArray.java
  class RemoveDuplicatesFromSortedArray (line 10) | public class RemoveDuplicatesFromSortedArray {
    method removeDuplicates (line 11) | public int removeDuplicates(int[] nums) {

FILE: leetcode/two-pointers/RemoveElement.java
  class RemoveElement (line 9) | class RemoveElement {
    method removeElement (line 10) | public int removeElement(int[] nums, int val) {

FILE: leetcode/two-pointers/ReverseString.java
  class ReverseString (line 6) | public class ReverseString {
    method reverseString (line 7) | public String reverseString(String s) {

FILE: leetcode/two-pointers/SortColors.java
  class SortColors (line 8) | public class SortColors {
    method sortColors (line 9) | public void sortColors(int[] nums) {

FILE: uva/AddingReversedNumbers.java
  class AddingReversedNumbers (line 39) | public class AddingReversedNumbers {
    method main (line 41) | public static void main(String[] args) {

FILE: uva/Ants.java
  class Ants (line 34) | public class Ants {
    method main (line 36) | public static void main(String args[]) throws Exception {

FILE: uva/ArchaeologistsDilemma.java
  class ArchaeologistsDilemma (line 34) | public class ArchaeologistsDilemma {
    method main (line 42) | public static void main(String[] args) {

FILE: uva/AverageSpeed.java
  class AverageSpeed (line 34) | public class AverageSpeed {
    method main (line 36) | public static void main(String[] args) {
    method calcHours (line 64) | private static double calcHours(String s) {

FILE: uva/BackToIntermediateMath.java
  class BackToIntermediateMath (line 37) | public class BackToIntermediateMath {
    method main (line 39) | public static void main(String[] args) {

FILE: uva/BasicRemains.java
  class BasicRemains (line 31) | public class BasicRemains {
    method main (line 33) | public static void main(String[] args) {

FILE: uva/BasicallySpeaking.java
  class BasicallySpeaking (line 46) | public class BasicallySpeaking {
    method main (line 48) | public static void main(String[] args) {

FILE: uva/BigMod.java
  class BigMod (line 35) | public class BigMod {
    method main (line 37) | public static void main(String[] args) {

FILE: uva/BrickGame.java
  class BrickGame (line 37) | public class BrickGame {
    method main (line 39) | public static void main(String[] args) {

FILE: uva/CoconutsRevisited.java
  class CoconutsRevisited (line 40) | public class CoconutsRevisited {
    method main (line 42) | public static void main(String[] args) {

FILE: uva/DigitCounting.java
  class DigitCounting (line 36) | public class DigitCounting {
    method main (line 38) | public static void main(String[] args) {

FILE: uva/FactorialFrequenices.java
  class FactorialFrequenices (line 42) | public class FactorialFrequenices {
    method main (line 44) | public static void main(String[] args) {
    method formatOutput (line 65) | private static void formatOutput(int number, int[] digits) {

FILE: uva/FiveHundredFactorial.java
  class FiveHundredFactorial (line 44) | public class FiveHundredFactorial {
    method main (line 46) | public static void main(String[] args) {

FILE: uva/Friends.java
  class Friends (line 47) | public class Friends {
    method main (line 53) | public static void main(String args[]) throws Exception {
    method startUnion (line 100) | public static void startUnion(int numberOfPeople, int[] people, int[] ...
    method union (line 114) | public static void union(int person, int friend) {
    method find (line 129) | public static int find(int person) {
    method join (line 142) | public static void join(int person, int friend) {

FILE: uva/GoldbachConjecture.java
  class GoldbachConjecture (line 40) | public class GoldbachConjecture {
    method main (line 42) | public static void main(String[] args) {
    method sieveOfEratosthenes (line 66) | private static boolean[] sieveOfEratosthenes(int number) {

FILE: uva/GoogleIsFeelingLucky.java
  class GoogleIsFeelingLucky (line 61) | public class GoogleIsFeelingLucky {
    method main (line 63) | public static void main(String args[]) {

FILE: uva/HashmatWarriors.java
  class HashmatWarriors (line 27) | public class HashmatWarriors {
    method main (line 29) | public static void main(String[] args) {

FILE: uva/HighPrecisionNumber.java
  class HighPrecisionNumber (line 46) | public class HighPrecisionNumber {
    method main (line 48) | public static void main(String[] args) {

FILE: uva/HighSchoolPhysics.java
  class HighSchoolPhysics (line 22) | public class HighSchoolPhysics {
    method main (line 24) | public static void main(String[] args) {

FILE: uva/ICanGuessTheDataStructure.java
  class ICanGuessTheDataStructure (line 69) | public class ICanGuessTheDataStructure {
    method main (line 71) | public static void main(String args[]) throws Exception {

FILE: uva/IntegerInquiry.java
  class IntegerInquiry (line 29) | public class IntegerInquiry {
    method main (line 31) | public static void main(String[] args) {

FILE: uva/JollyJumpers.java
  class JollyJumpers (line 28) | public class JollyJumpers {
    method main (line 30) | public static void main(String[] args) {

FILE: uva/LargestPrimeDivisor.java
  class LargestPrimeDivisor (line 29) | public class LargestPrimeDivisor {
    method main (line 31) | public static void main(String[] args) {

FILE: uva/LightMoreLight.java
  class LightMoreLight (line 30) | public class LightMoreLight {
    method main (line 32) | public static void main(String[] args) {
    method isAPerfectSquare (line 45) | private static boolean isAPerfectSquare(long number) {

FILE: uva/MischievousChildren.java
  class MischievousChildren (line 34) | public class MischievousChildren {
    method main (line 36) | public static void main(String[] args) {
    method computeFactorial (line 76) | private static long computeFactorial(int number) {

FILE: uva/Modex.java
  class Modex (line 34) | public class Modex {
    method main (line 36) | public static void main(String[] args) {

FILE: uva/MultipleOfSeventeen.java
  class MultipleOfSeventeen (line 30) | public class MultipleOfSeventeen {
    method main (line 35) | public static void main(String[] args) {

FILE: uva/Newspaper.java
  class Newspaper (line 45) | public class Newspaper {
    method main (line 47) | public static void main(String[] args) {

FILE: uva/NumberTheoryForNewbies.java
  class NumberTheoryForNewbies (line 28) | public class NumberTheoryForNewbies {
    method main (line 30) | public static void main(String[] args) {

FILE: uva/NumberingRoads.java
  class NumberingRoads (line 43) | public class NumberingRoads {
    method main (line 45) | public static void main(String[] args) {

FILE: uva/OpenSource.java
  class OpenSource (line 65) | public class OpenSource {
    method main (line 67) | public static void main(String args[]) throws Exception {
  class Pair (line 136) | class Pair {
    method Pair (line 140) | Pair(String name, int total) {

FILE: uva/Parity.java
  class Parity (line 29) | public class Parity {
    method main (line 31) | public static void main(String[] args) {
    method convertToBinary (line 51) | private static String convertToBinary(int number) {

FILE: uva/PeskyPalindromes.java
  class PeskyPalindromes (line 36) | public class PeskyPalindromes {
    method main (line 38) | public static void main(String args[]) {
    method generateSubstrings (line 58) | public static List<String> generateSubstrings(String s) {
    method findUniquePalindromes (line 82) | public static int findUniquePalindromes(List<String> allSubstrings) {

FILE: uva/PrimeFactors.java
  class PrimeFactors (line 60) | public class PrimeFactors {
    method main (line 62) | public static void main(String[] args) {
    method sieveOfEratosthenes (line 78) | public static List<Integer> sieveOfEratosthenes(boolean[] isPrime, int...
    method formatOutput (line 95) | static void formatOutput(int number, List<Integer> primeFactors, boole...
    method generatePrimeNumbers (line 120) | static boolean[] generatePrimeNumbers() {

FILE: uva/PseudoPrimeNumbers.java
  class PseudoPrimeNumbers (line 42) | public class PseudoPrimeNumbers {
    method main (line 44) | public static void main(String[] args) {

FILE: uva/SimplifyingFractions.java
  class SimplifyingFractions (line 26) | public class SimplifyingFractions {
    method main (line 28) | public static void main(String[] args) {

FILE: uva/SimplyEmirp.java
  class SimplyEmirp (line 39) | public class SimplyEmirp {
    method main (line 41) | public static void main(String[] args) {

FILE: uva/SkewBinary.java
  class SkewBinary (line 50) | public class SkewBinary {
    method main (line 52) | public static void main(String[] args) {

FILE: uva/SolveEquation.java
  class SolveEquation (line 19) | public class SolveEquation {
    method main (line 21) | public static void main(String[] args) {

FILE: uva/SplittingNumbers.java
  class SplittingNumbers (line 40) | public class SplittingNumbers {
    method main (line 42) | public static void main(String args[]) throws Exception {

FILE: uva/TheHugeOne.java
  class TheHugeOne (line 40) | public class TheHugeOne {
    method main (line 42) | public static void main(String[] args) {

FILE: uva/TheLastNonZeroDigit.java
  class TheLastNonZeroDigit (line 31) | public class TheLastNonZeroDigit {
    method main (line 33) | public static void main(String[] args) {

FILE: uva/TheSettlersOfCatan.java
  class TheSettlersOfCatan (line 56) | public class TheSettlersOfCatan {
    method main (line 61) | public static void main(String args[]) throws Exception {
    method dfs (line 108) | public static void dfs(int nd, int l, int nodes) {

FILE: uva/VeryEasy.java
  class VeryEasy (line 32) | public class VeryEasy {
    method main (line 34) | public static void main(String[] args) {

FILE: uva/VirtualFriends.java
  class VirtualFriends (line 37) | public class VirtualFriends {
    method main (line 42) | public static void main(String args[]) throws Exception {
    method startUnion (line 71) | public static void startUnion(int numberOfPeople) {
    method union (line 81) | public static int union(int person, int friend) {
    method find (line 104) | public static int find(int person) {

FILE: uva/WhatBaseIsThis.java
  class WhatBaseIsThis (line 54) | public class WhatBaseIsThis {
    method main (line 56) | public static void main(String[] args) {

FILE: uva/WhoSaidCrisis.java
  class WhoSaidCrisis (line 34) | public class WhoSaidCrisis {
    method main (line 36) | public static void main(String[] args) {
Condensed preview — 526 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (783K chars).
[
  {
    "path": ".gitignore",
    "chars": 12,
    "preview": "/bin/\n.idea\n"
  },
  {
    "path": ".project",
    "chars": 203,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>interviews</name>\n\t<comment></comment>\n\t<projects>\n\t<"
  },
  {
    "path": "LICENSE",
    "chars": 1075,
    "preview": "MIT License\n\nCopyright (c) 2018 Kevin Naughton Jr.\n\nPermission is hereby granted, free of charge, to any person obtainin"
  },
  {
    "path": "README-zh-cn.md",
    "chars": 12215,
    "preview": "> * 原文地址:[github.com/kdn251/interviews](https://github.com/kdn251/interviews)\n> * 译文出自:[掘金翻译计划](https://github.com/xitu/"
  },
  {
    "path": "README.md",
    "chars": 21813,
    "preview": "# Interviews\n> Pass your coding interviews with [The Daily Byte](https://thedailybyte.dev/?ref=kevin)  \n> [30,000+ Softw"
  },
  {
    "path": "company/Company.iml",
    "chars": 891,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n  <component name=\"NewModuleRootManager\" "
  },
  {
    "path": "company/adobe/AddDigits.java",
    "chars": 580,
    "preview": "//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.\n\n//For example:\n/"
  },
  {
    "path": "company/adobe/MajorityElement.java",
    "chars": 858,
    "preview": "//Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 "
  },
  {
    "path": "company/airbnb/AddTwoNumbers.java",
    "chars": 1574,
    "preview": "// You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse ord"
  },
  {
    "path": "company/airbnb/ContainsDuplicate.java",
    "chars": 576,
    "preview": "//Given an array of integers, find if the array contains any duplicates. Your function should return \n//true if any valu"
  },
  {
    "path": "company/airbnb/ContainsDuplicatesII.java",
    "chars": 677,
    "preview": "//Given an array of integers and an integer k, find out whether there are two distinct indices i and \n//j in the array s"
  },
  {
    "path": "company/airbnb/ConvertSortedArrayToBinarySearchTree.java",
    "chars": 940,
    "preview": "// Given an array where elements are sorted in ascending order, convert it to a height balanced BST.\n\n/**\n * Definition "
  },
  {
    "path": "company/airbnb/HouseRobber.java",
    "chars": 1021,
    "preview": "// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed"
  },
  {
    "path": "company/airbnb/MergeKSortedLists.java",
    "chars": 1304,
    "preview": "// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n/**\n * Definition"
  },
  {
    "path": "company/airbnb/RegularExpressionMatching.java",
    "chars": 1781,
    "preview": "// Implement regular expression matching with support for '.' and '*'.\n\n// '.' Matches any single character.\n// '*' Matc"
  },
  {
    "path": "company/airbnb/TwoSum.java",
    "chars": 849,
    "preview": "// Given an array of integers, return indices of the two numbers such that they add up to a specific target.\n\n// You may"
  },
  {
    "path": "company/airbnb/ValidParentheses.java",
    "chars": 1090,
    "preview": "// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid"
  },
  {
    "path": "company/amazon/3Sum.java",
    "chars": 1685,
    "preview": "// 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 "
  },
  {
    "path": "company/amazon/AddTwoNumbers.java",
    "chars": 1424,
    "preview": "// You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse ord"
  },
  {
    "path": "company/amazon/BestTimeToBuyAndSellStock.java",
    "chars": 1022,
    "preview": "// Say you have an array for which the ith element is the price of a given stock on day i.\n\n// If you were only permitte"
  },
  {
    "path": "company/amazon/BinaryTreeLevelOrderTraversal.java",
    "chars": 1812,
    "preview": "// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level)."
  },
  {
    "path": "company/amazon/EncodeAndDecodeTinyURL.java",
    "chars": 1423,
    "preview": "//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl \n//and "
  },
  {
    "path": "company/amazon/FirstUniqueCharacterInAString.java",
    "chars": 1002,
    "preview": "//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.\n//"
  },
  {
    "path": "company/amazon/GroupAnagrams.java",
    "chars": 1037,
    "preview": "// Given an array of strings, group anagrams together.\n\n// For example, given: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\""
  },
  {
    "path": "company/amazon/InsertDeleteGetRandomO1.java",
    "chars": 2401,
    "preview": "//Design a data structure that supports all following operations in average O(1) time.\n\n//insert(val): Inserts an item v"
  },
  {
    "path": "company/amazon/KthLargestElementInAnArray.java",
    "chars": 476,
    "preview": "// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not t"
  },
  {
    "path": "company/amazon/LetterCombinationsOfAPhoneNumber.java",
    "chars": 1460,
    "preview": "// Given a digit string, return all possible letter combinations that the number could represent.\n\n// A mapping of digit"
  },
  {
    "path": "company/amazon/LinkedListCycle.java",
    "chars": 720,
    "preview": "//Given a linked list, determine if it has a cycle in it.\n//Follow up:\n//Can you solve it without using extra space?\n/**"
  },
  {
    "path": "company/amazon/LongestPalindromicSubstring.java",
    "chars": 1102,
    "preview": "//Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\n/"
  },
  {
    "path": "company/amazon/LowestCommonAncestorOfABinaryTree.java",
    "chars": 1385,
    "preview": "// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\n// According to the defin"
  },
  {
    "path": "company/amazon/MergeKSortedLists.java",
    "chars": 1302,
    "preview": "// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n/**\n * Definition"
  },
  {
    "path": "company/amazon/MinCostClimbingStairs.java",
    "chars": 1340,
    "preview": "//On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).\n//\n//Once you pay the cost, you"
  },
  {
    "path": "company/amazon/MinStack.java",
    "chars": 1266,
    "preview": "//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n//push(x) -- Push el"
  },
  {
    "path": "company/amazon/NumberOfIslands.java",
    "chars": 1650,
    "preview": "// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water an"
  },
  {
    "path": "company/amazon/PalindromeLinkedList.java",
    "chars": 892,
    "preview": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNo"
  },
  {
    "path": "company/amazon/ProductOfArrayExceptSelf.java",
    "chars": 1047,
    "preview": "// Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of"
  },
  {
    "path": "company/amazon/ReverseLinkedList.java",
    "chars": 583,
    "preview": "// Reverse a singly linked list.\n\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n "
  },
  {
    "path": "company/amazon/RotateImage.java",
    "chars": 782,
    "preview": "// You are given an n x n 2D matrix representing an image.\n\n// Rotate the image by 90 degrees (clockwise).\n\n// Follow up"
  },
  {
    "path": "company/amazon/Subsets.java",
    "chars": 929,
    "preview": "// Given a set of distinct integers, nums, return all possible subsets.\n\n// Note: The solution set must not contain dupl"
  },
  {
    "path": "company/amazon/TrappingRainWater.java",
    "chars": 928,
    "preview": "// Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water "
  },
  {
    "path": "company/amazon/TwoSum.java",
    "chars": 849,
    "preview": "// Given an array of integers, return indices of the two numbers such that they add up to a specific target.\n\n// You may"
  },
  {
    "path": "company/amazon/ValidParentheses.java",
    "chars": 1090,
    "preview": "// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid"
  },
  {
    "path": "company/amazon/ValidateBinarySearchTree.java",
    "chars": 1329,
    "preview": "// Given a binary tree, determine if it is a valid binary search tree (BST).\n\n// Assume a BST is defined as follows:\n\n//"
  },
  {
    "path": "company/amazon/WordBreak.java",
    "chars": 881,
    "preview": "// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segm"
  },
  {
    "path": "company/apple/ReverseWordsInAString.java",
    "chars": 442,
    "preview": "//Given an input string, reverse the string word by word.\n//For example,\n//Given s = \"the sky is blue\",\n//return \"blue i"
  },
  {
    "path": "company/apple/ValidSudoku.java",
    "chars": 1316,
    "preview": "//Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx)\n//The S"
  },
  {
    "path": "company/bloomberg/FirstUniqueCharacterInAString.java",
    "chars": 1002,
    "preview": "//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.\n//"
  },
  {
    "path": "company/bloomberg/LinkedListCycle.java",
    "chars": 720,
    "preview": "//Given a linked list, determine if it has a cycle in it.\n//Follow up:\n//Can you solve it without using extra space?\n/**"
  },
  {
    "path": "company/bloomberg/LongestPalindromicSubstring.java",
    "chars": 1103,
    "preview": "//Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\n/"
  },
  {
    "path": "company/bloomberg/MinStack.java",
    "chars": 1266,
    "preview": "//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n//push(x) -- Push el"
  },
  {
    "path": "company/bloomberg/ReverseWordsInAString.java",
    "chars": 442,
    "preview": "//Given an input string, reverse the string word by word.\n//For example,\n//Given s = \"the sky is blue\",\n//return \"blue i"
  },
  {
    "path": "company/bloomberg/UniquePaths.java",
    "chars": 1091,
    "preview": "//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).\n//\n//The robot can on"
  },
  {
    "path": "company/facebook/3Sum.java",
    "chars": 1665,
    "preview": "// 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 "
  },
  {
    "path": "company/facebook/AddAndSearchWordDataStructureDesign.java",
    "chars": 1770,
    "preview": "// Design a data structure that supports the following two operations:\n\n// void addWord(word)\n// bool search(word)\n// se"
  },
  {
    "path": "company/facebook/AddBinary.java",
    "chars": 806,
    "preview": "// Given two binary strings, return their sum (also a binary string).\n\n// For example,\n// a = \"11\"\n// b = \"1\"\n// Return "
  },
  {
    "path": "company/facebook/BestTimeToBuyAndSellStock.java",
    "chars": 1022,
    "preview": "// Say you have an array for which the ith element is the price of a given stock on day i.\n\n// If you were only permitte"
  },
  {
    "path": "company/facebook/BinarySearchTreeIterator.java",
    "chars": 1368,
    "preview": "// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST."
  },
  {
    "path": "company/facebook/BinaryTreeLevelOrderTraversal.java",
    "chars": 1820,
    "preview": "// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level)."
  },
  {
    "path": "company/facebook/BinaryTreePaths.java",
    "chars": 1104,
    "preview": "// Given a binary tree, return all root-to-leaf paths.\n\n// For example, given the following binary tree:\n\n//    1\n//  / "
  },
  {
    "path": "company/facebook/BinaryTreeVerticalOrderTraversal.java",
    "chars": 2468,
    "preview": "// Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by col"
  },
  {
    "path": "company/facebook/CloneGraph.java",
    "chars": 1709,
    "preview": "// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.\n\n// OJ's undirected g"
  },
  {
    "path": "company/facebook/CombinationSumIV.java",
    "chars": 1154,
    "preview": "// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add"
  },
  {
    "path": "company/facebook/CountAndSay.java",
    "chars": 1195,
    "preview": "// The count-and-say sequence is the sequence of integers beginning as follows:\n// 1, 11, 21, 1211, 111221, ...\n\n// 1 is"
  },
  {
    "path": "company/facebook/DecodeWays.java",
    "chars": 949,
    "preview": "// A message containing letters from A-Z is being encoded to numbers using the following mapping:\n\n// 'A' -> 1\n// 'B' ->"
  },
  {
    "path": "company/facebook/EncodeAndDecodeTinyURL.java",
    "chars": 1423,
    "preview": "//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl \n//and "
  },
  {
    "path": "company/facebook/ExclusiveTimeOfFunctions.java",
    "chars": 2624,
    "preview": "//Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive tim"
  },
  {
    "path": "company/facebook/ExpressionAddOperators.java",
    "chars": 1639,
    "preview": "// Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (no"
  },
  {
    "path": "company/facebook/FindTheCelebrity.java",
    "chars": 1824,
    "preview": "// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The"
  },
  {
    "path": "company/facebook/FirstBadVersion.java",
    "chars": 1133,
    "preview": "// You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of"
  },
  {
    "path": "company/facebook/FlattenNestedListIterator.java",
    "chars": 2246,
    "preview": "// Given a nested list of integers, implement an iterator to flatten it.\n\n// Each element is either an integer, or a lis"
  },
  {
    "path": "company/facebook/GroupAnagrams.java",
    "chars": 1037,
    "preview": "// Given an array of strings, group anagrams together.\n\n// For example, given: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\""
  },
  {
    "path": "company/facebook/HammingDistance.java",
    "chars": 542,
    "preview": "// The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\n"
  },
  {
    "path": "company/facebook/ImplementTrie.java",
    "chars": 1961,
    "preview": "// Implement a trie with insert, search, and startsWith methods.\n\n// Note:\n// You may assume that all inputs are consist"
  },
  {
    "path": "company/facebook/InorderSuccessorInBST.java",
    "chars": 760,
    "preview": "// Given a binary search tree and a node in it, find the in-order successor of that node in the BST.\n\n// Note: If the gi"
  },
  {
    "path": "company/facebook/InsertDeleteGetRandomO1.java",
    "chars": 2401,
    "preview": "//Design a data structure that supports all following operations in average O(1) time.\n\n//insert(val): Inserts an item v"
  },
  {
    "path": "company/facebook/InsertInterval.java",
    "chars": 1271,
    "preview": "// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\n// You may "
  },
  {
    "path": "company/facebook/IntegerToEnglishWords.java",
    "chars": 1594,
    "preview": "// Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1"
  },
  {
    "path": "company/facebook/KthLargestElementInAnArray.java",
    "chars": 476,
    "preview": "// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not t"
  },
  {
    "path": "company/facebook/LetterCombinationsOfAPhoneNumber.java",
    "chars": 1460,
    "preview": "// Given a digit string, return all possible letter combinations that the number could represent.\n\n// A mapping of digit"
  },
  {
    "path": "company/facebook/LongestConsecutiveSequence.java",
    "chars": 1024,
    "preview": "// Given an unsorted array of integers, find the length of the longest consecutive elements sequence.\n\n// For example,\n/"
  },
  {
    "path": "company/facebook/LowestCommonAncestorOfABinaryTree.java",
    "chars": 1386,
    "preview": "// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\n// According to the defin"
  },
  {
    "path": "company/facebook/MaximumSizeSubarraySumEqualsK.java",
    "chars": 1261,
    "preview": "// 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, r"
  },
  {
    "path": "company/facebook/MeetingRooms.java",
    "chars": 989,
    "preview": "// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine"
  },
  {
    "path": "company/facebook/MergeIntervals.java",
    "chars": 1329,
    "preview": "// Given a collection of intervals, merge all overlapping intervals.\n\n// For example,\n// Given [1,3],[2,6],[8,10],[15,18"
  },
  {
    "path": "company/facebook/MergeKSortedLists.java",
    "chars": 1302,
    "preview": "// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n/**\n * Definition"
  },
  {
    "path": "company/facebook/MergeSortedArray.java",
    "chars": 660,
    "preview": "// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.\n\n// Note:\n// You may ass"
  },
  {
    "path": "company/facebook/MinStack.java",
    "chars": 984,
    "preview": "/**\n * Your MinStack object will be instantiated and called as such:\n * MinStack obj = new MinStack();\n * obj.push(x);\n "
  },
  {
    "path": "company/facebook/MinimumSizeSubarraySum.java",
    "chars": 891,
    "preview": "// Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of w"
  },
  {
    "path": "company/facebook/MinimumWindowSubstring.java",
    "chars": 1856,
    "preview": "// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexit"
  },
  {
    "path": "company/facebook/MoveZeros.java",
    "chars": 805,
    "preview": "// Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the no"
  },
  {
    "path": "company/facebook/MultiplyStrings.java",
    "chars": 1224,
    "preview": "// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.\n\n// Note:\n"
  },
  {
    "path": "company/facebook/NumberOfIslands.java",
    "chars": 1633,
    "preview": "// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water an"
  },
  {
    "path": "company/facebook/OneEditDistance.java",
    "chars": 1311,
    "preview": "// Given two strings S and T, determine if they are both one edit distance apart.\n\npublic class OneEditDistance {\n    pu"
  },
  {
    "path": "company/facebook/PaintHouseII.java",
    "chars": 1658,
    "preview": "    // There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house "
  },
  {
    "path": "company/facebook/PalindromeLinkedList.java",
    "chars": 892,
    "preview": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNo"
  },
  {
    "path": "company/facebook/PalindromicSubstrings.java",
    "chars": 1084,
    "preview": "//Given a string, your task is to count how many palindromic substrings in this string.\n//The substrings with different "
  },
  {
    "path": "company/facebook/PowerOfXToTheN.java",
    "chars": 401,
    "preview": "// Implement pow(x, n).\n\npublic class PowerOfXToTheN {\n    public double myPow(double x, int n) {\n        if(n == 0) {\n "
  },
  {
    "path": "company/facebook/ProductOfArrayExceptSelf.java",
    "chars": 1047,
    "preview": "// Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of"
  },
  {
    "path": "company/facebook/RegularExpressionMatching.java",
    "chars": 1781,
    "preview": "// Implement regular expression matching with support for '.' and '*'.\n\n// '.' Matches any single character.\n// '*' Matc"
  },
  {
    "path": "company/facebook/RemoveDuplicatesFromSortedArray.java",
    "chars": 919,
    "preview": "// Given a sorted array, remove the duplicates in place such that each element appear only once and return the new lengt"
  },
  {
    "path": "company/facebook/RemoveInvalidParentheses.java",
    "chars": 1580,
    "preview": "// Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results"
  },
  {
    "path": "company/facebook/ReverseLinkedList.java",
    "chars": 583,
    "preview": "// Reverse a singly linked list.\n\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n "
  },
  {
    "path": "company/facebook/RomanToInteger.java",
    "chars": 841,
    "preview": "// Given a roman numeral, convert it to an integer.\n\n// Input is guaranteed to be within the range from 1 to 3999\n\npubli"
  },
  {
    "path": "company/facebook/SearchInRotatedSortedArray.java",
    "chars": 1190,
    "preview": "// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.\n\n// (i.e., 0 1 2 4 5 6"
  },
  {
    "path": "company/facebook/SortColors.java",
    "chars": 949,
    "preview": "// Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, w"
  },
  {
    "path": "company/facebook/SparseMatrixMultiplication.java",
    "chars": 997,
    "preview": "// Given two sparse matrices A and B, return the result of AB.\n\n// You may assume that A's column number is equal to B's"
  },
  {
    "path": "company/facebook/SquareRootX.java",
    "chars": 598,
    "preview": "// Implement int sqrt(int x).\n\n// Compute and return the square root of x.\n\npublic class SquareRootX {\n    public int my"
  },
  {
    "path": "company/facebook/Subsets.java",
    "chars": 929,
    "preview": "// Given a set of distinct integers, nums, return all possible subsets.\n\n// Note: The solution set must not contain dupl"
  },
  {
    "path": "company/facebook/SubsetsII.java",
    "chars": 1185,
    "preview": "    // Given a collection of integers that might contain duplicates, nums, return all possible subsets.\n\n// Note: The so"
  },
  {
    "path": "company/facebook/SumOfLeftLeaves.java",
    "chars": 911,
    "preview": "// Find the sum of all left leaves in a given binary tree.\n\n// Example:\n\n//     3\n//    / \\\n//   9  20\n//     /  \\\n//   "
  },
  {
    "path": "company/facebook/TwoSum.java",
    "chars": 849,
    "preview": "// Given an array of integers, return indices of the two numbers such that they add up to a specific target.\n\n// You may"
  },
  {
    "path": "company/facebook/ValidPalindrome.java",
    "chars": 668,
    "preview": "public class ValidPalindrome {\n    public boolean isPalindrome(String s) {\n        int left = 0;\n        int right = s.l"
  },
  {
    "path": "company/facebook/ValidParentheses.java",
    "chars": 1090,
    "preview": "// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid"
  },
  {
    "path": "company/facebook/ValidateBinarySearchTree.java",
    "chars": 1329,
    "preview": "// Given a binary tree, determine if it is a valid binary search tree (BST).\n\n// Assume a BST is defined as follows:\n\n//"
  },
  {
    "path": "company/facebook/WallsAndGates.java",
    "chars": 1841,
    "preview": "// You are given a m x n 2D grid initialized with these three possible values.\n\n// -1 - A wall or an obstacle.\n// 0 - A "
  },
  {
    "path": "company/facebook/WordBreak.java",
    "chars": 881,
    "preview": "// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segm"
  },
  {
    "path": "company/facebook/WordSearch.java",
    "chars": 1593,
    "preview": "// Given a 2D board and a word, find if the word exists in the grid.\n\n// The word can be constructed from letters of seq"
  },
  {
    "path": "company/google/3SumSmaller.java",
    "chars": 1585,
    "preview": "// 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 tha"
  },
  {
    "path": "company/google/AndroidUnlockPatterns.java",
    "chars": 3283,
    "preview": "// Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock "
  },
  {
    "path": "company/google/BinarySearchTreeIterator.java",
    "chars": 1377,
    "preview": "// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST."
  },
  {
    "path": "company/google/BinaryTreePaths.java",
    "chars": 1104,
    "preview": "// Given a binary tree, return all root-to-leaf paths.\n\n// For example, given the following binary tree:\n\n//    1\n//  / "
  },
  {
    "path": "company/google/BinaryTreeVerticalOrderTraversal.java",
    "chars": 2476,
    "preview": "// Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by col"
  },
  {
    "path": "company/google/BinaryWatch.java",
    "chars": 1477,
    "preview": "// A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the min"
  },
  {
    "path": "company/google/BombEnemy.java",
    "chars": 2046,
    "preview": "//  Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum ene"
  },
  {
    "path": "company/google/BullsAndCows.java",
    "chars": 1790,
    "preview": "//You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to gue"
  },
  {
    "path": "company/google/CloneGraph.java",
    "chars": 1709,
    "preview": "// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.\n\n// OJ's undirected g"
  },
  {
    "path": "company/google/ClosestBinarySearchTreeValue.java",
    "chars": 876,
    "preview": "// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.\n\n//"
  },
  {
    "path": "company/google/CombinationSumIV.java",
    "chars": 1054,
    "preview": "// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add"
  },
  {
    "path": "company/google/DailyTemperatures.java",
    "chars": 997,
    "preview": "//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would "
  },
  {
    "path": "company/google/DecodeString.java",
    "chars": 2475,
    "preview": "// Given an encoded string, return it's decoded string.\n\n// The encoding rule is: k[encoded_string], where the encoded_s"
  },
  {
    "path": "company/google/EncodeAndDecodeTinyURL.java",
    "chars": 1423,
    "preview": "//TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl \n//and "
  },
  {
    "path": "company/google/ExpressionAddOperators.java",
    "chars": 1638,
    "preview": "// Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (no"
  },
  {
    "path": "company/google/FindAllNumbersDisappearedInAnArray.java",
    "chars": 1050,
    "preview": "//Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.\n"
  },
  {
    "path": "company/google/FindTheDifference.java",
    "chars": 768,
    "preview": "// Given two strings s and t which consist of only lowercase letters.\n\n// String t is generated by random shuffling stri"
  },
  {
    "path": "company/google/FirstUniqueCharacterInAString.java",
    "chars": 1002,
    "preview": "//Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.\n//"
  },
  {
    "path": "company/google/FlattenNestedListIterator.java",
    "chars": 2246,
    "preview": "// Given a nested list of integers, implement an iterator to flatten it.\n\n// Each element is either an integer, or a lis"
  },
  {
    "path": "company/google/GameOfLife.java",
    "chars": 2533,
    "preview": "// According to the Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular automaton devised b"
  },
  {
    "path": "company/google/GeneralizedAbbreviation.java",
    "chars": 994,
    "preview": "// Write a function to generate the generalized abbreviations of a word.\n\n// Example:\n// Given word = \"word\", return the"
  },
  {
    "path": "company/google/GenerateParentheses.java",
    "chars": 956,
    "preview": "//Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n//\n//For examp"
  },
  {
    "path": "company/google/GroupShiftedStrings.java",
    "chars": 1616,
    "preview": "// Given a string, we can \"shift\" each of its letter to its successive letter, for example: \"abc\" -> \"bcd\". We can keep "
  },
  {
    "path": "company/google/GuessNumberHigherOrLower.java",
    "chars": 1105,
    "preview": "// We are playing the Guess Game. The game is as follows:\n\n// I pick a number from 1 to n. You have to guess which numbe"
  },
  {
    "path": "company/google/ImplementTrie.java",
    "chars": 1952,
    "preview": "// Implement a trie with insert, search, and startsWith methods.\n\n// Note:\n// You may assume that all inputs are consist"
  },
  {
    "path": "company/google/InsertDeleteGetRandomO1.java",
    "chars": 2400,
    "preview": "//Design a data structure that supports all following operations in average O(1) time.\n\n//insert(val): Inserts an item v"
  },
  {
    "path": "company/google/InsertInterval.java",
    "chars": 1271,
    "preview": "// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\n// You may "
  },
  {
    "path": "company/google/IslandPerimeter.java",
    "chars": 1582,
    "preview": "// You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid ce"
  },
  {
    "path": "company/google/JudgeRouteCircle.java",
    "chars": 1010,
    "preview": "//Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, whi"
  },
  {
    "path": "company/google/LetterCombinationsOfAPhoneNumber.java",
    "chars": 1460,
    "preview": "// Given a digit string, return all possible letter combinations that the number could represent.\n\n// A mapping of digit"
  },
  {
    "path": "company/google/LoggerRateLimiter.java",
    "chars": 2063,
    "preview": "// Design a logger system that receive stream of messages along with its timestamps, each message should be printed if a"
  },
  {
    "path": "company/google/LongestConsecutiveSequence.java",
    "chars": 1024,
    "preview": "// Given an unsorted array of integers, find the length of the longest consecutive elements sequence.\n\n// For example,\n/"
  },
  {
    "path": "company/google/LongestSubstringWithAtMostKDistinctCharacters.java",
    "chars": 1052,
    "preview": "// Given a string, find the length of the longest substring T that contains at most k distinct characters.\n\n// For examp"
  },
  {
    "path": "company/google/MaximumProductOfWordLengths.java",
    "chars": 1449,
    "preview": "// Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not sh"
  },
  {
    "path": "company/google/MergeIntervals.java",
    "chars": 1329,
    "preview": "// Given a collection of intervals, merge all overlapping intervals.\n\n// For example,\n// Given [1,3],[2,6],[8,10],[15,18"
  },
  {
    "path": "company/google/MinStack.java",
    "chars": 1266,
    "preview": "//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n//push(x) -- Push el"
  },
  {
    "path": "company/google/MissingRanges.java",
    "chars": 963,
    "preview": "// Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missin"
  },
  {
    "path": "company/google/MovingAverageFromDataStream.java",
    "chars": 979,
    "preview": "// Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.\n\n//"
  },
  {
    "path": "company/google/NumberOfIslands.java",
    "chars": 1633,
    "preview": "// Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water an"
  },
  {
    "path": "company/google/PacificAtlanticWaterFlow.java",
    "chars": 2648,
    "preview": "// Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the \"Pacific"
  },
  {
    "path": "company/google/PaintFence.java",
    "chars": 797,
    "preview": "// There is a fence with n posts, each post can be painted with one of the k colors.\n\n// You have to paint all the posts"
  },
  {
    "path": "company/google/PlusOne.java",
    "chars": 919,
    "preview": "//Given a non-empty array of digits representing a non-negative integer, plus one to the integer.\n//\n//The digits are st"
  },
  {
    "path": "company/google/PlusOneLinkedList.java",
    "chars": 1153,
    "preview": "// Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.\n\n// Yo"
  },
  {
    "path": "company/google/PowerOfTwo.java",
    "chars": 383,
    "preview": "//Given an integer, write a function to determine if it is a power of two.\n//\n//Example 1:\n//\n//Input: 1\n//Output: true\n"
  },
  {
    "path": "company/google/PowerOfXToTheN.java",
    "chars": 401,
    "preview": "// Implement pow(x, n).\n\npublic class PowerOfXToTheN {\n    public double myPow(double x, int n) {\n        if(n == 0) {\n "
  },
  {
    "path": "company/google/RegularExpressionMatching.javaa",
    "chars": 1781,
    "preview": "// Implement regular expression matching with support for '.' and '*'.\n\n// '.' Matches any single character.\n// '*' Matc"
  },
  {
    "path": "company/google/ReverseVowelsOfAString.java",
    "chars": 1083,
    "preview": "// Write a function that takes a string as input and reverse only the vowels of a string.\n\n// Example 1:\n// Given s = \"h"
  },
  {
    "path": "company/google/SentenceScreenFitting.java",
    "chars": 1706,
    "preview": "// Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sen"
  },
  {
    "path": "company/google/ShortestDistanceFromAllBuildings.java",
    "chars": 3433,
    "preview": "// You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can on"
  },
  {
    "path": "company/google/SpiralMatrix.java",
    "chars": 1543,
    "preview": "//Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\n//\n//Example "
  },
  {
    "path": "company/google/StrobogrammaticNumber.java",
    "chars": 616,
    "preview": "// A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).\n\n// Write "
  },
  {
    "path": "company/google/SummaryRanges.java",
    "chars": 832,
    "preview": "// Given a sorted integer array without duplicates, return the summary of its ranges.\n\n// For example, given [0,1,2,4,5,"
  },
  {
    "path": "company/google/TrappingRainWater.java",
    "chars": 928,
    "preview": "// Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water "
  },
  {
    "path": "company/google/UniqueWordAbbreviation.java",
    "chars": 1900,
    "preview": "// An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbre"
  },
  {
    "path": "company/google/Utf8Validation.java",
    "chars": 2280,
    "preview": "// A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:\n\n// For 1-byte character, the fi"
  },
  {
    "path": "company/google/ValidParentheses.java",
    "chars": 1090,
    "preview": "// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid"
  },
  {
    "path": "company/google/WallsAndGates.java",
    "chars": 1844,
    "preview": "// You are given a m x n 2D grid initialized with these three possible values.\n\n// -1 - A wall or an obstacle.\n// 0 - A "
  },
  {
    "path": "company/google/WiggleSort.java",
    "chars": 516,
    "preview": "// Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....\n\n// For exam"
  },
  {
    "path": "company/google/WordBreak.java",
    "chars": 872,
    "preview": "// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segm"
  },
  {
    "path": "company/google/WordSquares.java",
    "chars": 2182,
    "preview": "// Given a set of words (without duplicates), find all word squares you can build from them.\n\n// A sequence of words for"
  },
  {
    "path": "company/google/ZigZagIterator.java",
    "chars": 1082,
    "preview": "// Given two 1d vectors, implement an iterator to return their elements alternately.\n\n// For example, given two 1d vecto"
  },
  {
    "path": "company/linkedin/BinarySearchTreeIterator.java",
    "chars": 1377,
    "preview": "// Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST."
  },
  {
    "path": "company/linkedin/BinaryTreeLevelOrderTraversal.java",
    "chars": 1820,
    "preview": "// Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level)."
  },
  {
    "path": "company/linkedin/FindTheCelebrity.java",
    "chars": 1815,
    "preview": "// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The"
  },
  {
    "path": "company/linkedin/HouseRobber.java",
    "chars": 997,
    "preview": "// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed"
  },
  {
    "path": "company/linkedin/InsertInterval.java",
    "chars": 1271,
    "preview": "// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\n// You may "
  },
  {
    "path": "company/linkedin/LowestCommonAncestorOfABinaryTree.java",
    "chars": 1385,
    "preview": "// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\n// According to the defin"
  },
  {
    "path": "company/linkedin/MaximumDepthOfABinaryTree.java",
    "chars": 573,
    "preview": "// Given a binary tree, find its maximum depth.\n\n// The maximum depth is the number of nodes along the longest path from"
  },
  {
    "path": "company/linkedin/MaximumProductSubarray.java",
    "chars": 848,
    "preview": "// Find the contiguous subarray within an array (containing at least one number) which has the largest product.\n\n// For "
  },
  {
    "path": "company/linkedin/MaximumSubarray.java",
    "chars": 617,
    "preview": "// Find the contiguous subarray within an array (containing at least one number) which has the largest sum.\n\n// For exam"
  },
  {
    "path": "company/linkedin/MergeIntervals.java",
    "chars": 1329,
    "preview": "// Given a collection of intervals, merge all overlapping intervals.\n\n// For example,\n// Given [1,3],[2,6],[8,10],[15,18"
  },
  {
    "path": "company/linkedin/MergeKSortedLists.java",
    "chars": 1327,
    "preview": "// Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n/**\n * Definition"
  },
  {
    "path": "company/linkedin/MinimumWindowSubstring.java",
    "chars": 1856,
    "preview": "// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexit"
  },
  {
    "path": "company/linkedin/PaintHouse.java",
    "chars": 1160,
    "preview": "//There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. \n//The cost o"
  },
  {
    "path": "company/linkedin/PalindromicSubstrings.java",
    "chars": 1084,
    "preview": "//Given a string, your task is to count how many palindromic substrings in this string.\n//The substrings with different "
  },
  {
    "path": "company/linkedin/Permutations.java",
    "chars": 882,
    "preview": "//Given a collection of distinct numbers, return all possible permutations.\n//\n//For example,\n//[1,2,3] have the followi"
  },
  {
    "path": "company/linkedin/PowerOfXToTheN.java",
    "chars": 401,
    "preview": "// Implement pow(x, n).\n\npublic class PowerOfXToTheN {\n    public double myPow(double x, int n) {\n        if(n == 0) {\n "
  },
  {
    "path": "company/linkedin/ProductOfArrayExceptSelf.java",
    "chars": 1047,
    "preview": "// Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of"
  },
  {
    "path": "company/linkedin/SearchInRotatedSortedArray.java",
    "chars": 1190,
    "preview": "// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.\n\n// (i.e., 0 1 2 4 5 6"
  },
  {
    "path": "company/linkedin/SparseMatrixMultiplication.java",
    "chars": 997,
    "preview": "// Given two sparse matrices A and B, return the result of AB.\n\n// You may assume that A's column number is equal to B's"
  },
  {
    "path": "company/linkedin/SymmetricTree.java",
    "chars": 1055,
    "preview": "// Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n\n// For example, this "
  },
  {
    "path": "company/linkedin/TwoSum.java",
    "chars": 849,
    "preview": "// Given an array of integers, return indices of the two numbers such that they add up to a specific target.\n\n// You may"
  },
  {
    "path": "company/microsoft/AddDigits.java",
    "chars": 580,
    "preview": "//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.\n\n//For example:\n/"
  }
]

// ... and 326 more files (download for full content)

About this extraction

This page contains the full source code of the kdn251/interviews GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 526 files (696.0 KB), approximately 196.9k tokens, and a symbol index with 1317 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!