├── .DS_Store ├── .gitignore ├── .project ├── LICENSE ├── README-zh-cn.md ├── README.md ├── company ├── .DS_Store ├── 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 ├── images ├── BST.png ├── Complete.png ├── Full.png ├── InterviewsRepository.jpg ├── Perfect.png ├── bellman-ford.gif ├── bigO.png ├── bigOmega.png ├── bucketsort.png ├── dfsbfs.gif ├── dijkstra.gif ├── fenwickTree.png ├── graph.png ├── hash.png ├── heap.png ├── kruskal.gif ├── mergesort.gif ├── prim.gif ├── quicksort.gif ├── segmentTree.png ├── the-daily-byte.png ├── theta.png ├── trie.png ├── youtube.jpg └── youtube.png ├── interviews.iml ├── leetcode ├── .DS_Store ├── 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 │ ├── .DS_Store │ └── 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 /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | .idea 3 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | interviews 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Kevin Naughton Jr. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /company/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/.DS_Store -------------------------------------------------------------------------------- /company/Company.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /company/adobe/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /company/adobe/MajorityElement.java: -------------------------------------------------------------------------------- 1 | //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | //You may assume that the array is non-empty and the majority element always exist in the array. 3 | 4 | class MajorityElement { 5 | public int majorityElement(int[] nums) { 6 | if(nums.length == 1) { 7 | return nums[0]; 8 | } 9 | 10 | HashMap map = new HashMap(); 11 | for(int current: nums) { 12 | if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) { 13 | return current; 14 | } else if(map.containsKey(current)) { 15 | map.put(current, map.get(current) + 1); 16 | } else { 17 | map.put(current, 1); 18 | } 19 | } 20 | 21 | //no majority element exists 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /company/airbnb/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /company/airbnb/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /company/airbnb/ConvertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public TreeNode sortedArrayToBST(int[] nums) { 14 | if(nums.length == 0) { 15 | return null; 16 | } 17 | 18 | TreeNode root = helper(nums, 0, nums.length - 1); 19 | 20 | return root; 21 | } 22 | 23 | private TreeNode helper(int[] nums, int start, int end) { 24 | if(start <= end) { 25 | int mid = (start + end) / 2; 26 | 27 | TreeNode current = new TreeNode(nums[mid]); 28 | 29 | current.left = helper(nums, start, mid - 1); 30 | current.right = helper(nums, mid + 1, end); 31 | 32 | return current; 33 | } 34 | 35 | return null; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /company/airbnb/HouseRobber.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // 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. 4 | 5 | public class HouseRobber { 6 | public int rob(int[] nums) { 7 | if(nums.length == 0) { 8 | return 0; 9 | } 10 | 11 | if(nums.length == 1) { 12 | return nums[0]; 13 | } 14 | 15 | int[] dp = new int[nums.length]; 16 | 17 | dp[0] = nums[0]; 18 | dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; 19 | 20 | for(int i = 2; i < nums.length; i++) { 21 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 22 | } 23 | 24 | return dp[dp.length - 1]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /company/airbnb/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | 22 | return result; 23 | } 24 | 25 | map.put(nums[i], i); 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/amazon/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | 3 | // 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. 4 | 5 | // Example 1: 6 | // Input: [7, 1, 5, 3, 6, 4] 7 | // Output: 5 8 | 9 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 10 | // Example 2: 11 | // Input: [7, 6, 4, 3, 1] 12 | // Output: 0 13 | 14 | // In this case, no transaction is done, i.e. max profit = 0. 15 | 16 | public class BestTimeToBuyAndSellStock { 17 | public int maxProfit(int[] prices) { 18 | //Kadane's algorithm 19 | if(prices.length == 0) { 20 | return 0; 21 | } 22 | 23 | int max = 0; 24 | int min = prices[0]; 25 | 26 | for(int i = 1; i < prices.length; i++) { 27 | if(prices[i] > min) { 28 | max = Math.max(max, prices[i] - min); 29 | } else { 30 | min = prices[i]; 31 | } 32 | } 33 | 34 | return max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /company/amazon/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/amazon/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | 13 | Arrays.sort(nums); 14 | 15 | return nums[length - k]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /company/amazon/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /company/amazon/PalindromeLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class PalindromeLinkedList { 10 | public boolean isPalindrome(ListNode head) { 11 | if(head == null || head.next == null) { 12 | return true; 13 | } 14 | 15 | Stack stack = new Stack(); 16 | 17 | ListNode fast = head; 18 | ListNode slow = head; 19 | 20 | while(fast != null && fast.next != null) { 21 | stack.push(slow.val); 22 | fast = fast.next.next; 23 | slow = slow.next; 24 | } 25 | 26 | if(fast != null) { 27 | slow = slow.next; 28 | } 29 | 30 | while(slow != null) { 31 | if(stack.pop() != slow.val) { 32 | return false; 33 | } 34 | 35 | slow = slow.next; 36 | } 37 | 38 | return true; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /company/amazon/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/amazon/RotateImage.java: -------------------------------------------------------------------------------- 1 | // You are given an n x n 2D matrix representing an image. 2 | 3 | // Rotate the image by 90 degrees (clockwise). 4 | 5 | // Follow up: 6 | // Could you do this in-place? 7 | 8 | public class RotateImage { 9 | public void rotate(int[][] matrix) { 10 | for(int i = 0; i < matrix.length; i++) { 11 | for(int j = 0; j < i; j++) { 12 | int temp = matrix[i][j]; 13 | matrix[i][j] = matrix[j][i]; 14 | matrix[j][i] = temp; 15 | } 16 | } 17 | 18 | for(int i = 0; i < matrix.length; i++) { 19 | for(int j = 0; j < matrix[0].length / 2; j++) { 20 | int temp = matrix[i][j]; 21 | matrix[i][j] = matrix[i][matrix[0].length - 1 - j]; 22 | matrix[i][matrix[0].length - 1 - j] = temp; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /company/amazon/Subsets.java: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets. 2 | 3 | // Note: The solution set must not contain duplicate subsets. 4 | 5 | // For example, 6 | // If nums = [1,2,3], a solution is: 7 | 8 | // [ 9 | // [3], 10 | // [1], 11 | // [2], 12 | // [1,2,3], 13 | // [1,3], 14 | // [2,3], 15 | // [1,2], 16 | // [] 17 | // ] 18 | 19 | public class Subsets { 20 | public List> subsets(int[] nums) { 21 | List> result = new ArrayList<>(); 22 | 23 | recurse(result, nums, new Stack<>(), 0); 24 | 25 | return result; 26 | } 27 | 28 | 29 | private void recurse(List> result, int[] nums, Stack path, int position) { 30 | if(position == nums.length) { 31 | result.add(new ArrayList<>(path)); 32 | 33 | return; 34 | } 35 | 36 | path.push(nums[position]); 37 | 38 | recurse(result, nums, path, position + 1); 39 | 40 | path.pop(); 41 | 42 | recurse(result, nums, path, position + 1); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /company/amazon/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 5 | 6 | public class TrappingRainWater { 7 | public int trap(int[] height) { 8 | int water = 0; 9 | 10 | int leftIndex = 0; 11 | int rightIndex = height.length - 1; 12 | 13 | int leftMax = 0; 14 | int rightMax = 0; 15 | 16 | while(leftIndex <= rightIndex) { 17 | leftMax = Math.max(leftMax, height[leftIndex]); 18 | rightMax = Math.max(rightMax, height[rightIndex]); 19 | 20 | if(leftMax < rightMax) { 21 | water += leftMax - height[leftIndex]; 22 | leftIndex++; 23 | } else { 24 | water += rightMax - height[rightIndex]; 25 | rightIndex--; 26 | } 27 | } 28 | 29 | return water; 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /company/amazon/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | 22 | return result; 23 | } 24 | 25 | map.put(nums[i], i); 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/amazon/WordBreak.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given 4 | // s = "leetcode", 5 | // dict = ["leet", "code"]. 6 | 7 | // Return true because "leetcode" can be segmented as "leet code". 8 | 9 | public class WordBreak { 10 | public boolean wordBreak(String s, Set wordDict) { 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | 13 | dp[0] = true; 14 | 15 | for(int i = 1; i <= s.length(); i++) { 16 | for(int j = 0; j < i; j++) { 17 | if(dp[j] && wordDict.contains(s.substring(j, i))) { 18 | dp[i] = true; 19 | break; 20 | } 21 | } 22 | } 23 | 24 | return dp[s.length()]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /company/apple/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /company/bloomberg/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/bloomberg/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /company/bloomberg/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /company/facebook/AddBinary.java: -------------------------------------------------------------------------------- 1 | // Given two binary strings, return their sum (also a binary string). 2 | 3 | // For example, 4 | // a = "11" 5 | // b = "1" 6 | // Return "100" 7 | 8 | public class AddBinary { 9 | public String addBinary(String a, String b) { 10 | StringBuilder result = new StringBuilder(); 11 | 12 | int carry = 0; 13 | 14 | int i = a.length() - 1; 15 | int j = b.length() - 1; 16 | 17 | while(i >= 0 || j >= 0) { 18 | int sum = carry; 19 | 20 | if(i >= 0) { 21 | sum += a.charAt(i--) - '0'; 22 | } 23 | 24 | if(j >= 0) { 25 | sum += b.charAt(j--) - '0'; 26 | } 27 | 28 | result.append(sum % 2); 29 | carry = sum / 2; 30 | } 31 | 32 | if(carry != 0) { 33 | result.append(carry); 34 | } 35 | 36 | return result.reverse().toString(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /company/facebook/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | 3 | // 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. 4 | 5 | // Example 1: 6 | // Input: [7, 1, 5, 3, 6, 4] 7 | // Output: 5 8 | 9 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 10 | // Example 2: 11 | // Input: [7, 6, 4, 3, 1] 12 | // Output: 0 13 | 14 | // In this case, no transaction is done, i.e. max profit = 0. 15 | 16 | public class BestTimeToBuyAndSellStock { 17 | public int maxProfit(int[] prices) { 18 | //Kadane's algorithm 19 | if(prices.length == 0) { 20 | return 0; 21 | } 22 | 23 | int max = 0; 24 | int min = prices[0]; 25 | 26 | for(int i = 1; i < prices.length; i++) { 27 | if(prices[i] > min) { 28 | max = Math.max(max, prices[i] - min); 29 | } else { 30 | min = prices[i]; 31 | } 32 | } 33 | 34 | return max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /company/facebook/DecodeWays.java: -------------------------------------------------------------------------------- 1 | // A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | // 'A' -> 1 4 | // 'B' -> 2 5 | // ... 6 | // 'Z' -> 26 7 | 8 | // Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | // For example, 11 | // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | // The number of ways decoding "12" is 2. 14 | 15 | public class DecodeWays { 16 | public int numDecodings(String s) { 17 | int n = s.length(); 18 | 19 | if(n == 0) { 20 | return 0; 21 | } 22 | 23 | int[] dp = new int[n + 1]; 24 | dp[n] = 1; 25 | dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; 26 | 27 | for(int i = n - 2; i >= 0; i--) { 28 | if(s.charAt(i) == '0') { 29 | continue; 30 | } else { 31 | dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; 32 | } 33 | } 34 | 35 | return dp[0]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /company/facebook/HammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class HammingDistance { 22 | public int hammingDistance(int x, int y) { 23 | return Integer.bitCount(x ^ y); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/facebook/InorderSuccessorInBST.java: -------------------------------------------------------------------------------- 1 | // Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 2 | 3 | // Note: If the given node has no in-order successor in the tree, return null. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class InorderSuccessorInBST { 15 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 16 | TreeNode successor = null; 17 | 18 | while(root != null) { 19 | if(p.val < root.val) { 20 | successor = root; 21 | root = root.left; 22 | } else { 23 | root = root.right; 24 | } 25 | } 26 | 27 | return successor; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /company/facebook/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | 13 | Arrays.sort(nums); 14 | 15 | return nums[length - k]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /company/facebook/LongestConsecutiveSequence.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 2 | 3 | // For example, 4 | // Given [100, 4, 200, 1, 3, 2], 5 | // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 6 | 7 | // Your algorithm should run in O(n) complexity. 8 | 9 | class LongestConsecutiveSequence { 10 | public int longestConsecutive(int[] nums) { 11 | if(nums == null || nums.length == 0) { 12 | return 0; 13 | } 14 | 15 | Set set = new HashSet(); 16 | for(int n: nums) { 17 | set.add(n); 18 | } 19 | 20 | int maxLength = 0; 21 | for(int n: set) { 22 | if(!set.contains(n - 1)) { 23 | int current = n; 24 | int currentMax = 1; 25 | 26 | while(set.contains(n + 1)) { 27 | currentMax++; 28 | n++; 29 | } 30 | 31 | maxLength = Math.max(maxLength, currentMax); 32 | } 33 | } 34 | 35 | return maxLength; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /company/facebook/MeetingRooms.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [[0, 30],[5, 10],[15, 20]], 5 | // return false. 6 | 7 | /** 8 | * Definition for an interval. 9 | * public class Interval { 10 | * int start; 11 | * int end; 12 | * Interval() { start = 0; end = 0; } 13 | * Interval(int s, int e) { start = s; end = e; } 14 | * } 15 | */ 16 | public class MeetingRooms { 17 | public boolean canAttendMeetings(Interval[] intervals) { 18 | if(intervals == null) { 19 | return false; 20 | } 21 | 22 | // Sort the intervals by start time 23 | Arrays.sort(intervals, new Comparator() { 24 | public int compare(Interval a, Interval b) { return a.start - b.start; } 25 | }); 26 | 27 | for(int i = 1; i < intervals.length; i++) { 28 | if(intervals[i].start < intervals[i - 1].end) { 29 | return false; 30 | } 31 | } 32 | 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /company/facebook/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | 3 | // Note: 4 | // 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. 5 | 6 | public class MergeSortedArray { 7 | public void merge(int[] A, int m, int[] B, int n) { 8 | int i = m - 1; 9 | int j = n - 1; 10 | int k = m + n - 1; 11 | 12 | while(i >= 0 && j >= 0) { 13 | A[k--] = A[i] > B[j] ? A[i--] : B[j--]; 14 | } 15 | 16 | while(j >= 0) { 17 | A[k--] = B[j--]; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /company/facebook/MinimumSizeSubarraySum.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given the array [2,3,1,2,4,3] and s = 7, 4 | // the subarray [4,3] has the minimal length under the problem constraint. 5 | 6 | public class MinimumSizeSubarraySum { 7 | public int minSubArrayLen(int s, int[] nums) { 8 | if(nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int i = 0; 13 | int j = 0; 14 | int result = Integer.MAX_VALUE; 15 | int total = 0; 16 | 17 | while(i < nums.length) { 18 | total += nums[i++]; 19 | 20 | while(total >= s) { 21 | result = Math.min(result, i - j); 22 | total -= nums[j++]; 23 | } 24 | } 25 | 26 | return result == Integer.MAX_VALUE ? 0 : result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/facebook/MoveZeros.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 4 | 5 | // Note: 6 | // You must do this in-place without making a copy of the array. 7 | // Minimize the total number of operations. 8 | 9 | public class MoveZeros { 10 | public void moveZeroes(int[] nums) { 11 | if(nums == null || nums.length == 0) { 12 | return; 13 | } 14 | 15 | int index = 0; 16 | for(int num : nums) { 17 | if(num != 0) { 18 | nums[index] = num; 19 | index++; 20 | } 21 | } 22 | 23 | while(index < nums.length) { 24 | nums[index] = 0; 25 | index++; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/facebook/PalindromeLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class PalindromeLinkedList { 10 | public boolean isPalindrome(ListNode head) { 11 | if(head == null || head.next == null) { 12 | return true; 13 | } 14 | 15 | Stack stack = new Stack(); 16 | 17 | ListNode fast = head; 18 | ListNode slow = head; 19 | 20 | while(fast != null && fast.next != null) { 21 | stack.push(slow.val); 22 | fast = fast.next.next; 23 | slow = slow.next; 24 | } 25 | 26 | if(fast != null) { 27 | slow = slow.next; 28 | } 29 | 30 | while(slow != null) { 31 | if(stack.pop() != slow.val) { 32 | return false; 33 | } 34 | 35 | slow = slow.next; 36 | } 37 | 38 | return true; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /company/facebook/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /company/facebook/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 2 | 3 | // Do not allocate extra space for another array, you must do this in place with constant memory. 4 | 5 | // For example, 6 | // Given input array nums = [1,1,2], 7 | 8 | // 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. 9 | 10 | public class RemoveDuplicatesFromSortedArray { 11 | public int removeDuplicates(int[] nums) { 12 | if(nums.length == 0 || nums == null) { 13 | return 0; 14 | } 15 | 16 | if(nums.length < 2) { 17 | return nums.length; 18 | } 19 | 20 | int index = 1; 21 | 22 | for(int i = 1; i < nums.length; i++) { 23 | if(nums[i] != nums[i - 1]) { 24 | nums[index++] = nums[i]; 25 | } 26 | } 27 | 28 | return index; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/facebook/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/facebook/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | // Given a roman numeral, convert it to an integer. 2 | 3 | // Input is guaranteed to be within the range from 1 to 3999 4 | 5 | public class RomanToInteger { 6 | public int romanToInt(String s) { 7 | HashMap map = new HashMap(); 8 | 9 | map.put('I', 1); 10 | map.put('V', 5); 11 | map.put('X', 10); 12 | map.put('L', 50); 13 | map.put('C', 100); 14 | map.put('D', 500); 15 | map.put('M', 1000); 16 | 17 | int total = 0; 18 | 19 | for(int i = 0; i < s.length() - 1; i++) { 20 | if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { 21 | total -= map.get(s.charAt(i)); 22 | } else { 23 | total += map.get(s.charAt(i)); 24 | } 25 | } 26 | 27 | total += map.get(s.charAt(s.length() - 1)); 28 | 29 | return total; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /company/facebook/SortColors.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 4 | 5 | // Note: 6 | // You are not suppose to use the library's sort function for this problem. 7 | 8 | public class SortColors { 9 | public void sortColors(int[] nums) { 10 | int wall = 0; 11 | 12 | for(int i = 0; i < nums.length; i++) { 13 | if(nums[i] < 1) { 14 | int temp = nums[i]; 15 | nums[i] = nums[wall]; 16 | nums[wall] = temp; 17 | wall++; 18 | } 19 | } 20 | 21 | for(int i = 0; i < nums.length; i++) { 22 | if(nums[i] == 1) { 23 | int temp = nums[i]; 24 | nums[i] = nums[wall]; 25 | nums[wall] = temp; 26 | wall++; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/facebook/SquareRootX.java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class SquareRootX { 6 | public int mySqrt(int x) { 7 | if(x == 0) { 8 | return 0; 9 | } 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | int mid = left + (right - left) / 2; 16 | 17 | if(mid == x / mid) { 18 | return mid; 19 | } else if(mid > x / mid) { 20 | right = mid - 1; 21 | } else if(mid < x / mid) { 22 | left = mid + 1; 23 | } 24 | } 25 | 26 | return right; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/facebook/Subsets.java: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets. 2 | 3 | // Note: The solution set must not contain duplicate subsets. 4 | 5 | // For example, 6 | // If nums = [1,2,3], a solution is: 7 | 8 | // [ 9 | // [3], 10 | // [1], 11 | // [2], 12 | // [1,2,3], 13 | // [1,3], 14 | // [2,3], 15 | // [1,2], 16 | // [] 17 | // ] 18 | 19 | public class Subsets { 20 | public List> subsets(int[] nums) { 21 | List> result = new ArrayList<>(); 22 | 23 | recurse(result, nums, new Stack<>(), 0); 24 | 25 | return result; 26 | } 27 | 28 | 29 | private void recurse(List> result, int[] nums, Stack path, int position) { 30 | if(position == nums.length) { 31 | result.add(new ArrayList<>(path)); 32 | 33 | return; 34 | } 35 | 36 | path.push(nums[position]); 37 | 38 | recurse(result, nums, path, position + 1); 39 | 40 | path.pop(); 41 | 42 | recurse(result, nums, path, position + 1); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /company/facebook/SumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | // Find the sum of all left leaves in a given binary tree. 2 | 3 | // Example: 4 | 5 | // 3 6 | // / \ 7 | // 9 20 8 | // / \ 9 | // 15 7 10 | 11 | // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 12 | 13 | /** 14 | * Definition for a binary tree node. 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | public class SumOfLeftLeaves { 23 | public int sumOfLeftLeaves(TreeNode root) { 24 | if(root == null) { 25 | return 0; 26 | } 27 | 28 | int total = 0; 29 | 30 | if(root.left != null) { 31 | if(root.left.left == null && root.left.right == null) { 32 | total += root.left.val; 33 | } else { 34 | total += sumOfLeftLeaves(root.left); 35 | } 36 | } 37 | 38 | total += sumOfLeftLeaves(root.right); 39 | 40 | return total; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /company/facebook/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | 22 | return result; 23 | } 24 | 25 | map.put(nums[i], i); 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/facebook/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | public class ValidPalindrome { 2 | public boolean isPalindrome(String s) { 3 | int left = 0; 4 | int right = s.length() - 1; 5 | 6 | while(left < right) { 7 | while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { 8 | left++; 9 | } 10 | 11 | while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { 12 | right--; 13 | } 14 | 15 | if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 16 | return false; 17 | } 18 | 19 | left++; 20 | right--; 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/facebook/WordBreak.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given 4 | // s = "leetcode", 5 | // dict = ["leet", "code"]. 6 | 7 | // Return true because "leetcode" can be segmented as "leet code". 8 | 9 | public class WordBreak { 10 | public boolean wordBreak(String s, Set wordDict) { 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | 13 | dp[0] = true; 14 | 15 | for(int i = 1; i <= s.length(); i++) { 16 | for(int j = 0; j < i; j++) { 17 | if(dp[j] && wordDict.contains(s.substring(j, i))) { 18 | dp[i] = true; 19 | break; 20 | } 21 | } 22 | } 23 | 24 | return dp[s.length()]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /company/google/ClosestBinarySearchTreeValue.java: -------------------------------------------------------------------------------- 1 | // Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 2 | 3 | // Note: 4 | // Given target value is a floating point. 5 | // You are guaranteed to have only one unique value in the BST that is closest to the target. 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class ClosestBinarySearchTreeValue { 17 | public int closestValue(TreeNode root, double target) { 18 | int value = root.val; 19 | TreeNode child = root.val < target ? root.right : root.left; 20 | 21 | if(child == null) { 22 | return value; 23 | } 24 | 25 | int childValue = closestValue(child, target); 26 | 27 | return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /company/google/DailyTemperatures.java: -------------------------------------------------------------------------------- 1 | //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 2 | // 3 | //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 4 | // 5 | //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 6 | 7 | class DailyTemperatures { 8 | public int[] dailyTemperatures(int[] temperatures) { 9 | int[] result = new int[temperatures.length]; 10 | Stack stack = new Stack(); 11 | for(int i = 0; i < temperatures.length; i++) { 12 | while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { 13 | int index = stack.pop(); 14 | result[index] = i - index; 15 | } 16 | stack.push(i); 17 | } 18 | 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /company/google/FindTheDifference.java: -------------------------------------------------------------------------------- 1 | // Given two strings s and t which consist of only lowercase letters. 2 | 3 | // String t is generated by random shuffling string s and then add one more letter at a random position. 4 | 5 | // Find the letter that was added in t. 6 | 7 | // Example: 8 | 9 | // Input: 10 | // s = "abcd" 11 | // t = "abcde" 12 | 13 | // Output: 14 | // e 15 | 16 | // Explanation: 17 | // 'e' is the letter that was added. 18 | 19 | public class FindTheDifference { 20 | public char findTheDifference(String s, String t) { 21 | int charCodeS = 0; 22 | int charCodeT = 0; 23 | 24 | for(int i = 0; i < s.length(); i++) { 25 | charCodeS += (int)(s.charAt(i)); 26 | } 27 | 28 | for(int i = 0; i < t.length(); i++) { 29 | charCodeT += (int)(t.charAt(i)); 30 | } 31 | 32 | return (char)(charCodeT - charCodeS); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/google/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/google/GeneralizedAbbreviation.java: -------------------------------------------------------------------------------- 1 | // Write a function to generate the generalized abbreviations of a word. 2 | 3 | // Example: 4 | // Given word = "word", return the following list (order does not matter): 5 | // ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 6 | 7 | public class GeneralizedAbbreviation { 8 | public List generateAbbreviations(String word) { 9 | List result = new ArrayList(); 10 | 11 | backtrack(result, word, 0, "", 0); 12 | 13 | return result; 14 | } 15 | 16 | void backtrack(List result, String word, int position, String current, int count) { 17 | if(position == word.length()) { 18 | if(count > 0) { 19 | current += count; 20 | } 21 | 22 | result.add(current); 23 | } else { 24 | backtrack(result, word, position + 1, current, count + 1); 25 | backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/google/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | // 3 | //For example, given n = 3, a solution set is: 4 | // 5 | //[ 6 | //"((()))", 7 | //"(()())", 8 | //"(())()", 9 | //"()(())", 10 | //"()()()" 11 | //] 12 | 13 | class GenerateParentheses { 14 | public List generateParenthesis(int n) { 15 | List result = new ArrayList(); 16 | generateParenthesisRecursive(result, "", 0, 0, n); 17 | 18 | return result; 19 | } 20 | 21 | public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { 22 | if(current.length() == n * 2) { 23 | result.add(current); 24 | return; 25 | } 26 | 27 | if(open < n) { 28 | generateParenthesisRecursive(result, current + "(", open + 1, close, n); 29 | } 30 | 31 | if(close < open) { 32 | generateParenthesisRecursive(result, current + ")", open, close + 1, n); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /company/google/JudgeRouteCircle.java: -------------------------------------------------------------------------------- 1 | //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 2 | // 3 | //The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 4 | // 5 | //Example 1: 6 | //Input: "UD" 7 | //Output: true 8 | //Example 2: 9 | //Input: "LL" 10 | //Output: false 11 | 12 | class JudgeRouteCircle { 13 | public boolean judgeCircle(String moves) { 14 | int UD = 0; 15 | int LR = 0; 16 | for(int i = 0; i < moves.length(); i++) { 17 | if(moves.charAt(i) == 'U') { 18 | UD++; 19 | } else if(moves.charAt(i) == 'D') { 20 | UD--; 21 | } else if(moves.charAt(i) == 'L') { 22 | LR++; 23 | } else if(moves.charAt(i) == 'R') { 24 | LR--; 25 | } 26 | } 27 | 28 | return UD == 0 && LR == 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/google/MissingRanges.java: -------------------------------------------------------------------------------- 1 | // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 2 | 3 | // For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. 4 | 5 | public class MissingRanges { 6 | public List findMissingRanges(int[] nums, int lower, int upper) { 7 | ArrayList result = new ArrayList(); 8 | 9 | for(int i = 0; i <= nums.length; i++) { 10 | long start = i == 0 ? lower : (long)nums[i - 1] + 1; 11 | long end = i == nums.length ? upper : (long)nums[i] - 1; 12 | 13 | addMissing(result, start, end); 14 | } 15 | 16 | return result; 17 | } 18 | 19 | void addMissing(ArrayList result, long start, long end) { 20 | if(start > end) { 21 | return; 22 | } else if(start == end) { 23 | result.add(start + ""); 24 | } else { 25 | result.add(start + "->" + end); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/google/MovingAverageFromDataStream.java: -------------------------------------------------------------------------------- 1 | // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 2 | 3 | // For example, 4 | // MovingAverage m = new MovingAverage(3); 5 | // m.next(1) = 1 6 | // m.next(10) = (1 + 10) / 2 7 | // m.next(3) = (1 + 10 + 3) / 3 8 | // m.next(5) = (10 + 3 + 5) / 3 9 | 10 | /** 11 | * Your MovingAverage object will be instantiated and called as such: 12 | * MovingAverage obj = new MovingAverage(size); 13 | * double param_1 = obj.next(val); 14 | */ 15 | 16 | public class MovingAverageFromDataStream { 17 | double previousSum = 0.0; 18 | int maxSize; 19 | Queue window; 20 | 21 | /** Initialize your data structure here. */ 22 | public MovingAverage(int size) { 23 | this.maxSize = size; 24 | window = new LinkedList(); 25 | } 26 | 27 | public double next(int val) { 28 | if(window.size() == maxSize) { 29 | previousSum -= window.remove(); 30 | } 31 | 32 | window.add(val); 33 | previousSum += val; 34 | 35 | return previousSum / window.size(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /company/google/PaintFence.java: -------------------------------------------------------------------------------- 1 | // There is a fence with n posts, each post can be painted with one of the k colors. 2 | 3 | // You have to paint all the posts such that no more than two adjacent fence posts have the same color. 4 | 5 | // Return the total number of ways you can paint the fence. 6 | 7 | // Note: 8 | // n and k are non-negative integers. 9 | 10 | public class PaintFence { 11 | public int numWays(int n, int k) { 12 | if(n <= 0) { 13 | return 0; 14 | } 15 | 16 | int sameColorCounts = 0; 17 | int differentColorCounts = k; 18 | 19 | for(int i = 2; i <= n; i++) { 20 | int temp = differentColorCounts; 21 | 22 | differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); 23 | 24 | sameColorCounts = temp; 25 | } 26 | 27 | return sameColorCounts + differentColorCounts; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /company/google/PlusOne.java: -------------------------------------------------------------------------------- 1 | //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 2 | // 3 | //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 4 | // 5 | //You may assume the integer does not contain any leading zero, except the number 0 itself. 6 | // 7 | //Example 1: 8 | // 9 | //Input: [1,2,3] 10 | //Output: [1,2,4] 11 | //Explanation: The array represents the integer 123. 12 | //Example 2: 13 | // 14 | //Input: [4,3,2,1] 15 | //Output: [4,3,2,2] 16 | //Explanation: The array represents the integer 4321. 17 | 18 | class Solution { 19 | public int[] plusOne(int[] digits) { 20 | for(int i = digits.length - 1; i >= 0; i--) { 21 | if(digits[i] < 9) { 22 | digits[i]++; 23 | return digits; 24 | } 25 | 26 | digits[i] = 0; 27 | } 28 | 29 | int[] result = new int[digits.length + 1]; 30 | result[0] = 1; 31 | 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/google/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/google/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /company/google/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | 3 | // Write a function to determine if a number is strobogrammatic. The number is represented as a string. 4 | 5 | // For example, the numbers "69", "88", and "818" are all strobogrammatic. 6 | 7 | public class StrobogrammaticNumber { 8 | public boolean isStrobogrammatic(String num) { 9 | for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { 10 | if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /company/google/SummaryRanges.java: -------------------------------------------------------------------------------- 1 | // Given a sorted integer array without duplicates, return the summary of its ranges. 2 | 3 | // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 4 | 5 | public class SummaryRanges { 6 | public List summaryRanges(int[] nums) { 7 | List result = new ArrayList(); 8 | 9 | if(nums.length == 1) { 10 | result.add(nums[0] + ""); 11 | 12 | return result; 13 | } 14 | 15 | for(int i = 0; i < nums.length; i++) { 16 | int current = nums[i]; 17 | 18 | while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) { 19 | i++; 20 | } 21 | 22 | if(current != nums[i]) { 23 | result.add(current + "->" + nums[i]); 24 | } else { 25 | result.add(current + ""); 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /company/google/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 5 | 6 | public class TrappingRainWater { 7 | public int trap(int[] height) { 8 | int water = 0; 9 | 10 | int leftIndex = 0; 11 | int rightIndex = height.length - 1; 12 | 13 | int leftMax = 0; 14 | int rightMax = 0; 15 | 16 | while(leftIndex <= rightIndex) { 17 | leftMax = Math.max(leftMax, height[leftIndex]); 18 | rightMax = Math.max(rightMax, height[rightIndex]); 19 | 20 | if(leftMax < rightMax) { 21 | water += leftMax - height[leftIndex]; 22 | leftIndex++; 23 | } else { 24 | water += rightMax - height[rightIndex]; 25 | rightIndex--; 26 | } 27 | } 28 | 29 | return water; 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /company/google/WiggleSort.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class WiggleSort { 6 | public void wiggleSort(int[] nums) { 7 | for(int i = 1; i < nums.length; i++) { 8 | int current = nums[i - 1]; 9 | 10 | if((i % 2 == 1) == (current > nums[i])) { 11 | nums[i - 1] = nums[i]; 12 | nums[i] = current; 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /company/google/WordBreak.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given 4 | // s = "leetcode", 5 | // dict = ["leet", "code"]. 6 | 7 | // Return true because "leetcode" can be segmented as "leet code". 8 | 9 | public class WordBreak { 10 | public boolean wordBreak(String s, Set wordDict) { 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | dp[0] = true; 13 | 14 | for(int i = 1; i <= s.length(); i++) { 15 | for(int j = 0; j < i; j++) { 16 | if(dp[j] && wordDict.contains(s.substring(j, i))) { 17 | dp[i] = true; 18 | break; 19 | } 20 | } 21 | } 22 | 23 | return dp[s.length()]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/linkedin/HouseRobber.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // 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. 4 | 5 | public class HouseRobber { 6 | public int rob(int[] nums) { 7 | if(nums.length == 0) { 8 | return 0; 9 | } 10 | 11 | if(nums.length == 1) { 12 | return nums[0]; 13 | } 14 | 15 | int[] dp = new int[nums.length]; 16 | 17 | dp[0] = nums[0]; 18 | dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; 19 | 20 | for(int i = 2; i < nums.length; i++) { 21 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 22 | } 23 | 24 | return dp[dp.length - 1]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /company/linkedin/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /company/linkedin/MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest product. 2 | 3 | // For example, given the array [2,3,-2,4], 4 | // the contiguous subarray [2,3] has the largest product = 6. 5 | 6 | public class MaximumProductSubarray { 7 | public int maxProduct(int[] nums) { 8 | if(nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int result = nums[0]; 13 | int max = nums[0]; 14 | int min = nums[0]; 15 | 16 | for(int i = 1; i < nums.length; i++) { 17 | int temp = max; 18 | 19 | max = Math.max(Math.max(nums[i] * max, nums[i] * min), nums[i]); 20 | min = Math.min(Math.min(nums[i] * temp, nums[i] * min), nums[i]); 21 | 22 | if(max > result) { 23 | result = max; 24 | } 25 | } 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /company/linkedin/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 2 | 3 | // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 4 | // the contiguous subarray [4,-1,2,1] has the largest sum = 6. 5 | 6 | public class MaximumSubarray { 7 | public int maxSubArray(int[] nums) { 8 | int[] dp = new int[nums.length]; 9 | 10 | dp[0] = nums[0]; 11 | 12 | int max = dp[0]; 13 | 14 | for(int i = 1; i < nums.length; i++) { 15 | dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 16 | max = Math.max(dp[i], max); 17 | } 18 | 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /company/linkedin/Permutations.java: -------------------------------------------------------------------------------- 1 | //Given a collection of distinct numbers, return all possible permutations. 2 | // 3 | //For example, 4 | //[1,2,3] have the following permutations: 5 | //[ 6 | //[1,2,3], 7 | //[1,3,2], 8 | //[2,1,3], 9 | //[2,3,1], 10 | //[3,1,2], 11 | //[3,2,1] 12 | //] 13 | 14 | class Permutations { 15 | public List> permute(int[] nums) { 16 | LinkedList> result = new LinkedList>(); 17 | result.add(new ArrayList()); 18 | for (int n: nums) { 19 | int size = result.size(); 20 | while(size > 0) { 21 | List current = result.pollFirst(); 22 | for (int i = 0; i <= current.size(); i++) { 23 | List temp = new ArrayList(current); 24 | temp.add(i, n); 25 | result.add(temp); 26 | } 27 | size--; 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /company/linkedin/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /company/linkedin/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | 22 | return result; 23 | } 24 | 25 | map.put(nums[i], i); 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /company/microsoft/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /company/microsoft/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /company/microsoft/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /company/microsoft/Permutations.java: -------------------------------------------------------------------------------- 1 | //Given a collection of distinct numbers, return all possible permutations. 2 | // 3 | //For example, 4 | //[1,2,3] have the following permutations: 5 | //[ 6 | //[1,2,3], 7 | //[1,3,2], 8 | //[2,1,3], 9 | //[2,3,1], 10 | //[3,1,2], 11 | //[3,2,1] 12 | //] 13 | 14 | class Permutations { 15 | public List> permute(int[] nums) { 16 | LinkedList> result = new LinkedList>(); 17 | result.add(new ArrayList()); 18 | for (int n: nums) { 19 | int size = result.size(); 20 | while(size > 0) { 21 | List current = result.pollFirst(); 22 | for (int i = 0; i <= current.size(); i++) { 23 | List temp = new ArrayList(current); 24 | temp.add(i, n); 25 | result.add(temp); 26 | } 27 | size--; 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /company/microsoft/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /company/palantir/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /company/palantir/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /company/snapchat/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /company/twitter/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/twitter/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 5 | 6 | public class TrappingRainWater { 7 | public int trap(int[] height) { 8 | int water = 0; 9 | 10 | int leftIndex = 0; 11 | int rightIndex = height.length - 1; 12 | 13 | int leftMax = 0; 14 | int rightMax = 0; 15 | 16 | while(leftIndex <= rightIndex) { 17 | leftMax = Math.max(leftMax, height[leftIndex]); 18 | rightMax = Math.max(rightMax, height[rightIndex]); 19 | 20 | if(leftMax < rightMax) { 21 | water += leftMax - height[leftIndex]; 22 | leftIndex++; 23 | } else { 24 | water += rightMax - height[rightIndex]; 25 | rightIndex--; 26 | } 27 | } 28 | 29 | return water; 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /company/uber/BestTimeToBuyOrSellStock.java: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | 3 | // 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. 4 | 5 | // Example 1: 6 | // Input: [7, 1, 5, 3, 6, 4] 7 | // Output: 5 8 | 9 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 10 | // Example 2: 11 | // Input: [7, 6, 4, 3, 1] 12 | // Output: 0 13 | 14 | // In this case, no transaction is done, i.e. max profit = 0. 15 | 16 | public class BestTimeToBuyAndSellStock { 17 | public int maxProfit(int[] prices) { 18 | //Kadane's algorithm 19 | if(prices.length == 0) { 20 | return 0; 21 | } 22 | 23 | int max = 0; 24 | int min = prices[0]; 25 | 26 | for(int i = 1; i < prices.length; i++) { 27 | if(prices[i] > min) { 28 | max = Math.max(max, prices[i] - min); 29 | } else { 30 | min = prices[i]; 31 | } 32 | } 33 | 34 | return max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /company/uber/DecodeWays.java: -------------------------------------------------------------------------------- 1 | // A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | // 'A' -> 1 4 | // 'B' -> 2 5 | // ... 6 | // 'Z' -> 26 7 | 8 | // Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | // For example, 11 | // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | // The number of ways decoding "12" is 2. 14 | 15 | public class DecodeWays { 16 | public int numDecodings(String s) { 17 | int n = s.length(); 18 | 19 | if(n == 0) { 20 | return 0; 21 | } 22 | 23 | int[] dp = new int[n + 1]; 24 | dp[n] = 1; 25 | dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; 26 | 27 | for(int i = n - 2; i >= 0; i--) { 28 | if(s.charAt(i) == '0') { 29 | continue; 30 | } else { 31 | dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; 32 | } 33 | } 34 | 35 | return dp[0]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /company/uber/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | class GenerateParentheses { 2 | public List generateParenthesis(int n) { 3 | List result = new ArrayList(); 4 | generateParenthesisRecursive(result, "", 0, 0, n); 5 | 6 | return result; 7 | } 8 | 9 | public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { 10 | if(current.length() == n * 2) { 11 | result.add(current); 12 | return; 13 | } 14 | 15 | if(open < n) { 16 | generateParenthesisRecursive(result, current + "(", open + 1, close, n); 17 | } 18 | 19 | if(close < open) { 20 | generateParenthesisRecursive(result, current + ")", open, close + 1, n); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /company/uber/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /company/uber/PalindromePermutation.java: -------------------------------------------------------------------------------- 1 | public class PalindromePermutation { 2 | public boolean canPermutePalindrome(String s) { 3 | char[] characters = new char[256]; 4 | 5 | for(int i = 0; i < s.length(); i++) { 6 | characters[s.charAt(i)]++; 7 | } 8 | 9 | int oddCount = 0; 10 | 11 | for(int i = 0; i < characters.length; i++) { 12 | if(!(characters[i] % 2 == 0)) { 13 | oddCount++; 14 | if(oddCount > 1) { 15 | return false; 16 | } 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /company/uber/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /company/uber/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | // Given a roman numeral, convert it to an integer. 2 | 3 | // Input is guaranteed to be within the range from 1 to 3999 4 | 5 | public class RomanToInteger { 6 | public int romanToInt(String s) { 7 | HashMap map = new HashMap(); 8 | 9 | map.put('I', 1); 10 | map.put('V', 5); 11 | map.put('X', 10); 12 | map.put('L', 50); 13 | map.put('C', 100); 14 | map.put('D', 500); 15 | map.put('M', 1000); 16 | 17 | int total = 0; 18 | 19 | for(int i = 0; i < s.length() - 1; i++) { 20 | if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { 21 | total -= map.get(s.charAt(i)); 22 | } else { 23 | total += map.get(s.charAt(i)); 24 | } 25 | } 26 | 27 | total += map.get(s.charAt(s.length() - 1)); 28 | 29 | return total; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /company/uber/Subsets.java: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets. 2 | 3 | // Note: The solution set must not contain duplicate subsets. 4 | 5 | // For example, 6 | // If nums = [1,2,3], a solution is: 7 | 8 | // [ 9 | // [3], 10 | // [1], 11 | // [2], 12 | // [1,2,3], 13 | // [1,3], 14 | // [2,3], 15 | // [1,2], 16 | // [] 17 | // ] 18 | 19 | public class Subsets { 20 | public List> subsets(int[] nums) { 21 | List> result = new ArrayList<>(); 22 | 23 | recurse(result, nums, new Stack<>(), 0); 24 | 25 | return result; 26 | } 27 | 28 | 29 | private void recurse(List> result, int[] nums, Stack path, int position) { 30 | if(position == nums.length) { 31 | result.add(new ArrayList<>(path)); 32 | return; 33 | } 34 | 35 | path.push(nums[position]); 36 | 37 | recurse(result, nums, path, position + 1); 38 | 39 | path.pop(); 40 | 41 | recurse(result, nums, path, position + 1); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /company/uber/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | return result; 22 | } 23 | 24 | map.put(nums[i], i); 25 | } 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /company/uber/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | public class ValidPalindrome { 2 | public boolean isPalindrome(String s) { 3 | int left = 0; 4 | int right = s.length() - 1; 5 | 6 | while(left < right) { 7 | while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { 8 | left++; 9 | } 10 | 11 | while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { 12 | right--; 13 | } 14 | 15 | if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 16 | return false; 17 | } 18 | 19 | left++; 20 | right--; 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/uber/WordBreak.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given 4 | // s = "leetcode", 5 | // dict = ["leet", "code"]. 6 | 7 | // Return true because "leetcode" can be segmented as "leet code". 8 | 9 | public class WordBreak { 10 | public boolean wordBreak(String s, Set wordDict) { 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | dp[0] = true; 13 | 14 | for(int i = 1; i <= s.length(); i++) { 15 | for(int j = 0; j < i; j++) { 16 | if(dp[j] && wordDict.contains(s.substring(j, i))) { 17 | dp[i] = true; 18 | break; 19 | } 20 | } 21 | } 22 | 23 | return dp[s.length()]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /company/yahoo/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /company/yahoo/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /company/yelp/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /cracking-the-coding-interview/CrackingTheCodingInterview.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-five-bit-manipulation/BinaryRepresentation.java: -------------------------------------------------------------------------------- 1 | /* given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print 2 | * the binary representation. If the number cannot be represented accurately in binary 3 | * with at most 32 characters, print "ERROR" */ 4 | 5 | public class BinaryRepresentation { 6 | public static String printBinary(double num) { 7 | if(num >= 1 || num <= 0) { 8 | return "ERROR"; 9 | } 10 | 11 | StrinBuilder binary = new StringBuilder(); 12 | binary.append("."); 13 | while(num > 0) { 14 | /* setting a limit on length: 32 characters */ 15 | if(binary.length() >= 32) { 16 | return "ERROR"; 17 | } 18 | 19 | double r = num * 2; 20 | if(r >= 1) { 21 | binary.append(1); 22 | num = r - 1; 23 | } 24 | else { 25 | binary.append(0); 26 | num = r; 27 | } 28 | } 29 | return binary.toString(); 30 | } 31 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-five-bit-manipulation/SwapBits.java: -------------------------------------------------------------------------------- 1 | /* write a program to swap odd and even bits in an integer with as few instructions as 2 | * possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) */ 3 | 4 | public class SwapBits { 5 | public int swapOddEvenBits(int x) { 6 | return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) ); 7 | } 8 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-four-trees-and-graphs/BinaryTreeIsBalanced.java: -------------------------------------------------------------------------------- 1 | /* implement a function to check if a binary tree is balanced. For the purpose of this 2 | * question, a balanced tree is defined to be a tree such that the heights of the two 3 | * subtrees of any node never differ by more than one */ 4 | 5 | public class BinaryTreeIsBalanaced { 6 | public static int getHeight(TreeNode root) { 7 | if(root == null) { 8 | return 0; //base case 9 | } 10 | return Math.max(getHeight(root.left), getHeight(root.right)) + 1; 11 | } 12 | 13 | public static boolean isBalanced(TreeNode root) { 14 | if(root == null) { //base case 15 | return true; 16 | } 17 | 18 | int heightDiff = getHeight(root.left) - getHeight(root.right); 19 | if(Math.abs(heightDiff) > 1) { 20 | return false; 21 | } 22 | else { //recurse 23 | return isBalanced(root.left) && isBalanced(root.right); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* given a sorted (increasing order) array with unique integer elements, write an algorithm 2 | * to create a binary search tree with minimal height */ 3 | 4 | public class CreateBinarySearchTree { 5 | TreeNode createMinimalBST(int arr[], int start, int end) { 6 | if(end < start) { 7 | return null; 8 | } 9 | int mid = (start + end) / 2; 10 | TreeNode n = new TreeNode(arr[mid]); 11 | n.left = createMinimalBST(arr, start, mid - 1); 12 | n.right = createMinimalBST(arr, mid + 1, end); 13 | return n; 14 | } 15 | 16 | TreeNode createMinimalBST(int array[]) { 17 | return createMinimalBST(array, 0, array.length - 1); 18 | } 19 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateLinkedListForEachLevel.java: -------------------------------------------------------------------------------- 1 | /* given a binary tree, design an algorithm which creates a linked list of all the nodes 2 | * at each depth (e.g., if you have a tree with depth D, you'll have D linked lists) */ 3 | 4 | public class CreateLinkedListForEachLevel { 5 | ArrayList> createLinkedList(TreeNode root) { 6 | ArrayList> result = new ArrayList>(); 7 | /* "visit" the root */ 8 | LinkedList current = new LinkedList(); 9 | if(root != null) { 10 | current.add(root); 11 | } 12 | 13 | while(current.size() > 0) { 14 | result.add(current); //add previous level 15 | LinkedList parents = current; //go to next level 16 | current = new LinkedList(); 17 | for(TreeNode parent : parents) { 18 | /* visit the children */ 19 | if(parent.left != null) { 20 | current.add(parrent.left); 21 | } 22 | if(parent.right != null) { 23 | current.add(parent.right); 24 | } 25 | } 26 | } 27 | return result; 28 | } 29 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-four-trees-and-graphs/FindPath.java: -------------------------------------------------------------------------------- 1 | /* give a directed graph, design an algorithm to find out whether there is a route between two nodes */ 2 | 3 | public class FindPath { 4 | public enum State { 5 | Unvisited, Visited, Visiting; 6 | } 7 | 8 | public static boolean search(Graph g, Node start, Node end) { 9 | if(start == end) return true; 10 | 11 | //operates as Queue 12 | LinkedList q = new LinkedList(); 13 | 14 | for(Node u : g.getNodes()) { 15 | u.state = State.Unvisited; 16 | } 17 | 18 | start.state = State.Visiting; 19 | q.add(start); 20 | Node u; 21 | while(!q.isEmpty()) { 22 | u = q.removeFirst(); //i.e., dequeue() 23 | if(u != null) { 24 | for(Node v : u.getAdjacent()) { 25 | if(v.state == State.Unvisited) { 26 | if(v == end) { 27 | return true; 28 | } 29 | else { 30 | v.state = State.Visiting; 31 | q.add(v); 32 | } 33 | } 34 | } 35 | } 36 | u.state = State.Visited; 37 | } 38 | return false; 39 | } 40 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-four-trees-and-graphs/ValidBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* implement a function to check if a binary tree is a binary search tree */ 2 | 3 | public class ValidBinarySearchTree { 4 | boolean checkBST(TreeNode n) { 5 | return checkBST(n, null, null); 6 | } 7 | 8 | boolean checkBST(TreeNode n, Integer min, Integer max) { 9 | if(n == null) { 10 | return true; 11 | } 12 | if((min != null && n.data <= min) || (max != null && n.data > max)) { 13 | return false; 14 | } 15 | 16 | if(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)) { 17 | return false; 18 | } 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllPermutations.java: -------------------------------------------------------------------------------- 1 | /* write a method to compute all permutations of a string of unique characters */ 2 | 3 | public class AllPermutations { 4 | public static ArrayList getPerms(String str) { 5 | if(str == null) { 6 | return null; 7 | } 8 | ArrayList permutations = new ArrayList(); 9 | if(str.length() == 0) { //base case 10 | permutations.add(""); 11 | return permutations; 12 | } 13 | 14 | char first = str.charAt(0); //get the first character 15 | String remainder = str.substring(1); //remove the 1st character 16 | ArrayList words = getPerms(remainder); 17 | for(String word : words) { 18 | for(int j = 0; j <= word.length(); j++) { 19 | String s = insertCharAt(word, first, j); 20 | permutations.add(s); 21 | } 22 | } 23 | return permutations; 24 | } 25 | 26 | public static String insertCharAt(String word, char c, int i) { 27 | String start = word.substring(0, i); 28 | String end = word.substring(i); 29 | return start + c + end; 30 | } 31 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllSubsets.java: -------------------------------------------------------------------------------- 1 | /* write a method to return all subsets of a set */ 2 | 3 | public class AllSubsets { 4 | ArrayList> getSubsets(ArrayList set, int index) { 5 | ArrayList> allsubsets; 6 | if(set.size() == index) { //base case - add empty set 7 | allsubsets = new ArrayList>(); 8 | allsubsets.add(new ArrayList()); //empty set 9 | } 10 | else { 11 | allsubsets = getSubsets(set, index + 1); 12 | int item = set.get(index); 13 | ArrayList> moresubsets = new ArrayList>(); 14 | for(ArrayList subset : allsubsets) { 15 | ArrayList newsubset = new ArrayList(); 16 | newsubset.addAll(subset); 17 | newsubset.add(item); 18 | moresubsets.add(newsubset); 19 | } 20 | allsubsets.addAll(moresubsets); 21 | } 22 | return allsubsets; 23 | } 24 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/MagicIndex.java: -------------------------------------------------------------------------------- 1 | /* a magic index is an array A[1...n - 1] is defined to be an index such that A[i] = i. Given a sorted 2 | * array of distinct integers, write a method to find a magic index, if one exists, in array A */ 3 | 4 | public class MagicIndex { 5 | public static int magicFast(int[] array, int start, int end) { 6 | if(end < start || start < 0 || end >= array.length) { 7 | return -1; 8 | } 9 | int mid = (start + end) / 2; 10 | if(array[mid] == mid) { 11 | return mid; 12 | } 13 | else if(array[mid] > mid) { 14 | return magicFast(array, start, mid - 1); 15 | } 16 | else { 17 | return magicFast(array, mid + 1, end); 18 | } 19 | } 20 | 21 | public static int magicFast(int[] array) { 22 | return magicFast(array, 0, array.length - 1); 23 | } 24 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/RepresentingNCents.java: -------------------------------------------------------------------------------- 1 | /* given an infinite number of quars (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), 2 | * write code to calculate the number of ways of representing n cents */ 3 | 4 | public class RepresentingNCents { 5 | int makeChange(int n) { 6 | int[] denoms = {25, 10, 5, 1}; 7 | int[][] map = new int[n + 1][denoms.length]; //precomputed vals 8 | return makeChange(n, denoms, 0, map); 9 | } 10 | 11 | int makeChange(int amount, int[] denoms, int index, int[][] map) { 12 | if(map[amount][index] > 0) { //retrieve value 13 | return map[amount][index]; 14 | } 15 | if(index >= denoms.length - 1) return 1; //one denom remaining 16 | int denomAmount = denoms[index]; 17 | int ways = 0; 18 | for(int i = 0; i * denomAmount <= amount; i++) { 19 | //go to next denom, assuming i coints of denomAmount 20 | int amountRemaining = amount - i * denomAmount; 21 | ways += makeChange(amountRemaining, denoms, index + 1, map); 22 | } 23 | map[amount][index] = ways; 24 | return ways; 25 | } 26 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/Staircase.java: -------------------------------------------------------------------------------- 1 | /* a child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps 2 | * at a time. Implement a method to count how many possible ways the child can run up the stairs */ 3 | 4 | public class Staircase { 5 | public static int countWaysDP(int n, int[] map) { 6 | if(n < 0) { 7 | return 0; 8 | } 9 | else if(n == 0) { 10 | return 1; 11 | } 12 | else if(map[n] > -1) { 13 | return map[n]; 14 | } 15 | else { 16 | map[n] = countWaysDP(n - 1, map) + 17 | countWaysDP(n - 2, map) + 18 | countWaysDP(n - 3, map); 19 | return map[n]; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java: -------------------------------------------------------------------------------- 1 | //Write code to remove duplicates from an unsorted linked list 2 | 3 | public class RemoveDups { 4 | void deleteDups(LinkedListNode n) { 5 | HashSet set = new HashSet(); 6 | LinkedListNode previous = null; 7 | while(n != null) { 8 | if(set.contains(n.data)) { 9 | previous.next = n.next; 10 | } 11 | else { 12 | set.add(n.data); 13 | previous = n; 14 | } 15 | n = n.next; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/IsRotation.java: -------------------------------------------------------------------------------- 1 | // Assume you have a method isSubstring which checks if one word is a isSubstring of another. 2 | // Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only 3 | // one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat"). 4 | 5 | public class IsRotation { 6 | public boolean isRotation(String s1, String s2) { 7 | int len = s1.length(); 8 | /*check that s1 and s2 are equal length and not empty */ 9 | if(len == s2.length() && len > 0) { 10 | /* concatenate s1 and s1 within new buffer */ 11 | String s1s1 = s1 + s1; 12 | return isSubstring(s1s1, s2); 13 | } 14 | 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/IsUniqueChars.java: -------------------------------------------------------------------------------- 1 | //Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? 2 | 3 | public class IsUniqueChars { 4 | public boolean isUniqueChars(String str) { 5 | int checker = 0; 6 | for(int i = 0; i < str.length(); i++) { 7 | int val = str.charAt(i) - 'a'; 8 | if((checker & (1 << val)) > 0) { 9 | return false; 10 | } 11 | checker |= (1 << val); 12 | } 13 | return true; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/NthToLast.java: -------------------------------------------------------------------------------- 1 | //Implement an algorithm to find the kth to last element of a single linked list 2 | 3 | public class NthToLast { 4 | LinkedListNode nthToLast(LinkedListNode head, int k) { 5 | if(k <= 0) return null; 6 | 7 | LinkedListNode p1 = head; 8 | LinkedListNode p2 = head; 9 | 10 | //move p2 forward k nodes into the list 11 | for(int i = 0; i < k - 1; i++) { 12 | if(p2 == null) return null; //error check 13 | p2 = p2.next; 14 | } 15 | 16 | if(p2 == null) return null; 17 | 18 | /* now, move p1 and p2 at the same speed. When p2 hits the end, 19 | * p1 will be at the right element */ 20 | while(p2.next != null) { 21 | p1 = p1.next; 22 | p2 = p2.next; 23 | } 24 | 25 | return p1; 26 | } 27 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/Permutation.java: -------------------------------------------------------------------------------- 1 | // Given two strings, write a method to decide if one is a permutation of the other 2 | 3 | public class Permutation { 4 | public boolean permutation(String s, String t) { 5 | if(s.length() != t.length()) { 6 | return false; 7 | } 8 | 9 | int[] letters = new int[256]; 10 | 11 | char[] s_array = s.toCharArray(); 12 | for(char c : s_array) { 13 | letters[c]++; 14 | } 15 | 16 | for(int i = 0; i < t.length(); i++) { 17 | int c = (int)t.charAt(i); 18 | if(--letters[c] < 0) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java: -------------------------------------------------------------------------------- 1 | // Write a method to replace all spaces in a string with '%20.' You may assume that the string 2 | // has sufficient space at the end of the string to hold the additional characters, and that you 3 | // are given the "true" length of the string. (Note: if implementing in Java, please use a characters 4 | // array so that you can perform this operation in place) 5 | 6 | public class ReplaceSpaces { 7 | public void replaceSpaces(char[] str, int length) { 8 | int spaceCount = 0, newLength; 9 | for(int i = 0; i < length; i++) { 10 | if(str[i] == ' ') { 11 | spaceCount++; 12 | } 13 | } 14 | 15 | newLength = length + spaceCount * 2; 16 | str[newLength] = '\0'; 17 | for(int i = length - 1; i >= 0; i--) { 18 | if(str[i] == ' ') { 19 | str[newLength - 1] = '0'; 20 | str[newLength - 2] = '2'; 21 | str[newLength - 3] = '%'; 22 | newLength = newLength - 3; 23 | } 24 | else { 25 | str[newLength - 1] = str[i]; 26 | newLength = newLength - 1; 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-seven-mathematics-and-probability/WouldIntersect.java: -------------------------------------------------------------------------------- 1 | /* give two lines on a Cartesian plane, determine whether the two lines would intersect */ 2 | 3 | public class WouldIntersect { 4 | //placeholder for class name 5 | } 6 | 7 | class Line { 8 | static double epsilon = 0.000001; 9 | public double slope; 10 | public double yintercept; 11 | 12 | public Line(double s, double y) { 13 | this.slope = s; 14 | this.yintercept = y; 15 | } 16 | 17 | public boolean Intersect(Line line2) { 18 | return Math.abs(this.slope - line2.slope) > epsilon || Math.abs(this.yintercept - line2.yintercept) < epsilon; 19 | } 20 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/BinaryTreeIsBalanced.java: -------------------------------------------------------------------------------- 1 | /* implement a function to check if a binary tree is balanced. For the purpose of this 2 | * question, a balanced tree is defined to be a tree such that the heights of the two 3 | * subtrees of any node never differ by more than one */ 4 | 5 | public class BinaryTreeIsBalanaced { 6 | public static int getHeight(TreeNode root) { 7 | if(root == null) { 8 | return 0; //base case 9 | } 10 | return Math.max(getHeight(root.left), getHeight(root.right)) + 1; 11 | } 12 | 13 | public static boolean isBalanced(TreeNode root) { 14 | if(root == null) { //base case 15 | return true; 16 | } 17 | 18 | int heightDiff = getHeight(root.left) - getHeight(root.right); 19 | if(Math.abs(heightDiff) > 1) { 20 | return false; 21 | } 22 | else { //recurse 23 | return isBalanced(root.left) && isBalanced(root.right); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQUeue.java: -------------------------------------------------------------------------------- 1 | /* implement a MyQueue class which implements a queue using two stacks */ 2 | 3 | public class MyQueue { 4 | Stack stackNewest, stackOldest; 5 | 6 | public MyQueue() { 7 | stackNewest = new Stack(); 8 | stackOldest = new Stack(); 9 | } 10 | 11 | public int size() { 12 | return stackNewest.size() + stackOldest.size(); 13 | } 14 | 15 | public void add(T value) { 16 | /* push onto stackNewest, which always has the newest 17 | * elements on top */ 18 | stackNewest.push(value); 19 | } 20 | 21 | /* Move elements from stackNewest into stackOldest. This 22 | * is usually done so that we can do operations on stackOldest */ 23 | private void shiftStacks() { 24 | if(stackOldest.isEmpty()) { 25 | while(!stackNewest.isEmpty()) { 26 | stackOldest.push(stackNewest.pop()); 27 | } 28 | } 29 | } 30 | 31 | public T peek() { 32 | shiftStacks(); //ensure stackOldest has the current elements 33 | return stackOldest.peek(); //retrieve the oldest item 34 | } 35 | 36 | public T remove() { 37 | shiftStacks(); //ensure stackOldest has the current elements 38 | return stackOldest.pop(); 39 | } 40 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQueue.java: -------------------------------------------------------------------------------- 1 | /* implement a MyQueue class which implements a queue using two stacks */ 2 | 3 | public class MyQueue { 4 | Stack stackNewest, stackOldest; 5 | 6 | public MyQueue() { 7 | stackNewest = new Stack(); 8 | stackOldest = new Stack(); 9 | } 10 | 11 | public int size() { 12 | return stackNewest.size() + stackOldest.size(); 13 | } 14 | 15 | public void add(T value) { 16 | /* push onto stackNewest, which always has the newest 17 | * elements on top */ 18 | stackNewest.push(value); 19 | } 20 | 21 | /* Move elements from stackNewest into stackOldest. This 22 | * is usually done so that we can do operations on stackOldest */ 23 | private void shiftStacks() { 24 | if(stackOldest.isEmpty()) { 25 | while(!stackNewest.isEmpty()) { 26 | stackOldest.push(stackNewest.pop()); 27 | } 28 | } 29 | } 30 | 31 | public T peek() { 32 | shiftStacks(); //ensure stackOldest has the current elements 33 | return stackOldest.peek(); //retrieve the oldest item 34 | } 35 | 36 | public T remove() { 37 | shiftStacks(); //ensure stackOldest has the current elements 38 | return stackOldest.pop(); 39 | } 40 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java: -------------------------------------------------------------------------------- 1 | /* implement a MyQueue class which implements a queue using two stacks */ 2 | 3 | public class QueueUsingTwoStacks { 4 | 5 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/SortStack.java: -------------------------------------------------------------------------------- 1 | /* write a program to sort a stack in ascending order (with biggest items on top). 2 | * you may use at most one additional stack to hold items, but you may not copy the 3 | * elements into any other data strcuture (such as an array). The stack supports the 4 | * folowing operations: push, pop, peek, and isEmpty */ 5 | 6 | public class SortStack { 7 | public static Stack sort(Stack s) { 8 | Stack r = new Stack(); 9 | while(!s.isEmpty()) { 10 | int tmp = s.pop(); //step 1 11 | while(!r.isEmpty() && r.peek() > tmp) { //step 2 12 | s.push(r.pop()); 13 | } 14 | r.push(tmp); //step 3 15 | } 16 | return r; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-three-stacks-and-queues/StackWithMin.java: -------------------------------------------------------------------------------- 1 | //How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop, and min should all operate in O(1) time 2 | 3 | public class StackWithMin extends Stack { 4 | public void push(int value) { 5 | int newMin = Math.min(value, min()); 6 | super.push(new NodeWithMin(value, newMin)); 7 | } 8 | 9 | public int min() { 10 | if(this.isEmpty()) { 11 | return Integer.MAX_VALUE; //error value 12 | } 13 | else { 14 | return peek().min; 15 | } 16 | } 17 | } 18 | 19 | class NodeWithMin { 20 | public int value; 21 | public int min; 22 | public NodeWithMin(int v, int min) { 23 | this.value = v; 24 | this.min = min; 25 | } 26 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/DeleteDups.java: -------------------------------------------------------------------------------- 1 | //Write code to remove duplicates from an unsorted linked list 2 | 3 | public class RemoveDups { 4 | void deleteDups(LinkedListNode n) { 5 | HashSet set = new HashSet(); 6 | LinkedListNode previous = null; 7 | while(n != null) { 8 | if(set.contains(n.data)) { 9 | previous.next = n.next; 10 | } 11 | else { 12 | set.add(n.data); 13 | previous = n; 14 | } 15 | n = n.next; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/DeleteNode.java: -------------------------------------------------------------------------------- 1 | //Implement an algorithm to delete a node in the middle of a singly linked list, give only access to that node 2 | 3 | public class DeleteNode { 4 | public static boolean deleteNode(LinkedListNode n) { 5 | if(n == null || n.next == null) { 6 | return false; 7 | } 8 | 9 | LinkedListNode next = n.next; 10 | n.data = next.data; 11 | n.next = next.next; 12 | return true; 13 | } 14 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/FindBeginning.java: -------------------------------------------------------------------------------- 1 | //Given a circular linked list, implement an algorithm which returns 2 | //the node at the beginning of the loop 3 | 4 | public class FindBeginning { 5 | LinkedListNode findBeginning(LinkedListNode head) { 6 | LinkedListNode slow = head; 7 | LinkedListNode fast = head; 8 | 9 | /* find meeting point. This will be LOOP_SIZE - k 10 | * steps int othe linked list */ 11 | while(fast != null && fast.next != null) { 12 | slow = slow.next; 13 | fast = fast.next.next; 14 | if(fast == slow) { 15 | break; 16 | } 17 | } 18 | 19 | /* error checking - no meeting point, and therefore no loop */ 20 | if(fast == null || fast.next == null) { 21 | return null; 22 | } 23 | 24 | /* move slow to head. Keep fast at meeting point. Each are k 25 | * steps from the loop start. If they move at the same pace, 26 | * they must meet at the loop start */ 27 | slow = head; 28 | while(slow != fast) { 29 | slow = slow.next; 30 | fast = fast.next; 31 | } 32 | 33 | /* both now point to the start of the loop */ 34 | return fast; 35 | } 36 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/IsPalindrome.java: -------------------------------------------------------------------------------- 1 | //Implement a function to check if a linked list is a palindrome 2 | //don't forget import statements! 3 | 4 | public class IsPalindrome { 5 | boolean isPalindrome(LinkedListNode head) { 6 | LinkedListNode fast = head; 7 | LinkedListNode slow = head; 8 | 9 | Stack stack = new Stack(); 10 | 11 | /* push elements from first half of linked list onto stack. 12 | * When fast runner (which is moving at 2x speed) reaches the 13 | * end of the linked list, then we know we're at the middle */ 14 | while(fast != null && fast.next != null) { 15 | stack.push(slow.data); 16 | slow = slow.next; 17 | fast = fast.next.next; 18 | } 19 | 20 | /*has odd number of elements, so skip the middle element */ 21 | if(fast != null) { 22 | slow = slow.next; 23 | } 24 | 25 | while(slow != null) { 26 | int top = stack.pop().intValue(); 27 | 28 | /* if values are different, then it's not a palindrome */ 29 | if(top != slow.data) { 30 | return false; 31 | } 32 | 33 | slow = slow.next; 34 | } 35 | 36 | return true; 37 | } 38 | } -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java -------------------------------------------------------------------------------- /cracking-the-coding-interview/chapter-two-linked-lists/Partition.java: -------------------------------------------------------------------------------- 1 | //Write code to partition a linked list around a value x, such that 2 | //all nodes less than x come before all nodes greater than or equal to x. 3 | 4 | public class Partition { 5 | LinkedListNode partition(LinkedListNode node, int x) { 6 | LinkedListNode head = node; 7 | LinkedListNode tail = node; 8 | 9 | while(node != null) { 10 | LinkedListNode next = node.next; 11 | if(node.data < x) { 12 | /* insert node at head */ 13 | node.next = head; 14 | head = node; 15 | } 16 | else { 17 | /* insert node at tail */ 18 | tail.next = node; 19 | tail = node; 20 | } 21 | node = next; 22 | } 23 | tail.next = null; 24 | 25 | //the head has changed, so we need to return it to the user 26 | return head; 27 | } 28 | } -------------------------------------------------------------------------------- /images/BST.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/BST.png -------------------------------------------------------------------------------- /images/Complete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/Complete.png -------------------------------------------------------------------------------- /images/Full.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/Full.png -------------------------------------------------------------------------------- /images/InterviewsRepository.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/InterviewsRepository.jpg -------------------------------------------------------------------------------- /images/Perfect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/Perfect.png -------------------------------------------------------------------------------- /images/bellman-ford.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/bellman-ford.gif -------------------------------------------------------------------------------- /images/bigO.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/bigO.png -------------------------------------------------------------------------------- /images/bigOmega.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/bigOmega.png -------------------------------------------------------------------------------- /images/bucketsort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/bucketsort.png -------------------------------------------------------------------------------- /images/dfsbfs.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/dfsbfs.gif -------------------------------------------------------------------------------- /images/dijkstra.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/dijkstra.gif -------------------------------------------------------------------------------- /images/fenwickTree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/fenwickTree.png -------------------------------------------------------------------------------- /images/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/graph.png -------------------------------------------------------------------------------- /images/hash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/hash.png -------------------------------------------------------------------------------- /images/heap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/heap.png -------------------------------------------------------------------------------- /images/kruskal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/kruskal.gif -------------------------------------------------------------------------------- /images/mergesort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/mergesort.gif -------------------------------------------------------------------------------- /images/prim.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/prim.gif -------------------------------------------------------------------------------- /images/quicksort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/quicksort.gif -------------------------------------------------------------------------------- /images/segmentTree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/segmentTree.png -------------------------------------------------------------------------------- /images/the-daily-byte.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/the-daily-byte.png -------------------------------------------------------------------------------- /images/theta.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/theta.png -------------------------------------------------------------------------------- /images/trie.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/trie.png -------------------------------------------------------------------------------- /images/youtube.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/youtube.jpg -------------------------------------------------------------------------------- /images/youtube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/images/youtube.png -------------------------------------------------------------------------------- /interviews.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /leetcode/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/.DS_Store -------------------------------------------------------------------------------- /leetcode/LeetCode.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /leetcode/array/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | // Say you have an array for which the ith element is the price of a given stock on day i. 2 | 3 | // 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. 4 | 5 | // Example 1: 6 | // Input: [7, 1, 5, 3, 6, 4] 7 | // Output: 5 8 | 9 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 10 | // Example 2: 11 | // Input: [7, 6, 4, 3, 1] 12 | // Output: 0 13 | 14 | // In this case, no transaction is done, i.e. max profit = 0. 15 | 16 | public class BestTimeToBuyAndSellStock { 17 | public int maxProfit(int[] prices) { 18 | //Kadane's algorithm 19 | if(prices.length == 0) { 20 | return 0; 21 | } 22 | 23 | int min = prices[0]; 24 | int max = 0; 25 | 26 | for(int i = 1; i < prices.length; i++) { 27 | if(prices[i] > min) { 28 | max = Math.max(max, prices[i] - min); 29 | } else { 30 | min = prices[i]; 31 | } 32 | } 33 | 34 | return max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/array/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/array/IncreasingTripletSubsequence.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 2 | 3 | // Formally the function should: 4 | // Return true if there exists i, j, k 5 | // such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. 6 | // Your algorithm should run in O(n) time complexity and O(1) space complexity. 7 | 8 | // Examples: 9 | // Given [1, 2, 3, 4, 5], 10 | // return true. 11 | 12 | // Given [5, 4, 3, 2, 1], 13 | // return false. 14 | 15 | public class IncreasingTripletSequence { 16 | public boolean increasingTriplet(int[] nums) { 17 | int firstMin = Integer.MAX_VALUE; 18 | int secondMin = Integer.MAX_VALUE; 19 | 20 | for(int n : nums) { 21 | if(n <= firstMin) { 22 | firstMin = n; 23 | } else if(n < secondMin) { 24 | secondMin = n; 25 | } else if(n > secondMin) { 26 | return true; 27 | } 28 | } 29 | 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/array/MajorityElement.java: -------------------------------------------------------------------------------- 1 | //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | //You may assume that the array is non-empty and the majority element always exist in the array. 3 | 4 | class MajorityElement { 5 | public int majorityElement(int[] nums) { 6 | if(nums.length == 1) { 7 | return nums[0]; 8 | } 9 | 10 | HashMap map = new HashMap(); 11 | for(int current: nums) { 12 | if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) { 13 | return current; 14 | } else if(map.containsKey(current)) { 15 | map.put(current, map.get(current) + 1); 16 | } else { 17 | map.put(current, 1); 18 | } 19 | } 20 | 21 | //no majority element exists 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/array/MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest product. 2 | 3 | // For example, given the array [2,3,-2,4], 4 | // the contiguous subarray [2,3] has the largest product = 6. 5 | 6 | public class MaximumProductSubarray { 7 | public int maxProduct(int[] nums) { 8 | if(nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int result = nums[0]; 13 | int max = nums[0]; 14 | int min = nums[0]; 15 | 16 | for(int i = 1; i < nums.length; i++) { 17 | int temp = max; 18 | max = Math.max(Math.max(nums[i] * max, nums[i] * min), nums[i]); 19 | min = Math.min(Math.min(nums[i] * temp, nums[i] * min), nums[i]); 20 | 21 | if(max > result) { 22 | result = max; 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/array/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 2 | 3 | // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 4 | // the contiguous subarray [4,-1,2,1] has the largest sum = 6. 5 | 6 | public class Solution { 7 | 8 | public int maxSubArray(int[] nums) { 9 | 10 | int[] dp = new int[nums.length]; 11 | 12 | dp[0] = nums[0]; 13 | 14 | int max = dp[0]; 15 | 16 | for(int i = 1; i < nums.length; i++) { 17 | 18 | dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 19 | 20 | max = Math.max(dp[i], max); 21 | 22 | } 23 | 24 | return max; 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /leetcode/array/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | //Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right 2 | //which minimizes the sum of all numbers along its path. 3 | //Note: You can only move either down or right at any point in time. 4 | //Example 1: 5 | //[[1,3,1], 6 | //[1,5,1], 7 | //[4,2,1]] 8 | //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. 9 | 10 | class MinimumPathSum { 11 | public int minPathSum(int[][] grid) { 12 | for(int i = 1; i < grid.length; i++) { 13 | grid[i][0] += grid[i - 1][0]; 14 | } 15 | for(int i = 1; i < grid[0].length; i++) { 16 | grid[0][i] += grid[0][i - 1]; 17 | } 18 | 19 | for(int i = 1; i < grid.length; i++) { 20 | for(int j = 1; j < grid[0].length; j++) { 21 | grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 22 | } 23 | } 24 | 25 | return grid[grid.length - 1][grid[0].length - 1]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/array/MissingRanges.java: -------------------------------------------------------------------------------- 1 | // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 2 | 3 | // For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. 4 | 5 | public class MissingRanges { 6 | public List findMissingRanges(int[] nums, int lower, int upper) { 7 | ArrayList result = new ArrayList(); 8 | for(int i = 0; i <= nums.length; i++) { 9 | long start = i == 0 ? lower : (long)nums[i - 1] + 1; 10 | long end = i == nums.length ? upper : (long)nums[i] - 1; 11 | addMissing(result, start, end); 12 | } 13 | 14 | return result; 15 | } 16 | 17 | void addMissing(ArrayList result, long start, long end) { 18 | if(start > end) { 19 | return; 20 | } else if(start == end) { 21 | result.add(start + ""); 22 | } else { 23 | result.add(start + "->" + end); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/array/PlusOne.java: -------------------------------------------------------------------------------- 1 | //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 2 | // 3 | //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 4 | // 5 | //You may assume the integer does not contain any leading zero, except the number 0 itself. 6 | // 7 | //Example 1: 8 | // 9 | //Input: [1,2,3] 10 | //Output: [1,2,4] 11 | //Explanation: The array represents the integer 123. 12 | //Example 2: 13 | // 14 | //Input: [4,3,2,1] 15 | //Output: [4,3,2,2] 16 | //Explanation: The array represents the integer 4321. 17 | 18 | class Solution { 19 | public int[] plusOne(int[] digits) { 20 | for(int i = digits.length - 1; i >= 0; i--) { 21 | if(digits[i] < 9) { 22 | digits[i]++; 23 | return digits; 24 | } 25 | 26 | digits[i] = 0; 27 | } 28 | 29 | int[] result = new int[digits.length + 1]; 30 | result[0] = 1; 31 | 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/array/RemoveElement.java: -------------------------------------------------------------------------------- 1 | //Given an array and a value, remove all instances of that value in-place and return the new length. 2 | //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 3 | //The order of elements can be changed. It doesn't matter what you leave beyond the new length. 4 | 5 | //Example: 6 | //Given nums = [3,2,2,3], val = 3, 7 | //Your function should return length = 2, with the first two elements of nums being 2. 8 | 9 | class RemoveElement { 10 | public int removeElement(int[] nums, int val) { 11 | int index = 0; 12 | for(int i = 0; i < nums.length; i++) { 13 | if(nums[i] != val) { 14 | nums[index++] = nums[i]; 15 | } 16 | } 17 | 18 | return index; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/array/RotateImage.java: -------------------------------------------------------------------------------- 1 | // You are given an n x n 2D matrix representing an image. 2 | 3 | // Rotate the image by 90 degrees (clockwise). 4 | 5 | // Follow up: 6 | // Could you do this in-place? 7 | 8 | public class RotateImage { 9 | public void rotate(int[][] matrix) { 10 | for(int i = 0; i < matrix.length; i++) { 11 | for(int j = 0; j < i; j++) { 12 | int temp = matrix[i][j]; 13 | matrix[i][j] = matrix[j][i]; 14 | matrix[j][i] = temp; 15 | } 16 | } 17 | 18 | for(int i = 0; i < matrix.length; i++) { 19 | for(int j = 0; j < matrix[0].length / 2; j++) { 20 | int temp = matrix[i][j]; 21 | matrix[i][j] = matrix[i][matrix[0].length - 1 - j]; 22 | matrix[i][matrix[0].length - 1 - j] = temp; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/array/Subsets.java: -------------------------------------------------------------------------------- 1 | // Given a set of distinct integers, nums, return all possible subsets. 2 | 3 | // Note: The solution set must not contain duplicate subsets. 4 | 5 | // For example, 6 | // If nums = [1,2,3], a solution is: 7 | 8 | // [ 9 | // [3], 10 | // [1], 11 | // [2], 12 | // [1,2,3], 13 | // [1,3], 14 | // [2,3], 15 | // [1,2], 16 | // [] 17 | // ] 18 | 19 | public class Subsets { 20 | public List> subsets(int[] nums) { 21 | List> result = new ArrayList<>(); 22 | 23 | recurse(result, nums, new Stack<>(), 0); 24 | 25 | return result; 26 | } 27 | 28 | private void recurse(List> result, int[] nums, Stack path, int position) { 29 | if(position == nums.length) { 30 | result.add(new ArrayList<>(path)); 31 | return; 32 | } 33 | 34 | path.push(nums[position]); 35 | 36 | recurse(result, nums, path, position + 1); 37 | 38 | path.pop(); 39 | 40 | recurse(result, nums, path, position + 1); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /leetcode/array/SummaryRanges.java: -------------------------------------------------------------------------------- 1 | // Given a sorted integer array without duplicates, return the summary of its ranges. 2 | 3 | // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 4 | 5 | public class SummaryRanges { 6 | public List summaryRanges(int[] nums) { 7 | List result = new ArrayList(); 8 | 9 | if(nums.length == 1) { 10 | result.add(nums[0] + ""); 11 | return result; 12 | } 13 | 14 | for(int i = 0; i < nums.length; i++) { 15 | int current = nums[i]; 16 | 17 | while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) { 18 | i++; 19 | } 20 | 21 | if(current != nums[i]) { 22 | result.add(current + "->" + nums[i]); 23 | } else { 24 | result.add(current + ""); 25 | } 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/array/WiggleSort.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class WiggleSort { 6 | public void wiggleSort(int[] nums) { 7 | for(int i = 1; i < nums.length; i++) { 8 | int current = nums[i - 1]; 9 | 10 | if((i % 2 == 1) == (current > nums[i])) { 11 | nums[i - 1] = nums[i]; 12 | nums[i] = current; 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/backtracking/GeneralizedAbbreviation.java: -------------------------------------------------------------------------------- 1 | // Write a function to generate the generalized abbreviations of a word. 2 | 3 | // Example: 4 | // Given word = "word", return the following list (order does not matter): 5 | // ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 6 | 7 | public class GeneralizedAbbreviation { 8 | public List generateAbbreviations(String word) { 9 | List result = new ArrayList(); 10 | 11 | backtrack(result, word, 0, "", 0); 12 | 13 | return result; 14 | } 15 | 16 | void backtrack(List result, String word, int position, String current, int count) { 17 | if(position == word.length()) { 18 | if(count > 0) { 19 | current += count; 20 | } 21 | 22 | result.add(current); 23 | } else { 24 | backtrack(result, word, position + 1, current, count + 1); 25 | backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/backtracking/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | // 3 | //For example, given n = 3, a solution set is: 4 | // 5 | //[ 6 | //"((()))", 7 | //"(()())", 8 | //"(())()", 9 | //"()(())", 10 | //"()()()" 11 | //] 12 | 13 | class GenerateParentheses { 14 | public List generateParenthesis(int n) { 15 | List result = new ArrayList(); 16 | generateParenthesisRecursive(result, "", 0, 0, n); 17 | 18 | return result; 19 | } 20 | 21 | public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { 22 | if(current.length() == n * 2) { 23 | result.add(current); 24 | return; 25 | } 26 | 27 | if(open < n) { 28 | generateParenthesisRecursive(result, current + "(", open + 1, close, n); 29 | } 30 | 31 | if(close < open) { 32 | generateParenthesisRecursive(result, current + ")", open, close + 1, n); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/backtracking/Permutations.java: -------------------------------------------------------------------------------- 1 | //Given a collection of distinct numbers, return all possible permutations. 2 | // 3 | //For example, 4 | //[1,2,3] have the following permutations: 5 | //[ 6 | //[1,2,3], 7 | //[1,3,2], 8 | //[2,1,3], 9 | //[2,3,1], 10 | //[3,1,2], 11 | //[3,2,1] 12 | //] 13 | 14 | class Permutations { 15 | public List> permute(int[] nums) { 16 | LinkedList> result = new LinkedList>(); 17 | result.add(new ArrayList()); 18 | for (int n: nums) { 19 | int size = result.size(); 20 | while(size > 0) { 21 | List current = result.pollFirst(); 22 | for (int i = 0; i <= current.size(); i++) { 23 | List temp = new ArrayList(current); 24 | temp.add(i, n); 25 | result.add(temp); 26 | } 27 | size--; 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/binary-search/ClosestBinarySearchTreeValue.java: -------------------------------------------------------------------------------- 1 | // Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 2 | 3 | // Note: 4 | // Given target value is a floating point. 5 | // You are guaranteed to have only one unique value in the BST that is closest to the target. 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * public class TreeNode { 10 | * int val; 11 | * TreeNode left; 12 | * TreeNode right; 13 | * TreeNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class ClosestBinarySearchTreeValue { 17 | public int closestValue(TreeNode root, double target) { 18 | int value = root.val; 19 | TreeNode child = root.val < target ? root.right : root.left; 20 | 21 | if(child == null) { 22 | return value; 23 | } 24 | 25 | int childValue = closestValue(child, target); 26 | 27 | return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/binary-search/GuessNumberHigherOrLower.java: -------------------------------------------------------------------------------- 1 | // We are playing the Guess Game. The game is as follows: 2 | 3 | // I pick a number from 1 to n. You have to guess which number I picked. 4 | 5 | // Every time you guess wrong, I'll tell you whether the number is higher or lower. 6 | 7 | // You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 8 | 9 | // -1 : My number is lower 10 | // 1 : My number is higher 11 | // 0 : Congrats! You got it! 12 | // Example: 13 | // n = 10, I pick 6. 14 | 15 | // Return 6. 16 | 17 | public class GuessNumberHigherOrLower extends GuessGame { 18 | public int guessNumber(int n) { 19 | int left = 1; 20 | int right = n; 21 | while(left <= right) { 22 | int mid = left + (right - left) / 2; 23 | if(guess(mid) == 0) { 24 | return mid; 25 | } else if(guess(mid) > 0) { 26 | left = mid + 1; 27 | } else { 28 | right = mid; 29 | } 30 | } 31 | 32 | return -1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/binary-search/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/binary-search/SquareRootX.java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class Solution { 6 | public int mySqrt(int x) { 7 | if(x == 0) { 8 | return 0; 9 | } 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | int mid = left + (right - left) / 2; 16 | 17 | if(mid == x / mid) { 18 | return mid; 19 | } else if(mid > x / mid) { 20 | right = mid - 1; 21 | } else if(mid < x / mid) { 22 | left = mid + 1; 23 | } 24 | } 25 | 26 | return right; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/CountingBits.java: -------------------------------------------------------------------------------- 1 | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 2 | 3 | // Example: 4 | // For num = 5 you should return [0,1,1,2,1,2]. 5 | 6 | public class CountingBits { 7 | public int[] countBits(int num) { 8 | int[] bits = new int[num + 1]; 9 | 10 | bits[0] = 0; 11 | 12 | for(int i = 1; i <= num; i++) { 13 | bits[i] = bits[i >> 1] + (i & 1); 14 | } 15 | 16 | return bits; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/HammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class HammingDistance { 22 | public int hammingDistance(int x, int y) { 23 | return Integer.bitCount(x ^ y); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/NumberOfOneBits.java: -------------------------------------------------------------------------------- 1 | // Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 2 | 3 | // For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 4 | 5 | public class NumberOfOneBits { 6 | // you need to treat n as an unsigned value 7 | public int hammingWeight(int n) { 8 | if(n == 0) { 9 | return 0; 10 | } 11 | 12 | int count = 0; 13 | 14 | while(n != 0) { 15 | count += (n) & 1; 16 | n >>>= 1; 17 | } 18 | 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/SumOfTwoInteger.java: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | 3 | // Example: 4 | // Given a = 1 and b = 2, return 3. 5 | 6 | public class SumOfTwoIntegers { 7 | public int getSum(int a, int b) { 8 | if(a == 0) { 9 | return b; 10 | } 11 | 12 | if(b == 0) { 13 | return a; 14 | } 15 | 16 | while(b != 0) { 17 | int carry = a & b; 18 | a = a ^ b; 19 | b = carry << 1; 20 | } 21 | 22 | return a; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/brainteaser/BulbSwitcher.java: -------------------------------------------------------------------------------- 1 | //There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 2 | //Example: 3 | //Given n = 3. 4 | 5 | //At first, the three bulbs are [off, off, off]. 6 | //After first round, the three bulbs are [on, on, on]. 7 | //After second round, the three bulbs are [on, off, on]. 8 | //After third round, the three bulbs are [on, off, off]. 9 | 10 | //So you should return 1, because there is only one bulb is on. 11 | 12 | class BulbSwitcher { 13 | public int bulbSwitch(int n) { 14 | return (int)Math.sqrt(n); 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode/depth-first-search/BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, determine if it is height-balanced. 2 | 3 | // For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class BalancedBinaryTree { 15 | boolean balanced = true; 16 | 17 | public boolean isBalanced(TreeNode root) { 18 | height(root); 19 | return balanced; 20 | } 21 | 22 | private int height(TreeNode root) { 23 | if(root == null) { 24 | return 0; 25 | } 26 | 27 | int leftHeight = height(root.left); 28 | int rightHeight = height(root.right); 29 | 30 | if(Math.abs(leftHeight - rightHeight) > 1) { 31 | balanced = false; 32 | } 33 | 34 | return 1 + Math.max(leftHeight, rightHeight); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/depth-first-search/ConvertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class ConvertSortedArrayToBinarySearchTree { 13 | public TreeNode sortedArrayToBST(int[] nums) { 14 | if(nums.length == 0) { 15 | return null; 16 | } 17 | 18 | TreeNode root = helper(nums, 0, nums.length - 1); 19 | 20 | return root; 21 | } 22 | 23 | private TreeNode helper(int[] nums, int start, int end) { 24 | if(start <= end) { 25 | int mid = (start + end) / 2; 26 | 27 | TreeNode current = new TreeNode(nums[mid]); 28 | 29 | current.left = helper(nums, start, mid - 1); 30 | current.right = helper(nums, mid + 1, end); 31 | 32 | return current; 33 | } 34 | 35 | return null; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/depth-first-search/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/depth-first-search/SameTree.java: -------------------------------------------------------------------------------- 1 | // Given two binary trees, write a function to check if they are equal or not. 2 | 3 | // Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class SameTree { 15 | public boolean isSameTree(TreeNode p, TreeNode q) { 16 | if(p == null && q == null) { 17 | return true; 18 | } 19 | 20 | if(p == null && q != null || q == null && p != null) { 21 | return false; 22 | } 23 | 24 | if(p.val != q.val) { 25 | return false; 26 | } 27 | 28 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/divide-and-conquer/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | Arrays.sort(nums); 13 | 14 | return nums[length - k]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | // You are climbing a stair case. It takes n steps to reach to the top. 2 | 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | // Note: Given n will be a positive integer. 6 | 7 | public class ClimbingStairs { 8 | public int climbStairs(int n) { 9 | int[] dp = new int[n + 1]; 10 | 11 | dp[0] = 1; 12 | dp[1] = 1; 13 | 14 | for(int i = 2; i < dp.length; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } 17 | 18 | return dp[dp.length - 1]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/CountingBits.java: -------------------------------------------------------------------------------- 1 | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 2 | 3 | // Example: 4 | // For num = 5 you should return [0,1,1,2,1,2]. 5 | 6 | // Follow up: 7 | // It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? 8 | // Space complexity should be O(n). 9 | // Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. 10 | 11 | public class CountingBits { 12 | public int[] countBits(int num) { 13 | int[] bits = new int[num + 1]; 14 | 15 | bits[0] = 0; 16 | 17 | for(int i = 1; i <= num; i++) { 18 | bits[i] = bits[i >> 1] + (i & 1); 19 | } 20 | 21 | return bits; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/HouseRobber.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // 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. 4 | 5 | public class Solution { 6 | public int rob(int[] nums) { 7 | if(nums.length == 0) { 8 | return 0; 9 | } 10 | 11 | if(nums.length == 1) { 12 | return nums[0]; 13 | } 14 | 15 | int[] dp = new int[nums.length]; 16 | 17 | dp[0] = nums[0]; 18 | dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; 19 | 20 | for(int i = 2; i < nums.length; i++) { 21 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 22 | } 23 | 24 | return dp[dp.length - 1]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | //Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right 2 | //which minimizes the sum of all numbers along its path. 3 | //Note: You can only move either down or right at any point in time. 4 | //Example 1: 5 | //[[1,3,1], 6 | //[1,5,1], 7 | //[4,2,1]] 8 | //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. 9 | 10 | class MinimumPathSum { 11 | public int minPathSum(int[][] grid) { 12 | for(int i = 1; i < grid.length; i++) { 13 | grid[i][0] += grid[i - 1][0]; 14 | } 15 | for(int i = 1; i < grid[0].length; i++) { 16 | grid[0][i] += grid[0][i - 1]; 17 | } 18 | 19 | for(int i = 1; i < grid.length; i++) { 20 | for(int j = 1; j < grid[0].length; j++) { 21 | grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 22 | } 23 | } 24 | 25 | return grid[grid.length - 1][grid[0].length - 1]; 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/PaintFence.java: -------------------------------------------------------------------------------- 1 | // There is a fence with n posts, each post can be painted with one of the k colors. 2 | 3 | // You have to paint all the posts such that no more than two adjacent fence posts have the same color. 4 | 5 | // Return the total number of ways you can paint the fence. 6 | 7 | // Note: 8 | // n and k are non-negative integers. 9 | 10 | public class PaintFence { 11 | public int numWays(int n, int k) { 12 | if(n <= 0) { 13 | return 0; 14 | } 15 | 16 | int sameColorCounts = 0; 17 | int differentColorCounts = k; 18 | 19 | for(int i = 2; i <= n; i++) { 20 | int temp = differentColorCounts; 21 | differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); 22 | sameColorCounts = temp; 23 | } 24 | 25 | return sameColorCounts + differentColorCounts; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/UniqueBinarySearchTrees.java: -------------------------------------------------------------------------------- 1 | // Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 2 | 3 | // For example, 4 | // Given n = 3, there are a total of 5 unique BST's. 5 | 6 | // 1 3 3 2 1 7 | // \ / / / \ \ 8 | // 3 2 1 1 3 2 9 | // / / \ \ 10 | // 2 1 2 3 11 | 12 | public class UniqueBinarySearchTree { 13 | public int numTrees(int n) { 14 | int[] dp = new int[n + 1]; 15 | 16 | dp[0] = 1; 17 | dp[1] = 1; 18 | 19 | for(int i = 2; i <= n; i++) { 20 | for(int j = 1; j <= i; j++) { 21 | dp[i] += dp[i - j] * dp[j - 1]; 22 | } 23 | } 24 | 25 | return dp[n]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/dynamic-programming/WordBreak.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given 4 | // s = "leetcode", 5 | // dict = ["leet", "code"]. 6 | 7 | // Return true because "leetcode" can be segmented as "leet code". 8 | 9 | public class WordBreak { 10 | public boolean wordBreak(String s, Set wordDict) { 11 | boolean[] dp = new boolean[s.length() + 1]; 12 | 13 | dp[0] = true; 14 | 15 | for(int i = 1; i <= s.length(); i++) { 16 | for(int j = 0; j < i; j++) { 17 | if(dp[j] && wordDict.contains(s.substring(j, i))) { 18 | dp[i] = true; 19 | break; 20 | } 21 | } 22 | } 23 | 24 | return dp[s.length()]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/greedy/BestTimeToBuyAndSellStockII.java: -------------------------------------------------------------------------------- 1 | //Say you have an array for which the ith element is the price of a given stock on day i. 2 | //Design an algorithm to find the maximum profit. You may complete as many transactions as you 3 | //like (ie, buy one and sell one share of the stock multiple times). However, you may not engage 4 | //in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | 6 | class BestTimeToBuyAndSellStockII { 7 | public int maxProfit(int[] prices) { 8 | if(prices == null || prices.length == 0) { 9 | return 0; 10 | } 11 | 12 | int profit = 0; 13 | for(int i = 0; i < prices.length - 1; i++) { 14 | if(prices[i] < prices[i + 1]) { 15 | profit += prices[i + 1] - prices[i]; 16 | } 17 | } 18 | 19 | return profit; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/hash-table/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/hash-table/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /leetcode/hash-table/DailyTemperatures.java: -------------------------------------------------------------------------------- 1 | //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 2 | // 3 | //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 4 | // 5 | //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 6 | 7 | class DailyTemperatures { 8 | public int[] dailyTemperatures(int[] temperatures) { 9 | int[] result = new int[temperatures.length]; 10 | Stack stack = new Stack(); 11 | for(int i = 0; i < temperatures.length; i++) { 12 | while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { 13 | int index = stack.pop(); 14 | result[index] = i - index; 15 | } 16 | stack.push(i); 17 | } 18 | 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/hash-table/FindAnagramMappings.java: -------------------------------------------------------------------------------- 1 | //Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. 2 | //We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j. 3 | //These lists A and B may contain duplicates. If there are multiple answers, output any of them. 4 | 5 | //For example, given 6 | //A = [12, 28, 46, 32, 50] 7 | //B = [50, 12, 32, 46, 28] 8 | 9 | //We should return 10 | //[1, 4, 3, 2, 0] 11 | //as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on. 12 | 13 | class FindAnagramMappings { 14 | public int[] anagramMappings(int[] A, int[] B) { 15 | int[] mapping = new int[A.length]; 16 | HashMap map = new HashMap(); 17 | 18 | for(int i = 0; i < B.length; i++) { 19 | map.put(B[i], i); 20 | } 21 | 22 | for(int i = 0; i < A.length; i++) { 23 | mapping[i] = map.get(A[i]); 24 | } 25 | 26 | return mapping; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/hash-table/FindTheDifference.java: -------------------------------------------------------------------------------- 1 | // Given two strings s and t which consist of only lowercase letters. 2 | 3 | // String t is generated by random shuffling string s and then add one more letter at a random position. 4 | 5 | // Find the letter that was added in t. 6 | 7 | // Example: 8 | 9 | // Input: 10 | // s = "abcd" 11 | // t = "abcde" 12 | 13 | // Output: 14 | // e 15 | 16 | // Explanation: 17 | // 'e' is the letter that was added. 18 | 19 | public class FindTheDifference { 20 | public char findTheDifference(String s, String t) { 21 | int charCodeS = 0; 22 | int charCodeT = 0; 23 | 24 | for(int i = 0; i < s.length(); i++) { 25 | charCodeS += (int)(s.charAt(i)); 26 | } 27 | 28 | for(int i = 0; i < t.length(); i++) { 29 | charCodeT += (int)(t.charAt(i)); 30 | } 31 | 32 | return (char)(charCodeT - charCodeS); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/hash-table/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/hash-table/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | //You're given strings J representing the types of stones that are jewels, and S representing the stones you have. 2 | //Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 3 | 4 | //The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, 5 | //so "a" is considered a different type of stone from "A". 6 | 7 | class JewelsAndStones { 8 | public int numJewelsInStones(String J, String S) { 9 | HashMap map = new HashMap(); 10 | for(char c: J.toCharArray()) { 11 | map.put(c, 1); 12 | } 13 | 14 | int numberOfJewels = 0; 15 | for(char c: S.toCharArray()) { 16 | if(map.containsKey(c)) { 17 | numberOfJewels++; 18 | } 19 | } 20 | 21 | return numberOfJewels; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/hash-table/SingleNumberII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, every element appears three times except for one, 2 | //which appears exactly once. Find that single one. 3 | 4 | //Note: 5 | //Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | 7 | class SingleNumberII { 8 | public int singleNumber(int[] nums) { 9 | HashMap map = new HashMap(); 10 | for(int i: nums) { 11 | if(map.containsKey(i)) { 12 | map.put(i, map.get(i) + 1); 13 | } else { 14 | map.put(i, 1); 15 | } 16 | } 17 | 18 | for(int key: map.keySet()) { 19 | if(map.get(key) == 1) { 20 | return key; 21 | } 22 | } 23 | 24 | //no unique integer in nums 25 | return -1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/hash-table/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | 3 | // Write a function to determine if a number is strobogrammatic. The number is represented as a string. 4 | 5 | // For example, the numbers "69", "88", and "818" are all strobogrammatic. 6 | 7 | public class StrobogrammaticNumber { 8 | public boolean isStrobogrammatic(String num) { 9 | for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { 10 | if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/hash-table/TwoSum.java: -------------------------------------------------------------------------------- 1 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 2 | 3 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | // Example: 6 | // Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | // Because nums[0] + nums[1] = 2 + 7 = 9, 9 | // return [0, 1]. 10 | 11 | public class TwoSum { 12 | public int[] twoSum(int[] nums, int target) { 13 | int[] result = new int[2]; 14 | 15 | HashMap map = new HashMap<>(); 16 | 17 | for(int i = 0; i < nums.length; i++) { 18 | if(map.containsKey(target - nums[i])) { 19 | result[1] = i; 20 | result[0] = map.get(target - nums[i]); 21 | 22 | return result; 23 | } 24 | 25 | map.put(nums[i], i); 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/hash-table/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | class ValidAnagram { 2 | public boolean isAnagram(String s, String t) { 3 | HashMap map = new HashMap(); 4 | for(char c: s.toCharArray()) { 5 | if(map.containsKey(c)) { 6 | map.put(c, map.get(c) + 1); 7 | } 8 | else { 9 | map.put(c, 1); 10 | } 11 | } 12 | 13 | for(char c: t.toCharArray()) { 14 | if(map.containsKey(c)) { 15 | map.put(c, map.get(c) - 1); 16 | } 17 | else { 18 | return false; 19 | } 20 | } 21 | 22 | for(char c: map.keySet()) { 23 | if(map.get(c) != 0) { 24 | return false; 25 | } 26 | } 27 | 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/linked-list/DeleteNodeInALinkedList.java: -------------------------------------------------------------------------------- 1 | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 2 | 3 | // Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class DeleteNodeInALinkedList { 14 | public void deleteNode(ListNode node) { 15 | node.val = node.next.val; 16 | node.next = node.next.next; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/linked-list/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /leetcode/linked-list/PalindromeLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class PalindromeLinkedList { 10 | public boolean isPalindrome(ListNode head) { 11 | if(head == null || head.next == null) { 12 | return true; 13 | } 14 | 15 | Stack stack = new Stack(); 16 | 17 | ListNode fast = head; 18 | ListNode slow = head; 19 | 20 | while(fast != null && fast.next != null) { 21 | stack.push(slow.val); 22 | fast = fast.next.next; 23 | slow = slow.next; 24 | } 25 | 26 | if(fast != null) { 27 | slow = slow.next; 28 | } 29 | 30 | while(slow != null) { 31 | if(stack.pop() != slow.val) { 32 | return false; 33 | } 34 | 35 | slow = slow.next; 36 | } 37 | 38 | return true; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /leetcode/linked-list/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/math/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/math/BulbSwitcher.java: -------------------------------------------------------------------------------- 1 | //There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 2 | //Example: 3 | //Given n = 3. 4 | 5 | //At first, the three bulbs are [off, off, off]. 6 | //After first round, the three bulbs are [on, on, on]. 7 | //After second round, the three bulbs are [on, off, on]. 8 | //After third round, the three bulbs are [on, off, off]. 9 | 10 | //So you should return 1, because there is only one bulb is on. 11 | 12 | class BulbSwitcher { 13 | public int bulbSwitch(int n) { 14 | return (int)Math.sqrt(n); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/math/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | //Determine whether an integer is a palindrome. Do this without extra space. 2 | 3 | class PalindromeNumber { 4 | public boolean isPalindrome(int x) { 5 | if(x < 0) { 6 | return false; 7 | } 8 | 9 | int num = x; 10 | int reversed = 0; 11 | 12 | while(num != 0) { 13 | reversed = reversed * 10 + num % 10; 14 | num /= 10; 15 | } 16 | 17 | return x == reversed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/math/PlusOne.java: -------------------------------------------------------------------------------- 1 | //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 2 | // 3 | //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 4 | // 5 | //You may assume the integer does not contain any leading zero, except the number 0 itself. 6 | // 7 | //Example 1: 8 | // 9 | //Input: [1,2,3] 10 | //Output: [1,2,4] 11 | //Explanation: The array represents the integer 123. 12 | //Example 2: 13 | // 14 | //Input: [4,3,2,1] 15 | //Output: [4,3,2,2] 16 | //Explanation: The array represents the integer 4321. 17 | 18 | class Solution { 19 | public int[] plusOne(int[] digits) { 20 | for(int i = digits.length - 1; i >= 0; i--) { 21 | if(digits[i] < 9) { 22 | digits[i]++; 23 | return digits; 24 | } 25 | 26 | digits[i] = 0; 27 | } 28 | 29 | int[] result = new int[digits.length + 1]; 30 | result[0] = 1; 31 | 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/math/PoorPigs.java: -------------------------------------------------------------------------------- 1 | //There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. 2 | //They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the 3 | //minimum amount of pigs you need to figure out which bucket contains the poison within one hour. 4 | 5 | //Answer this question, and write an algorithm for the follow-up general case. 6 | 7 | //Follow-up: 8 | //If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) 9 | //you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. 10 | 11 | class PoorPigs { 12 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 13 | int numPigs = 0; 14 | while (Math.pow(minutesToTest / minutesToDie + 1, numPigs) < buckets) { 15 | numPigs++; 16 | } 17 | 18 | return numPigs; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/math/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/queue/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kdn251/interviews/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/queue/.DS_Store -------------------------------------------------------------------------------- /leetcode/queue/MovingAverageFromDataStream.java: -------------------------------------------------------------------------------- 1 | // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 2 | 3 | // For example, 4 | // MovingAverage m = new MovingAverage(3); 5 | // m.next(1) = 1 6 | // m.next(10) = (1 + 10) / 2 7 | // m.next(3) = (1 + 10 + 3) / 3 8 | // m.next(5) = (10 + 3 + 5) / 3 9 | 10 | /** 11 | * Your MovingAverage object will be instantiated and called as such: 12 | * MovingAverage obj = new MovingAverage(size); 13 | * double param_1 = obj.next(val); 14 | */ 15 | 16 | public class MovingAverageFromDataStream { 17 | double previousSum = 0.0; 18 | int maxSize; 19 | Queue window; 20 | 21 | /** Initialize your data structure here. */ 22 | public MovingAverage(int size) { 23 | this.maxSize = size; 24 | window = new LinkedList(); 25 | } 26 | 27 | public double next(int val) { 28 | if(window.size() == maxSize) { 29 | previousSum -= window.remove(); 30 | } 31 | 32 | window.add(val); 33 | previousSum += val; 34 | 35 | return previousSum / window.size(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/sort/MeetingRooms.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [[0, 30],[5, 10],[15, 20]], 5 | // return false. 6 | 7 | /** 8 | * Definition for an interval. 9 | * public class Interval { 10 | * int start; 11 | * int end; 12 | * Interval() { start = 0; end = 0; } 13 | * Interval(int s, int e) { start = s; end = e; } 14 | * } 15 | */ 16 | public class MeetingRooms { 17 | public boolean canAttendMeetings(Interval[] intervals) { 18 | if(intervals == null) { 19 | return false; 20 | } 21 | 22 | // Sort the intervals by start time 23 | Arrays.sort(intervals, new Comparator() { 24 | public int compare(Interval a, Interval b) { return a.start - b.start; } 25 | }); 26 | 27 | for(int i = 1; i < intervals.length; i++) { 28 | if(intervals[i].start < intervals[i - 1].end) { 29 | return false; 30 | } 31 | } 32 | 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/stack/DailyTemperatures.java: -------------------------------------------------------------------------------- 1 | //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 2 | // 3 | //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 4 | // 5 | //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 6 | 7 | class DailyTemperatures { 8 | public int[] dailyTemperatures(int[] temperatures) { 9 | int[] result = new int[temperatures.length]; 10 | Stack stack = new Stack(); 11 | for(int i = 0; i < temperatures.length; i++) { 12 | while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { 13 | int index = stack.pop(); 14 | result[index] = i - index; 15 | } 16 | stack.push(i); 17 | } 18 | 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/stack/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, 4 | // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 5 | 6 | public class TrappingRainWater { 7 | public int trap(int[] height) { 8 | int water = 0; 9 | 10 | int leftIndex = 0; 11 | int rightIndex = height.length - 1; 12 | 13 | int leftMax = 0; 14 | int rightMax = 0; 15 | 16 | while(leftIndex <= rightIndex) { 17 | leftMax = Math.max(leftMax, height[leftIndex]); 18 | rightMax = Math.max(rightMax, height[rightIndex]); 19 | 20 | if(leftMax < rightMax) { 21 | water += leftMax - height[leftIndex]; 22 | leftIndex++; 23 | } else { 24 | water += rightMax - height[rightIndex]; 25 | rightIndex--; 26 | } 27 | } 28 | 29 | return water; 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /leetcode/string/AddBinary.java: -------------------------------------------------------------------------------- 1 | // Given two binary strings, return their sum (also a binary string). 2 | 3 | // For example, 4 | // a = "11" 5 | // b = "1" 6 | // Return "100" 7 | 8 | public class AddBinary { 9 | public String addBinary(String a, String b) { 10 | StringBuilder result = new StringBuilder(); 11 | 12 | int carry = 0; 13 | int i = a.length() - 1; 14 | int j = b.length() - 1; 15 | 16 | while(i >= 0 || j >= 0) { 17 | int sum = carry; 18 | 19 | if(i >= 0) { 20 | sum += a.charAt(i--) - '0'; 21 | } 22 | 23 | if(j >= 0) { 24 | sum += b.charAt(j--) - '0'; 25 | } 26 | 27 | result.append(sum % 2); 28 | carry = sum / 2; 29 | } 30 | 31 | if(carry != 0) { 32 | result.append(carry); 33 | } 34 | 35 | return result.reverse().toString(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/string/DecodeWays.java: -------------------------------------------------------------------------------- 1 | // A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | // 'A' -> 1 4 | // 'B' -> 2 5 | // ... 6 | // 'Z' -> 26 7 | 8 | // Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | // For example, 11 | // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | // The number of ways decoding "12" is 2. 14 | 15 | public class DecodeWays { 16 | public int numDecodings(String s) { 17 | int n = s.length(); 18 | 19 | if(n == 0) { 20 | return 0; 21 | } 22 | 23 | int[] dp = new int[n + 1]; 24 | dp[n] = 1; 25 | dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; 26 | 27 | for(int i = n - 2; i >= 0; i--) { 28 | if(s.charAt(i) == '0') { 29 | continue; 30 | } else { 31 | dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; 32 | } 33 | } 34 | 35 | return dp[0]; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/string/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 2 | // 3 | //Examples: 4 | // 5 | //s = "leetcode" 6 | //return 0. 7 | // 8 | //s = "loveleetcode", 9 | //return 2. 10 | //Note: You may assume the string contain only lowercase letters. 11 | 12 | class FirstUniqueCharacterInAString { 13 | public int firstUniqChar(String s) { 14 | HashMap characters = new HashMap(); 15 | for(int i = 0; i < s.length(); i++) { 16 | char current = s.charAt(i); 17 | if(characters.containsKey(current)) { 18 | characters.put(current, -1); 19 | } else { 20 | characters.put(current, i); 21 | } 22 | } 23 | 24 | int min = Integer.MAX_VALUE; 25 | for(char c: characters.keySet()) { 26 | if(characters.get(c) > -1 && characters.get(c) < min) { 27 | min = characters.get(c); 28 | } 29 | } 30 | 31 | return min == Integer.MAX_VALUE ? -1 : min; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/string/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | // 3 | //For example, given n = 3, a solution set is: 4 | // 5 | //[ 6 | //"((()))", 7 | //"(()())", 8 | //"(())()", 9 | //"()(())", 10 | //"()()()" 11 | //] 12 | 13 | class GenerateParentheses { 14 | public List generateParenthesis(int n) { 15 | List result = new ArrayList(); 16 | generateParenthesisRecursive(result, "", 0, 0, n); 17 | 18 | return result; 19 | } 20 | 21 | public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { 22 | if(current.length() == n * 2) { 23 | result.add(current); 24 | return; 25 | } 26 | 27 | if(open < n) { 28 | generateParenthesisRecursive(result, current + "(", open + 1, close, n); 29 | } 30 | 31 | if(close < open) { 32 | generateParenthesisRecursive(result, current + ")", open, close + 1, n); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/string/JudgeRouteCircle.java: -------------------------------------------------------------------------------- 1 | //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 2 | // 3 | //The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 4 | // 5 | //Example 1: 6 | //Input: "UD" 7 | //Output: true 8 | //Example 2: 9 | //Input: "LL" 10 | //Output: false 11 | 12 | class JudgeRouteCircle { 13 | public boolean judgeCircle(String moves) { 14 | int UD = 0; 15 | int LR = 0; 16 | for(int i = 0; i < moves.length(); i++) { 17 | if(moves.charAt(i) == 'U') { 18 | UD++; 19 | } else if(moves.charAt(i) == 'D') { 20 | UD--; 21 | } else if(moves.charAt(i) == 'L') { 22 | LR++; 23 | } else if(moves.charAt(i) == 'R') { 24 | LR--; 25 | } 26 | } 27 | 28 | return UD == 0 && LR == 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/string/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | class LongestCommonPrefix { 2 | public String longestCommonPrefix(String[] strs) { 3 | if(strs == null || strs.length == 0) { 4 | return ""; 5 | } 6 | 7 | String s = strs[0]; 8 | for(int i = 0; i < s.length(); i++) { 9 | char current = s.charAt(i); 10 | for(int j = 1; j < strs.length; j++) { 11 | if(i >= strs[j].length() || strs[j].charAt(i) != current) { 12 | return s.substring(0, i); 13 | } 14 | } 15 | } 16 | 17 | return s; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/string/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | public class LongestPalindrome { 2 | public int longestPalindrome(String s) { 3 | HashMap map = new HashMap(); 4 | 5 | int count = 0; 6 | 7 | for(int i = 0; i < s.length(); i++) { 8 | if(!map.containsKey(s.charAt(i))) { 9 | map.put(s.charAt(i), (int)(s.charAt(i))); 10 | } else { 11 | map.remove(s.charAt(i)); 12 | count++; 13 | } 14 | } 15 | 16 | return map.isEmpty() ? count * 2 : count * 2 + 1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/string/PalindromePermutation.java: -------------------------------------------------------------------------------- 1 | public class PalindromePermutation { 2 | public boolean canPermutePalindrome(String s) { 3 | char[] characters = new char[256]; 4 | 5 | for(int i = 0; i < s.length(); i++) { 6 | characters[s.charAt(i)]++; 7 | } 8 | 9 | int oddCount = 0; 10 | 11 | for(int i = 0; i < characters.length; i++) { 12 | if(!(characters[i] % 2 == 0)) { 13 | oddCount++; 14 | 15 | if(oddCount > 1) { 16 | return false; 17 | } 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/string/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/string/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | // Given a roman numeral, convert it to an integer. 2 | 3 | // Input is guaranteed to be within the range from 1 to 3999 4 | 5 | public class RomanToInteger { 6 | public int romanToInt(String s) { 7 | HashMap map = new HashMap(); 8 | 9 | map.put('I', 1); 10 | map.put('V', 5); 11 | map.put('X', 10); 12 | map.put('L', 50); 13 | map.put('C', 100); 14 | map.put('D', 500); 15 | map.put('M', 1000); 16 | 17 | int total = 0; 18 | 19 | for(int i = 0; i < s.length() - 1; i++) { 20 | if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { 21 | total -= map.get(s.charAt(i)); 22 | } else { 23 | total += map.get(s.charAt(i)); 24 | } 25 | } 26 | 27 | total += map.get(s.charAt(s.length() - 1)); 28 | 29 | return total; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/string/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | public class ValidPalindrome { 2 | public boolean isPalindrome(String s) { 3 | int left = 0; 4 | int right = s.length() - 1; 5 | 6 | while(left < right) { 7 | while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { 8 | left++; 9 | } 10 | 11 | while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { 12 | right--; 13 | } 14 | 15 | if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 16 | return false; 17 | } 18 | 19 | left++; 20 | right--; 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/tree/InorderSuccessorInBST.java: -------------------------------------------------------------------------------- 1 | // Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 2 | 3 | // Note: If the given node has no in-order successor in the tree, return null. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class InorderSuccessorInBST { 15 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 16 | TreeNode successor = null; 17 | 18 | while(root != null) { 19 | if(p.val < root.val) { 20 | successor = root; 21 | root = root.left; 22 | } else { 23 | root = root.right; 24 | } 25 | } 26 | 27 | return successor; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/tree/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Invert a binary tree. 2 | 3 | // 4 4 | // / \ 5 | // 2 7 6 | // / \ / \ 7 | // 1 3 6 9 8 | 9 | // to 10 | 11 | // 4 12 | // / \ 13 | // 7 2 14 | // / \ / \ 15 | // 9 6 3 1 16 | 17 | /** 18 | * Definition for a binary tree node. 19 | * public class TreeNode { 20 | * int val; 21 | * TreeNode left; 22 | * TreeNode right; 23 | * TreeNode(int x) { val = x; } 24 | * } 25 | */ 26 | public class InvertBinaryTree { 27 | public TreeNode invertTree(TreeNode root) { 28 | if(root == null) { 29 | return root; 30 | } 31 | 32 | TreeNode temp = root.left; 33 | root.left = invertTree(root.right); 34 | root.right = invertTree(temp); 35 | 36 | return root; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /leetcode/tree/SumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | // Find the sum of all left leaves in a given binary tree. 2 | 3 | // Example: 4 | 5 | // 3 6 | // / \ 7 | // 9 20 8 | // / \ 9 | // 15 7 10 | 11 | // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 12 | 13 | /** 14 | * Definition for a binary tree node. 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | public class SumOfLeftLeaves { 23 | public int sumOfLeftLeaves(TreeNode root) { 24 | if(root == null) { 25 | return 0; 26 | } 27 | 28 | int total = 0; 29 | 30 | if(root.left != null) { 31 | if(root.left.left == null && root.left.right == null) { 32 | total += root.left.val; 33 | } else { 34 | total += sumOfLeftLeaves(root.left); 35 | } 36 | } 37 | 38 | total += sumOfLeftLeaves(root.right); 39 | 40 | return total; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /leetcode/tree/TrimABinarySearchTree.java: -------------------------------------------------------------------------------- 1 | //Given a binary search tree and the lowest and highest boundaries as L and R, trim the 2 | //tree so that all its elements lies in [L, R] (R >= L). You might need to change the root 3 | //of the tree, so the result should return the new root of the trimmed binary search tree. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | class TrimABinarySearchTree { 15 | public TreeNode trimBST(TreeNode root, int L, int R) { 16 | if(root == null) { 17 | return root; 18 | } 19 | if(root.val < L) { 20 | return trimBST(root.right, L, R); 21 | } 22 | if(root.val > R) { 23 | return trimBST(root.left, L, R); 24 | } 25 | 26 | root.left = trimBST(root.left, L, R); 27 | root.right = trimBST(root.right, L, R); 28 | 29 | return root; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/two-pointers/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | //Given a linked list, determine if it has a cycle in it. 2 | //Follow up: 3 | //Can you solve it without using extra space? 4 | /** 5 | * Definition for singly-linked list. 6 | * class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | if(head == null || head.next == null) { 18 | return false; 19 | } 20 | 21 | ListNode slow = head; 22 | ListNode fast = head.next; 23 | while(fast != null && fast.next != null && fast != slow) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | } 27 | 28 | return fast == slow; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/two-pointers/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | 3 | // Note: 4 | // 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. 5 | 6 | public class MergeSortedArray { 7 | public void merge(int[] A, int m, int[] B, int n) { 8 | int i = m - 1; 9 | int j = n - 1; 10 | int k = m + n - 1; 11 | 12 | while(i >= 0 && j >= 0) { 13 | A[k--] = A[i] > B[j] ? A[i--] : B[j--]; 14 | } 15 | 16 | while(j >= 0) { 17 | A[k--] = B[j--]; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/two-pointers/MinimumSizeSubarraySum.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given the array [2,3,1,2,4,3] and s = 7, 4 | // the subarray [4,3] has the minimal length under the problem constraint. 5 | 6 | public class MinimumSizeSubarraySum { 7 | public int minSubArrayLen(int s, int[] nums) { 8 | if(nums == null || nums.length == 0) { 9 | return 0; 10 | } 11 | 12 | int i = 0; 13 | int j = 0; 14 | int result = Integer.MAX_VALUE; 15 | int total = 0; 16 | 17 | while(i < nums.length) { 18 | total += nums[i++]; 19 | 20 | while(total >= s) { 21 | result = Math.min(result, i - j); 22 | total -= nums[j++]; 23 | } 24 | } 25 | 26 | return result == Integer.MAX_VALUE ? 0 : result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/two-pointers/MoveZeros.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 4 | 5 | // Note: 6 | // You must do this in-place without making a copy of the array. 7 | // Minimize the total number of operations. 8 | 9 | public class MoveZeros { 10 | public void moveZeroes(int[] nums) { 11 | if(nums == null || nums.length == 0) { 12 | return; 13 | } 14 | 15 | int index = 0; 16 | for(int num : nums) { 17 | if(num != 0) { 18 | nums[index] = num; 19 | index++; 20 | } 21 | } 22 | 23 | while(index < nums.length) { 24 | nums[index] = 0; 25 | index++; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/two-pointers/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 2 | 3 | // Do not allocate extra space for another array, you must do this in place with constant memory. 4 | 5 | // For example, 6 | // Given input array nums = [1,1,2], 7 | 8 | // 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. 9 | 10 | public class RemoveDuplicatesFromSortedArray { 11 | public int removeDuplicates(int[] nums) { 12 | if(nums.length == 0 || nums == null) { 13 | return 0; 14 | } 15 | 16 | if(nums.length < 2) { 17 | return nums.length; 18 | } 19 | 20 | int index = 1; 21 | 22 | for(int i = 1; i < nums.length; i++) { 23 | if(nums[i] != nums[i - 1]) { 24 | nums[index++] = nums[i]; 25 | } 26 | } 27 | 28 | return index; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/two-pointers/RemoveElement.java: -------------------------------------------------------------------------------- 1 | //Given an array and a value, remove all instances of that value in-place and return the new length. 2 | //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 3 | //The order of elements can be changed. It doesn't matter what you leave beyond the new length. 4 | 5 | //Example: 6 | //Given nums = [3,2,2,3], val = 3, 7 | //Your function should return length = 2, with the first two elements of nums being 2. 8 | 9 | class RemoveElement { 10 | public int removeElement(int[] nums, int val) { 11 | int index = 0; 12 | for(int i = 0; i < nums.length; i++) { 13 | if(nums[i] != val) { 14 | nums[index++] = nums[i]; 15 | } 16 | } 17 | 18 | return index; 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /leetcode/two-pointers/ReverseString.java: -------------------------------------------------------------------------------- 1 | // Write a function that takes a string as input and returns the string reversed. 2 | 3 | // Example: 4 | // Given s = "hello", return "olleh". 5 | 6 | public class ReverseString { 7 | public String reverseString(String s) { 8 | if(s == null || s.length() == 1 || s.length() == 0) { 9 | return s; 10 | } 11 | 12 | char[] word = s.toCharArray(); 13 | 14 | for(int i = 0, j = s.length() - 1; i < j; i++, j--) { 15 | char temp = word[i]; 16 | word[i] = word[j]; 17 | word[j] = temp; 18 | } 19 | 20 | return new String(word); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/two-pointers/SortColors.java: -------------------------------------------------------------------------------- 1 | // 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. 2 | 3 | // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 4 | 5 | // Note: 6 | // You are not suppose to use the library's sort function for this problem. 7 | 8 | public class SortColors { 9 | public void sortColors(int[] nums) { 10 | int wall = 0; 11 | 12 | for(int i = 0; i < nums.length; i++) { 13 | if(nums[i] < 1) { 14 | int temp = nums[i]; 15 | nums[i] = nums[wall]; 16 | nums[wall] = temp; 17 | wall++; 18 | } 19 | } 20 | 21 | for(int i = 0; i < nums.length; i++) { 22 | if(nums[i] == 1) { 23 | int temp = nums[i]; 24 | nums[i] = nums[wall]; 25 | nums[wall] = temp; 26 | wall++; 27 | } 28 | } 29 | } 30 | } 31 | --------------------------------------------------------------------------------