Repository: kdn251/interviews Branch: master Commit: 03fdcb2703ce Files: 526 Total size: 696.0 KB Directory structure: gitextract_nak9cli1/ ├── .gitignore ├── .project ├── LICENSE ├── README-zh-cn.md ├── README.md ├── company/ │ ├── Company.iml │ ├── adobe/ │ │ ├── AddDigits.java │ │ └── MajorityElement.java │ ├── airbnb/ │ │ ├── AddTwoNumbers.java │ │ ├── ContainsDuplicate.java │ │ ├── ContainsDuplicatesII.java │ │ ├── ConvertSortedArrayToBinarySearchTree.java │ │ ├── HouseRobber.java │ │ ├── MergeKSortedLists.java │ │ ├── RegularExpressionMatching.java │ │ ├── TwoSum.java │ │ └── ValidParentheses.java │ ├── amazon/ │ │ ├── 3Sum.java │ │ ├── AddTwoNumbers.java │ │ ├── BestTimeToBuyAndSellStock.java │ │ ├── BinaryTreeLevelOrderTraversal.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── GroupAnagrams.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── KthLargestElementInAnArray.java │ │ ├── LetterCombinationsOfAPhoneNumber.java │ │ ├── LinkedListCycle.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── LowestCommonAncestorOfABinaryTree.java │ │ ├── MergeKSortedLists.java │ │ ├── MinCostClimbingStairs.java │ │ ├── MinStack.java │ │ ├── NumberOfIslands.java │ │ ├── PalindromeLinkedList.java │ │ ├── ProductOfArrayExceptSelf.java │ │ ├── ReverseLinkedList.java │ │ ├── RotateImage.java │ │ ├── Subsets.java │ │ ├── TrappingRainWater.java │ │ ├── TwoSum.java │ │ ├── ValidParentheses.java │ │ ├── ValidateBinarySearchTree.java │ │ └── WordBreak.java │ ├── apple/ │ │ ├── ReverseWordsInAString.java │ │ └── ValidSudoku.java │ ├── bloomberg/ │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── LinkedListCycle.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── MinStack.java │ │ ├── ReverseWordsInAString.java │ │ └── UniquePaths.java │ ├── facebook/ │ │ ├── 3Sum.java │ │ ├── AddAndSearchWordDataStructureDesign.java │ │ ├── AddBinary.java │ │ ├── BestTimeToBuyAndSellStock.java │ │ ├── BinarySearchTreeIterator.java │ │ ├── BinaryTreeLevelOrderTraversal.java │ │ ├── BinaryTreePaths.java │ │ ├── BinaryTreeVerticalOrderTraversal.java │ │ ├── CloneGraph.java │ │ ├── CombinationSumIV.java │ │ ├── CountAndSay.java │ │ ├── DecodeWays.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── ExclusiveTimeOfFunctions.java │ │ ├── ExpressionAddOperators.java │ │ ├── FindTheCelebrity.java │ │ ├── FirstBadVersion.java │ │ ├── FlattenNestedListIterator.java │ │ ├── GroupAnagrams.java │ │ ├── HammingDistance.java │ │ ├── ImplementTrie.java │ │ ├── InorderSuccessorInBST.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── InsertInterval.java │ │ ├── IntegerToEnglishWords.java │ │ ├── KthLargestElementInAnArray.java │ │ ├── LetterCombinationsOfAPhoneNumber.java │ │ ├── LongestConsecutiveSequence.java │ │ ├── LowestCommonAncestorOfABinaryTree.java │ │ ├── MaximumSizeSubarraySumEqualsK.java │ │ ├── MeetingRooms.java │ │ ├── MergeIntervals.java │ │ ├── MergeKSortedLists.java │ │ ├── MergeSortedArray.java │ │ ├── MinStack.java │ │ ├── MinimumSizeSubarraySum.java │ │ ├── MinimumWindowSubstring.java │ │ ├── MoveZeros.java │ │ ├── MultiplyStrings.java │ │ ├── NumberOfIslands.java │ │ ├── OneEditDistance.java │ │ ├── PaintHouseII.java │ │ ├── PalindromeLinkedList.java │ │ ├── PalindromicSubstrings.java │ │ ├── PowerOfXToTheN.java │ │ ├── ProductOfArrayExceptSelf.java │ │ ├── RegularExpressionMatching.java │ │ ├── RemoveDuplicatesFromSortedArray.java │ │ ├── RemoveInvalidParentheses.java │ │ ├── ReverseLinkedList.java │ │ ├── RomanToInteger.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SortColors.java │ │ ├── SparseMatrixMultiplication.java │ │ ├── SquareRootX.java │ │ ├── Subsets.java │ │ ├── SubsetsII.java │ │ ├── SumOfLeftLeaves.java │ │ ├── TwoSum.java │ │ ├── ValidPalindrome.java │ │ ├── ValidParentheses.java │ │ ├── ValidateBinarySearchTree.java │ │ ├── WallsAndGates.java │ │ ├── WordBreak.java │ │ └── WordSearch.java │ ├── google/ │ │ ├── 3SumSmaller.java │ │ ├── AndroidUnlockPatterns.java │ │ ├── BinarySearchTreeIterator.java │ │ ├── BinaryTreePaths.java │ │ ├── BinaryTreeVerticalOrderTraversal.java │ │ ├── BinaryWatch.java │ │ ├── BombEnemy.java │ │ ├── BullsAndCows.java │ │ ├── CloneGraph.java │ │ ├── ClosestBinarySearchTreeValue.java │ │ ├── CombinationSumIV.java │ │ ├── DailyTemperatures.java │ │ ├── DecodeString.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── ExpressionAddOperators.java │ │ ├── FindAllNumbersDisappearedInAnArray.java │ │ ├── FindTheDifference.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── FlattenNestedListIterator.java │ │ ├── GameOfLife.java │ │ ├── GeneralizedAbbreviation.java │ │ ├── GenerateParentheses.java │ │ ├── GroupShiftedStrings.java │ │ ├── GuessNumberHigherOrLower.java │ │ ├── ImplementTrie.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── InsertInterval.java │ │ ├── IslandPerimeter.java │ │ ├── JudgeRouteCircle.java │ │ ├── LetterCombinationsOfAPhoneNumber.java │ │ ├── LoggerRateLimiter.java │ │ ├── LongestConsecutiveSequence.java │ │ ├── LongestSubstringWithAtMostKDistinctCharacters.java │ │ ├── MaximumProductOfWordLengths.java │ │ ├── MergeIntervals.java │ │ ├── MinStack.java │ │ ├── MissingRanges.java │ │ ├── MovingAverageFromDataStream.java │ │ ├── NumberOfIslands.java │ │ ├── PacificAtlanticWaterFlow.java │ │ ├── PaintFence.java │ │ ├── PlusOne.java │ │ ├── PlusOneLinkedList.java │ │ ├── PowerOfTwo.java │ │ ├── PowerOfXToTheN.java │ │ ├── RegularExpressionMatching.javaa │ │ ├── ReverseVowelsOfAString.java │ │ ├── SentenceScreenFitting.java │ │ ├── ShortestDistanceFromAllBuildings.java │ │ ├── SpiralMatrix.java │ │ ├── StrobogrammaticNumber.java │ │ ├── SummaryRanges.java │ │ ├── TrappingRainWater.java │ │ ├── UniqueWordAbbreviation.java │ │ ├── Utf8Validation.java │ │ ├── ValidParentheses.java │ │ ├── WallsAndGates.java │ │ ├── WiggleSort.java │ │ ├── WordBreak.java │ │ ├── WordSquares.java │ │ └── ZigZagIterator.java │ ├── linkedin/ │ │ ├── BinarySearchTreeIterator.java │ │ ├── BinaryTreeLevelOrderTraversal.java │ │ ├── FindTheCelebrity.java │ │ ├── HouseRobber.java │ │ ├── InsertInterval.java │ │ ├── LowestCommonAncestorOfABinaryTree.java │ │ ├── MaximumDepthOfABinaryTree.java │ │ ├── MaximumProductSubarray.java │ │ ├── MaximumSubarray.java │ │ ├── MergeIntervals.java │ │ ├── MergeKSortedLists.java │ │ ├── MinimumWindowSubstring.java │ │ ├── PaintHouse.java │ │ ├── PalindromicSubstrings.java │ │ ├── Permutations.java │ │ ├── PowerOfXToTheN.java │ │ ├── ProductOfArrayExceptSelf.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SparseMatrixMultiplication.java │ │ ├── SymmetricTree.java │ │ └── TwoSum.java │ ├── microsoft/ │ │ ├── AddDigits.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── HouseRobberII.java │ │ ├── LinkedListCycle.java │ │ ├── LongestIncreasingSubsequence.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── Permutations.java │ │ ├── ReverseWordsInAString.java │ │ └── SpiralMatrix.java │ ├── palantir/ │ │ ├── ContainsDuplicate.java │ │ └── ContainsDuplicatesII.java │ ├── snapchat/ │ │ ├── MinStack.java │ │ ├── ReverseWordsInAString.java │ │ └── ValidSudoku.java │ ├── twitter/ │ │ ├── FlattenNestedListIterator.java │ │ ├── ImplementTrie.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── LowestCommonAncestorOfABinaryTree.java │ │ ├── MergeIntervals.java │ │ ├── MergeKSortedLists.java │ │ ├── MultiplyStrings.java │ │ ├── OneEditDistance.java │ │ ├── RegularExpressionMatching.java │ │ ├── ReverseLinkedList.java │ │ ├── TrappingRainWater.java │ │ └── ValidParentheses.java │ ├── uber/ │ │ ├── BestTimeToBuyOrSellStock.java │ │ ├── CloneGraph.java │ │ ├── DecodeWays.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── ExclusiveTimeOfFunctions.java │ │ ├── GenerateParentheses.java │ │ ├── GroupAnagrams.java │ │ ├── GroupShiftedStrings.java │ │ ├── ImplementTrie.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── LetterCombinationsOfAPhoneNumber.java │ │ ├── MaximumDepthOfABinaryTree.java │ │ ├── MergeKSortedLists.java │ │ ├── MinStack.java │ │ ├── MinimumWindowSubstring.java │ │ ├── OneEditDistance.java │ │ ├── PalindromePermutation.java │ │ ├── RegularExpressionMatching.java │ │ ├── ReverseLinkedList.java │ │ ├── RomanToInteger.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SpiralMatrix.java │ │ ├── Subsets.java │ │ ├── TwoSum.java │ │ ├── ValidPalindrome.java │ │ ├── ValidSudoku.java │ │ └── WordBreak.java │ ├── yahoo/ │ │ ├── ContainsDuplicate.java │ │ └── LinkedListCycle.java │ └── yelp/ │ ├── InsertDeleteGetRandomO1.java │ └── ReverseWordsInAString.java ├── cracking-the-coding-interview/ │ ├── CrackingTheCodingInterview.iml │ ├── chapter-five-bit-manipulation/ │ │ ├── BinaryRepresentation.java │ │ ├── FindMissingInteger.java │ │ ├── InsertMIntoN.java │ │ └── SwapBits.java │ ├── chapter-four-trees-and-graphs/ │ │ ├── BinaryTreeIsBalanced.java │ │ ├── CreateBinarySearchTree.java │ │ ├── CreateLinkedListForEachLevel.java │ │ ├── FindPath.java │ │ ├── IsSubtree.java │ │ ├── PrintPaths.java │ │ └── ValidBinarySearchTree.java │ ├── chapter-nine-recursion-and-dynamic-programming/ │ │ ├── AllPermutations.java │ │ ├── AllSubsets.java │ │ ├── EightQueens.java │ │ ├── MagicIndex.java │ │ ├── RepresentingNCents.java │ │ ├── StackBoxes.java │ │ └── Staircase.java │ ├── chapter-one-arrays-and-strings/ │ │ ├── DeleteDups.java │ │ ├── IsRotation.java │ │ ├── IsUniqueChars.java │ │ ├── NthToLast.java │ │ ├── Permutation.java │ │ └── ReplaceSpaces.java │ ├── chapter-seven-mathematics-and-probability/ │ │ ├── Operations.java │ │ └── WouldIntersect.java │ ├── chapter-three-stacks-and-queues/ │ │ ├── BinaryTreeIsBalanced.java │ │ ├── MyQUeue.java │ │ ├── MyQueue.java │ │ ├── QueueUsingTwoStacks.java │ │ ├── SetOfStacks.java │ │ ├── SortStack.java │ │ ├── StackWithMin.java │ │ ├── ThreeStacks.java │ │ └── TowersOfHanoi.java │ └── chapter-two-linked-lists/ │ ├── DeleteDups.java │ ├── DeleteNode.java │ ├── FindBeginning.java │ ├── IsPalindrome.java │ ├── NthToLast.java │ └── Partition.java ├── interviews.iml ├── leetcode/ │ ├── LeetCode.iml │ ├── array/ │ │ ├── BestTimeToBuyAndSellStock.java │ │ ├── ContainsDuplicatesII.java │ │ ├── FindAllNumbersDisappearedInAnArray.java │ │ ├── FindTheCelebrity.java │ │ ├── GameOfLife.java │ │ ├── IncreasingTripletSubsequence.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── InsertInterval.java │ │ ├── LongestConsecutiveSequence.java │ │ ├── MajorityElement.java │ │ ├── MaximumProductSubarray.java │ │ ├── MaximumSubarray.java │ │ ├── MergeIntervals.java │ │ ├── MinCostClimbingStairs.java │ │ ├── MinimumPathSum.java │ │ ├── MissingRanges.java │ │ ├── PlusOne.java │ │ ├── ProductofArrayExceptSelf.java │ │ ├── RemoveElement.java │ │ ├── RotateImage.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SpiralMatrix.java │ │ ├── SpiralMatrixII.java │ │ ├── Subsets.java │ │ ├── SubsetsII.java │ │ ├── SummaryRanges.java │ │ ├── UniquePaths.java │ │ ├── WiggleSort.java │ │ └── WordSearch.java │ ├── backtracking/ │ │ ├── AndroidUnlockPatterns.java │ │ ├── GeneralizedAbbreviation.java │ │ ├── GenerateParentheses.java │ │ ├── LetterCombinationsOfAPhoneNumber.java │ │ └── Permutations.java │ ├── binary-search/ │ │ ├── ClosestBinarySearchTreeValue.java │ │ ├── FirstBadVersion.java │ │ ├── GuessNumberHigherOrLower.java │ │ ├── PowerOfXToTheN.java │ │ └── SquareRootX.java │ ├── bit-manipulation/ │ │ ├── BinaryWatch.java │ │ ├── CountingBits.java │ │ ├── HammingDistance.java │ │ ├── MaximumProductOfWordLengths.java │ │ ├── NumberOfOneBits.java │ │ ├── PowerOfTwo.java │ │ ├── SumOfTwoInteger.java │ │ └── Utf8Validation.java │ ├── brainteaser/ │ │ └── BulbSwitcher.java │ ├── breadth-first-search/ │ │ ├── BinaryTreeLevelOrderTraversal.java │ │ ├── CloneGraph.java │ │ ├── PacificAtlanticWaterFlow.java │ │ ├── RemoveInvalidParentheses.java │ │ ├── ShortestDistanceFromAllBuildings.java │ │ ├── SymmetricTree.java │ │ └── WallsAndGates.java │ ├── depth-first-search/ │ │ ├── BalancedBinaryTree.java │ │ ├── BattleshipsInABoard.java │ │ ├── ConvertSortedArrayToBinarySearchTree.java │ │ ├── MaximumDepthOfABinaryTree.java │ │ ├── NumberOfIslands.java │ │ ├── PopulatingNextRightPointersInEachNode.java │ │ └── SameTree.java │ ├── design/ │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── MinStack.java │ │ └── ZigZagIterator.java │ ├── divide-and-conquer/ │ │ ├── ExpressionAddOperators.java │ │ └── KthLargestElementInAnArray.java │ ├── dynamic-programming/ │ │ ├── BombEnemy.java │ │ ├── ClimbingStairs.java │ │ ├── CoinChange.java │ │ ├── CombinationSumIV.java │ │ ├── CountingBits.java │ │ ├── EditDistance.java │ │ ├── HouseRobber.java │ │ ├── HouseRobberII.java │ │ ├── LongestIncreasingSubsequence.java │ │ ├── MinCostClimbingStairs.java │ │ ├── MinimumPathSum.java │ │ ├── PaintFence.java │ │ ├── PaintHouse.java │ │ ├── PaintHouseII.java │ │ ├── PalindromicSubstrings.java │ │ ├── RegularExpressionMatching.java │ │ ├── SentenceScreenFitting.java │ │ ├── UniqueBinarySearchTrees.java │ │ ├── UniquePaths.java │ │ └── WordBreak.java │ ├── greedy/ │ │ └── BestTimeToBuyAndSellStockII.java │ ├── hash-table/ │ │ ├── BinaryTreeVerticalOrderTraversal.java │ │ ├── BullsAndCows.java │ │ ├── ContainsDuplicate.java │ │ ├── ContainsDuplicatesII.java │ │ ├── DailyTemperatures.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── FindAnagramMappings.java │ │ ├── FindTheDifference.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── GroupAnagrams.java │ │ ├── GroupShiftedStrings.java │ │ ├── InsertDeleteGetRandomO1.java │ │ ├── IslandPerimeter.java │ │ ├── JewelsAndStones.java │ │ ├── LoggerRateLimiter.java │ │ ├── MaximumSizeSubarraySumEqualsK.java │ │ ├── MinimumWindowSubstring.java │ │ ├── SingleNumberII.java │ │ ├── SparseMatrixMultiplication.java │ │ ├── StrobogrammaticNumber.java │ │ ├── TwoSum.java │ │ ├── UniqueWordAbbreviation.java │ │ ├── ValidAnagram.java │ │ └── ValidSudoku.java │ ├── linked-list/ │ │ ├── AddTwoNumbers.java │ │ ├── DeleteNodeInALinkedList.java │ │ ├── LinkedListCycle.java │ │ ├── MergeKSortedLists.java │ │ ├── PalindromeLinkedList.java │ │ ├── PlusOneLinkedList.java │ │ └── ReverseLinkedList.java │ ├── math/ │ │ ├── AddDigits.java │ │ ├── BulbSwitcher.java │ │ ├── EncodeAndDecodeTinyURL.java │ │ ├── PalindromeNumber.java │ │ ├── PlusOne.java │ │ ├── PoorPigs.java │ │ └── PowerOfTwo.java │ ├── queue/ │ │ └── MovingAverageFromDataStream.java │ ├── sort/ │ │ ├── MeetingRooms.java │ │ └── MeetingRoomsII.java │ ├── stack/ │ │ ├── BinarySearchTreeIterator.java │ │ ├── DailyTemperatures.java │ │ ├── DecodeString.java │ │ ├── ExclusiveTimeOfFunctions.java │ │ ├── FlattenNestedListIterator.java │ │ ├── MinStack.java │ │ └── TrappingRainWater.java │ ├── string/ │ │ ├── AddBinary.java │ │ ├── CountAndSay.java │ │ ├── DecodeWays.java │ │ ├── EditDistance.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── GenerateParentheses.java │ │ ├── IntegerToEnglishWords.java │ │ ├── JudgeRouteCircle.java │ │ ├── LongestCommonPrefix.java │ │ ├── LongestPalindrome.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── LongestSubstringWithAtMostKDistinctCharacters.java │ │ ├── MinimumWindowSubstring.java │ │ ├── MultiplyStrings.java │ │ ├── OneEditDistance.java │ │ ├── PalindromePermutation.java │ │ ├── PalindromicSubstrings.java │ │ ├── ReverseVowelsOfAString.java │ │ ├── ReverseWordsInAString.java │ │ ├── RomanToInteger.java │ │ ├── ValidPalindrome.java │ │ └── ValidParentheses.java │ ├── tree/ │ │ ├── BinaryTreeMaximumPathSum.java │ │ ├── BinaryTreePaths.java │ │ ├── InorderSuccessorInBST.java │ │ ├── InvertBinaryTree.java │ │ ├── LowestCommonAncestorOfABinaryTree.java │ │ ├── SumOfLeftLeaves.java │ │ ├── TrimABinarySearchTree.java │ │ └── ValidateBinarySearchTree.java │ ├── trie/ │ │ ├── AddAndSearchWordDataStructureDesign.java │ │ ├── ImplementTrie.java │ │ └── WordSquares.java │ └── two-pointers/ │ ├── 3Sum.java │ ├── 3SumSmaller.java │ ├── LinkedListCycle.java │ ├── MergeSortedArray.java │ ├── MinimumSizeSubarraySum.java │ ├── MoveZeros.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── RemoveElement.java │ ├── ReverseString.java │ └── SortColors.java └── uva/ ├── AddingReversedNumbers.java ├── Ants.java ├── ArchaeologistsDilemma.java ├── AverageSpeed.java ├── BackToIntermediateMath.java ├── BasicRemains.java ├── BasicallySpeaking.java ├── BigMod.java ├── BrickGame.java ├── CoconutsRevisited.java ├── DigitCounting.java ├── FactorialFrequenices.java ├── FiveHundredFactorial.java ├── Friends.java ├── GoldbachConjecture.java ├── GoogleIsFeelingLucky.java ├── HashmatWarriors.java ├── HighPrecisionNumber.java ├── HighSchoolPhysics.java ├── ICanGuessTheDataStructure.java ├── IntegerInquiry.java ├── JollyJumpers.java ├── LargestPrimeDivisor.java ├── LightMoreLight.java ├── MischievousChildren.java ├── Modex.java ├── MultipleOfSeventeen.java ├── Newspaper.java ├── NumberTheoryForNewbies.java ├── NumberingRoads.java ├── OpenSource.java ├── Parity.java ├── PeskyPalindromes.java ├── PrimeFactors.java ├── PseudoPrimeNumbers.java ├── SimplifyingFractions.java ├── SimplyEmirp.java ├── SkewBinary.java ├── SolveEquation.java ├── SplittingNumbers.java ├── TheHugeOne.java ├── TheLastNonZeroDigit.java ├── TheSettlersOfCatan.java ├── VeryEasy.java ├── VirtualFriends.java ├── WhatBaseIsThis.java └── WhoSaidCrisis.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /bin/ .idea ================================================ FILE: .project ================================================ interviews ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Kevin Naughton Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README-zh-cn.md ================================================ > * 原文地址:[github.com/kdn251/interviews](https://github.com/kdn251/interviews) > * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner) > * 译者:[王下邀月熊](https://github.com/wxyyxc1992) > * 校对者:[PhxNirvana](https://github.com/phxnirvana)、[根号三](https://github.com/sqrthree) > * 这个 [链接](https://github.com/xitu/interviews/compare/master...kdn251:master) 用来查看本翻译与英文版是否有差别(如果你没有看到 README.md 发生变化,那就意味着这份翻译文档是最新的)。 # Interviews > 软件工程技术面试个人指南。 > > Maintainer - [Kevin Naughton Jr.](https://github.com/kdn251) ## 其他语言版本 - [English](./README.md) ## 目录 - [在线练习](#在线练习) - [在线面试编程](#在线面试编程) - [数据结构](#数据结构) - [算法](#算法) - [位运算](#位运算) - [算法复杂度分析](#算法复杂度分析) - [视频教程](#视频教程) - [面试书籍](#面试书籍) - [计算机科学与技术资讯](#计算机科学与技术资讯) - [文件结构](#文件结构) ## 在线练习 * [LeetCode](https://leetcode.com/) * [Virtual Judge](https://vjudge.net/) * [CareerCup](https://www.careercup.com/) * [HackerRank](https://www.hackerrank.com/) * [CodeFights](https://codefights.com/) * [Kattis](https://open.kattis.com/) * [HackerEarth](https://www.hackerearth.com) * [Codility](https://codility.com/programmers/lessons/1-iterations/) * [Code Forces](http://codeforces.com/) * [Code Chef](https://www.codechef.com/) * [Sphere Online Judge - SPOJ](http://www.spoj.com/) * [InterviewBit](https://www.interviewbit.com/) ## 在线面试编程 * [Pramp](https://www.pramp.com/ref/gt4-cn) * [Gainlo](http://www.gainlo.co/#!/) * [Refdash](https://refdash.com/) * [Interviewing.io](https://www.interviewing.io/) ## 数据结构 ### Linked List * 链表即是由节点(Node)组成的线性集合,每个节点可以利用指针指向其他节点。它是一种包含了多个节点的、能够用于表示序列的数据结构。 * **单向链表**: 链表中的节点仅指向下一个节点,并且最后一个节点指向空。 * **双向链表**: 其中每个节点具有两个指针 p、n,使得 p 指向先前节点并且 n 指向下一个节点;最后一个节点的 n 指针指向 null。 * **循环链表**:每个节点指向下一个节点并且最后一个节点指向第一个节点的链表。 * 时间复杂度: * 索引: `O(n)` * 搜索: `O(n)` * 插入: `O(1)` * 移除: `O(1)` ### Stack * 栈是元素的集合,其包含了两个基本操作:push 操作可以用于将元素压入栈,pop 操作可以将栈顶元素移除。 * 遵循后入先出(LIFO)原则。 * 时间复杂度: * 索引: `O(n)` * 搜索: `O(n)` * 插入: `O(1)` * 移除: `O(1)` ### Queue * 队列是元素的集合,其包含了两个基本操作:enqueue 操作可以用于将元素插入到队列中,而 dequeue 操作则是将元素从队列中移除。 * 遵循先入先出原则 (FIFO)。 * 时间复杂度: * 索引: `O(n)` * 搜索: `O(n)` * 插入: `O(1)` * 移除: `O(1)` ### Tree * 树是无向、连通的无环图。 ### Binary Tree * 二叉树即是每个节点最多包含左子节点与右子节点这两个节点的树形数据结构。 * **满二叉树**: 树中的每个节点仅包含 0 或 2 个节点。 * **完美二叉树(Perfect Binary Tree)**: 二叉树中的每个叶节点都拥有两个子节点,并且具有相同的高度。 * **完全二叉树**: 除最后一层外,每一层上的结点数均达到最大值;在最后一层上只缺少右边的若干结点。 ### Binary Search Tree * 二叉搜索树(BST)是一种特殊的二叉树,其任何节点中的值都会大于或者等于其左子树中存储的值并且小于或者等于其右子树中存储的值。 * 时间复杂度: * 索引: `O(log(n))` * 搜索: `O(log(n))` * 插入: `O(log(n))` * 删除: `O(log(n))` Binary Search Tree ### Trie * 字典树,又称基数树或者前缀树,能够用于存储键为字符串的动态集合或者关联数组的搜索树。树中的节点并没有直接存储关联键值,而是该节点在树中的挂载位置决定了其关联键值。某个节点的所有子节点都拥有相同的前缀,整棵树的根节点则是空字符串。 ![Alt text](/images/trie.png?raw=true "Trie") ### Fenwick Tree * 树状数组又称 Binary Indexed Tree,其表现形式为树,不过本质上是以数组实现。数组中的下标代表着树中的顶点,每个顶点的父节点或者子节点的下标能够通过位运算获得。数组中的每个元素包含了预计算的区间值之和,在整棵树更新的过程中同样会更新这些预计算的值。 * 时间复杂度: * 区间求值: `O(log(n))` * 更新: `O(log(n))` ![Alt text](/images/fenwickTree.png?raw=true "Fenwick Tree") ### Segment Tree * 线段树是用于存放间隔或者线段的树形数据结构,它允许快速的查找某一个节点在若干条线段中出现的次数. * 时间复杂度: * 区间查询: `O(log(n))` * 更新: `O(log(n))` ![Alt text](/images/segmentTree.png?raw=true "Segment Tree") ### Heap * 堆是一种特殊的基于树的满足某些特性的数据结构,整个堆中的所有父子节点的键值都会满足相同的排序条件。堆更准确地可以分为最大堆与最小堆,在最大堆中,父节点的键值永远大于或者等于子节点的值,并且整个堆中的最大值存储于根节点;而最小堆中,父节点的键值永远小于或者等于其子节点的键值,并且整个堆中的最小值存储于根节点。 * 时间复杂度: * 访问最大值 / 最小值: `O(1)` * 插入: `O(log(n))` * 移除最大值 / 最小值: `O(log(n))` Max Heap ### Hashing * 哈希能够将任意长度的数据映射到固定长度的数据。哈希函数返回的即是哈希值,如果两个不同的键得到相同的哈希值,即将这种现象称为碰撞。 * **Hash Map**: Hash Map 是一种能够建立起键与值之间关系的数据结构,Hash Map 能够使用哈希函数将键转化为桶或者槽中的下标,从而优化对于目标值的搜索速度。 * 碰撞解决 * **链地址法(Separate Chaining)**: 链地址法中,每个桶是相互独立的,包含了一系列索引的列表。搜索操作的时间复杂度即是搜索桶的时间(固定时间)与遍历列表的时间之和。 * **开地址法(Open Addressing)**: 在开地址法中,当插入新值时,会判断该值对应的哈希桶是否存在,如果存在则根据某种算法依次选择下一个可能的位置,直到找到一个尚未被占用的地址。所谓开地址法也是指某个元素的位置并不永远由其哈希值决定。 ![Alt text](/images/hash.png?raw=true "Hashing") ### Graph * 图是一种数据元素间为多对多关系的数据结构,加上一组基本操作构成的抽象数据类型。 * **无向图(Undirected Graph)**: 无向图具有对称的邻接矩阵,因此如果存在某条从节点 u 到节点 v 的边,反之从 v 到 u 的边也存在。 * **有向图(Directed Graph)**: 有向图的邻接矩阵是非对称的,即如果存在从 u 到 v 的边并不意味着一定存在从 v 到 u 的边。 Graph ## 算法 ### 排序 #### 快速排序 * 稳定: 否 * 时间复杂度: * 最优时间: `O(nlog(n))` * 最坏时间: `O(n^2)` * 平均时间: `O(nlog(n))` ![Alt text](/images/quicksort.gif?raw=true "Quicksort") #### 归并排序 * 归并排序是典型的分治算法,它不断地将某个数组分为两个部分,分别对左子数组与右子数组进行排序,然后将两个数组合并为新的有序数组。 * 稳定: 是 * 时间复杂度: * 最优时间: `O(nlog(n))` * 最坏时间: `O(nlog(n))` * 平均时间: `O(nlog(n))` ![Alt text](/images/mergesort.gif?raw=true "Mergesort") #### 桶排序 * 桶排序将数组分到有限数量的桶子里。每个桶子再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。 * 时间复杂度: * 最优时间: `Ω(n + k)` * 最坏时间: `O(n^2)` * 平均时间:`Θ(n + k)` ![Alt text](/images/bucketsort.png?raw=true "Bucket Sort") #### 基数排序 * 基数排序类似于桶排序,将数组分割到有限数目的桶中;不过其在分割之后并没有让每个桶单独地进行排序,而是直接进行了合并操作。 * 时间复杂度: * 最优时间: `Ω(nk)` * 最坏时间: `O(nk)` * 平均时间: `Θ(nk)` ### 图算法 #### 深度优先搜索 * 深度优先算法是一种优先遍历子节点而不是回溯的算法。 * 时间复杂度: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### 广度优先搜索 * 广度优先搜索是优先遍历邻居节点而不是子节点的图遍历算法。 * 时间复杂度: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### 拓扑排序 * 拓扑排序是对于有向图节点的线性排序,如果存在某条从 u 到 v 的边,则认为 u 的下标先于 v。 * 时间复杂度: `O(|V| + |E|)` #### Dijkstra 算法 * **Dijkstra 算法** 用于计算有向图中单源最短路径问题。 * 时间复杂度: `O(|V|^2)` ![Alt text](/images/dijkstra.gif?raw=true "Dijkstra's") #### Bellman-Ford 算法 * **Bellman-Ford 算法**是在带权图中计算从单一源点出发到其他节点的最短路径的算法。 * 尽管算法复杂度大于 Dijkstra 算法,但是它适用于包含了负值边的图。 * 时间复杂度: * 最优时间: `O(|E|)` - 最坏时间: `O(|V||E|)` ![Alt text](/images/bellman-ford.gif?raw=true "Bellman-Ford") #### Floyd-Warshall 算法 * **Floyd-Warshall 算法** 能够用于在无环带权图中寻找任意节点的最短路径。 * 时间复杂度: * 最优时间: `O(|V|^3)` * 最坏时间: `O(|V|^3)` * 平均时间: `O(|V|^3)` #### Prim 算法 * **Prim 算法**是用于在带权无向图中计算最小生成树的贪婪算法。换言之,Prim 算法能够在图中抽取出连接所有节点的边的最小代价子集。 * 时间复杂度: `O(|V|^2)` ![Alt text](/images/prim.gif?raw=true "Prim's Algorithm") #### Kruskal 算法 * **Kruskal 算法**同样是计算图的最小生成树的算法,与 Prim 的区别在于并不需要图是连通的。 * 时间复杂度: `O(|E|log|V|)` ![Alt text](/images/kruskal.gif?raw=true "Kruskal's Algorithm") ## 位运算 * 位运算即是在位级别进行操作的技术,合适的位运算能够帮助我们得到更快地运算速度与更小的内存使用。 * 测试第 k 位: `s & (1 << k)` * 设置第 k 位: `s |= (1 << k)` * 第 k 位置零: `s &= ~(1 << k)` * 切换第 k 位值: `s ^= ~(1 << k)` * 乘以 2n: `s << n` * 除以 2n: `s >> n` * 交集: `s & t` * 并集: `s | t` * 减法: `s & ~t` * 交换 `x = x ^ y ^ (y = x)` * 取出最小非 0 位(Extract lowest set bit): `s & (-s)` * 取出最小 0 位(Extract lowest unset bit): `~s & (s + 1)` * 交换值: ``` x ^= y; y ^= x; x ^= y; ``` ## 算法复杂度分析 #### 大 O 表示 * **大 O 表示** 用于表示某个算法的上限,往往用于描述最坏的情况。 ![Alt text](/images/bigO.png?raw=true "Theta Notation") #### 小 O 表示 * **小 O 表示**用于描述某个算法的渐进上界,不过二者要更为紧密。 #### 大 Ω 表示 * **大 Ω 表示**用于描述某个算法的渐进下界。 ![Alt text](/images/bigOmega.png?raw=true "Theta Notation") #### 小 ω 表示 * **Little Omega Notation**用于描述某个特定算法的下界,不过不一定很靠近。 #### Theta Θ 表示 * **Theta Notation**用于描述某个确定算法的确界。 ![Alt text](/images/theta.png?raw=true "Theta Notation") ## 视频教程 * Data Structures * [UC Berkeley Data Structures](https://www.youtube.com/watch?v=mFPmKGIrQs4&index=1&list=PL-XXv-cvA_iAlnI-BQr9hjqADPBtujFJd) * [MIT Advanced Data Structures](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf&index=1) * Algorithms * [MIT Introduction to Algorithms](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&index=1) * [MIT Advanced Algorithms](https://www.youtube.com/playlist?list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c) ## 面试书籍 * Competitive Programming 3 - Steven Halim & Felix Halim * Cracking The Coding Interview - Gayle Laakmann McDowell * Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro ## 计算机科学与技术资讯 * [Hacker News](https://news.ycombinator.com/) * [Lobsters](https://lobste.rs/) ## 文件结构 ``` . ├── Array │   ├── bestTimeToBuyAndSellStock.java │   ├── findTheCelebrity.java │   ├── gameOfLife.java │   ├── increasingTripletSubsequence.java │   ├── insertInterval.java │   ├── longestConsecutiveSequence.java │   ├── maximumProductSubarray.java │   ├── maximumSubarray.java │   ├── mergeIntervals.java │   ├── missingRanges.java │   ├── productOfArrayExceptSelf.java │   ├── rotateImage.java │   ├── searchInRotatedSortedArray.java │   ├── spiralMatrixII.java │   ├── subsetsII.java │   ├── subsets.java │   ├── summaryRanges.java │   ├── wiggleSort.java │   └── wordSearch.java ├── Backtracking │   ├── androidUnlockPatterns.java │   ├── generalizedAbbreviation.java │   └── letterCombinationsOfAPhoneNumber.java ├── BinarySearch │   ├── closestBinarySearchTreeValue.java │   ├── firstBadVersion.java │   ├── guessNumberHigherOrLower.java │   ├── pow(x,n).java │   └── sqrt(x).java ├── BitManipulation │   ├── binaryWatch.java │   ├── countingBits.java │   ├── hammingDistance.java │   ├── maximumProductOfWordLengths.java │   ├── numberOf1Bits.java │   ├── sumOfTwoIntegers.java │   └── utf-8Validation.java ├── BreadthFirstSearch │   ├── binaryTreeLevelOrderTraversal.java │   ├── cloneGraph.java │   ├── pacificAtlanticWaterFlow.java │   ├── removeInvalidParentheses.java │   ├── shortestDistanceFromAllBuildings.java │   ├── symmetricTree.java │   └── wallsAndGates.java ├── DepthFirstSearch │   ├── balancedBinaryTree.java │   ├── battleshipsInABoard.java │   ├── convertSortedArrayToBinarySearchTree.java │   ├── maximumDepthOfABinaryTree.java │   ├── numberOfIslands.java │   ├── populatingNextRightPointersInEachNode.java │   └── sameTree.java ├── Design │   └── zigzagIterator.java ├── DivideAndConquer │   ├── expressionAddOperators.java │   └── kthLargestElementInAnArray.java ├── DynamicProgramming │   ├── bombEnemy.java │   ├── climbingStairs.java │   ├── combinationSumIV.java │   ├── countingBits.java │   ├── editDistance.java │   ├── houseRobber.java │   ├── paintFence.java │   ├── paintHouseII.java │   ├── regularExpressionMatching.java │   ├── sentenceScreenFitting.java │   ├── uniqueBinarySearchTrees.java │   └── wordBreak.java ├── HashTable │   ├── binaryTreeVerticalOrderTraversal.java │   ├── findTheDifference.java │   ├── groupAnagrams.java │   ├── groupShiftedStrings.java │   ├── islandPerimeter.java │   ├── loggerRateLimiter.java │   ├── maximumSizeSubarraySumEqualsK.java │   ├── minimumWindowSubstring.java │   ├── sparseMatrixMultiplication.java │   ├── strobogrammaticNumber.java │   ├── twoSum.java │   └── uniqueWordAbbreviation.java ├── LinkedList │   ├── addTwoNumbers.java │   ├── deleteNodeInALinkedList.java │   ├── mergeKSortedLists.java │   ├── palindromeLinkedList.java │   ├── plusOneLinkedList.java │   ├── README.md │   └── reverseLinkedList.java ├── Queue │   └── movingAverageFromDataStream.java ├── README.md ├── Sort │   ├── meetingRoomsII.java │   └── meetingRooms.java ├── Stack │   ├── binarySearchTreeIterator.java │   ├── decodeString.java │   ├── flattenNestedListIterator.java │   └── trappingRainWater.java ├── String │   ├── addBinary.java │   ├── countAndSay.java │   ├── decodeWays.java │   ├── editDistance.java │   ├── integerToEnglishWords.java │   ├── longestPalindrome.java │   ├── longestSubstringWithAtMostKDistinctCharacters.java │   ├── minimumWindowSubstring.java │   ├── multiplyString.java │   ├── oneEditDistance.java │   ├── palindromePermutation.java │   ├── README.md │   ├── reverseVowelsOfAString.java │   ├── romanToInteger.java │   ├── validPalindrome.java │   └── validParentheses.java ├── Tree │   ├── binaryTreeMaximumPathSum.java │   ├── binaryTreePaths.java │   ├── inorderSuccessorInBST.java │   ├── invertBinaryTree.java │   ├── lowestCommonAncestorOfABinaryTree.java │   ├── sumOfLeftLeaves.java │   └── validateBinarySearchTree.java ├── Trie │   ├── addAndSearchWordDataStructureDesign.java │   ├── implementTrie.java │   └── wordSquares.java └── TwoPointers ├── 3Sum.java ├── 3SumSmaller.java ├── mergeSortedArray.java ├── minimumSizeSubarraySum.java ├── moveZeros.java ├── removeDuplicatesFromSortedArray.java ├── reverseString.java └── sortColors.java 18 directories, 124 files ``` ================================================ FILE: README.md ================================================ # Interviews > Pass your coding interviews with [The Daily Byte](https://thedailybyte.dev/?ref=kevin) > [30,000+ Software Engineers have trusted us with their interview prep](https://thedailybyte.dev/?ref=kevin). > > Maintainer - [Kevin Naughton Jr.](https://github.com/kdn251) ## Translations - [简体中文](./README-zh-cn.md) ## Table of Contents - [YouTube](#youtube) - [The Daily Byte](#the-daily-byte) - [Instagram](#instagram) - [Articles](#articles) - [Online Judges](#online-judges) - [Live Coding Practice](#live-coding-practice) - [Data Structures](#data-structures) - [Algorithms](#algorithms) - [Greedy Algorithms](#greedy-algorithms) - [Bitmasks](#bitmasks) - [Runtime Analysis](#runtime-analysis) - [Video Lectures](#video-lectures) - [Interview Books](#interview-books) - [Computer Science News](#computer-science-news) - [Directory Tree](#directory-tree) ## YouTube * [Kevin Naughton Jr.](https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g) ## The Daily Byte * [FAANG Interview Prep](https://thedailybyte.dev/?ref=kevin) ## Instagram * [Kevin Naughton Jr.](https://www.instagram.com/kevinnaughtonjr) ## Online Judges * [LeetCode](https://leetcode.com/) * [Virtual Judge](https://vjudge.net/) * [CareerCup](https://www.careercup.com/) * [HackerRank](https://www.hackerrank.com/) * [CodeFights](https://codefights.com/) * [Kattis](https://open.kattis.com/) * [HackerEarth](https://www.hackerearth.com) * [Codility](https://codility.com/programmers/lessons/1-iterations/) * [Code Forces](http://codeforces.com/) * [Code Chef](https://www.codechef.com/) * [Sphere Online Judge - SPOJ](http://www.spoj.com/) * [InterviewBit](https://www.interviewbit.com/) ## Live Mock Interviews * [The Daily Byte](https://thedailybyte.dev/mock-interview) ## Live Coding Practice * [The Daily Byte](https://thedailybyte.dev/?ref=kevin) * [Pramp](https://www.pramp.com/ref/gt4) * [Gainlo](http://www.gainlo.co/#!/) * [Refdash](https://refdash.com/) * [Interviewing.io](https://www.interviewing.io/) ## Data Structures ### Linked List * A *Linked List* is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. * **Singly-linked list**: linked list in which each node points to the next node and the last node points to null * **Doubly-linked list**: linked list in which each node has two pointers, p and n, such that p points to the previous node and n points to the next node; the last node's n pointer points to null * **Circular-linked list**: linked list in which each node points to the next node and the last node points back to the first node * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Stack * A *Stack* is a collection of elements, with two principle operations: *push*, which adds to the collection, and *pop*, which removes the most recently added element * **Last in, first out data structure (LIFO)**: the most recently added object is the first to be removed * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Queue * A *Queue* is a collection of elements, supporting two principle operations: *enqueue*, which inserts an element into the queue, and *dequeue*, which removes an element from the queue * **First in, first out data structure (FIFO)**: the oldest added object is the first to be removed * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Tree * A *Tree* is an undirected, connected, acyclic graph ### Binary Tree * A *Binary Tree* is a tree data structure in which each node has at most two children, which are referred to as the *left child* and *right child* * **Full Tree**: a tree in which every node has either 0 or 2 children * **Perfect Binary Tree**: a binary tree in which all interior nodes have two children and all leave have the same depth * **Complete Tree**: a binary tree in which every level *except possibly the last* is full and all nodes in the last level are as far left as possible ### Binary Search Tree * A binary search tree, sometimes called BST, is a type of binary tree which maintains the property that the value in each node must be greater than or equal to any value stored in the left sub-tree, and less than or equal to any value stored in the right sub-tree * Time Complexity: * Access: `O(log(n))` * Search: `O(log(n))` * Insert: `O(log(n))` * Remove: `O(log(n))` Binary Search Tree ### Trie * A trie, sometimes called a radix or prefix tree, is a kind of search tree that is used to store a dynamic set or associative array where the keys are usually Strings. No node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the String associated with that node, and the root is associated with the empty String. ![Alt text](/images/trie.png?raw=true "Trie") ### Fenwick Tree * A Fenwick tree, sometimes called a binary indexed tree, is a tree in concept, but in practice is implemented as an implicit data structure using an array. Given an index in the array representing a vertex, the index of a vertex's parent or child is calculated through bitwise operations on the binary representation of its index. Each element of the array contains the pre-calculated sum of a range of values, and by combining that sum with additional ranges encountered during an upward traversal to the root, the prefix sum is calculated * Time Complexity: * Range Sum: `O(log(n))` * Update: `O(log(n))` ![Alt text](/images/fenwickTree.png?raw=true "Fenwick Tree") ### Segment Tree * A Segment tree, is a tree data structure for storing intervals, or segments. It allows querying which of the stored segments contain a given point * Time Complexity: * Range Query: `O(log(n))` * Update: `O(log(n))` ![Alt text](/images/segmentTree.png?raw=true "Segment Tree") ### Heap * A *Heap* is a specialized tree based structure data structure that satisfies the *heap* property: if A is a parent node of B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap. A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than or equal to those of the children and the lowest key is in the root node * Time Complexity: * Access Max / Min: `O(1)` * Insert: `O(log(n))` * Remove Max / Min: `O(log(n))` Max Heap ### Hashing * *Hashing* is used to map data of an arbitrary size to data of a fixed size. The values returned by a hash function are called hash values, hash codes, or simply hashes. If two keys map to the same value, a collision occurs * **Hash Map**: a *hash map* is a structure that can map keys to values. A hash map uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. * Collision Resolution * **Separate Chaining**: in *separate chaining*, each bucket is independent, and contains a list of entries for each index. The time for hash map operations is the time to find the bucket (constant time), plus the time to iterate through the list * **Open Addressing**: in *open addressing*, when a new entry is inserted, the buckets are examined, starting with the hashed-to-slot and proceeding in some sequence, until an unoccupied slot is found. The name open addressing refers to the fact that the location of an item is not always determined by its hash value ![Alt text](/images/hash.png?raw=true "Hashing") ### Graph * A *Graph* is an ordered pair of G = (V, E) comprising a set V of vertices or nodes together with a set E of edges or arcs, which are 2-element subsets of V (i.e. an edge is associated with two vertices, and that association takes the form of the unordered pair comprising those two vertices) * **Undirected Graph**: a graph in which the adjacency relation is symmetric. So if there exists an edge from node u to node v (u -> v), then it is also the case that there exists an edge from node v to node u (v -> u) * **Directed Graph**: a graph in which the adjacency relation is not symmetric. So if there exists an edge from node u to node v (u -> v), this does *not* imply that there exists an edge from node v to node u (v -> u) Graph ## Algorithms ### Sorting #### Quicksort * Stable: `No` * Time Complexity: * Best Case: `O(nlog(n))` * Worst Case: `O(n^2)` * Average Case: `O(nlog(n))` ![Alt text](/images/quicksort.gif?raw=true "Quicksort") #### Mergesort * *Mergesort* is also a divide and conquer algorithm. It continuously divides an array into two halves, recurses on both the left subarray and right subarray and then merges the two sorted halves * Stable: `Yes` * Time Complexity: * Best Case: `O(nlog(n))` * Worst Case: `O(nlog(n))` * Average Case: `O(nlog(n))` ![Alt text](/images/mergesort.gif?raw=true "Mergesort") #### Bucket Sort * *Bucket Sort* is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm * Time Complexity: * Best Case: `Ω(n + k)` * Worst Case: `O(n^2)` * Average Case:`Θ(n + k)` ![Alt text](/images/bucketsort.png?raw=true "Bucket Sort") #### Radix Sort * *Radix Sort* is a sorting algorithm that like bucket sort, distributes elements of an array into a number of buckets. However, radix sort differs from bucket sort by 're-bucketing' the array after the initial pass as opposed to sorting each bucket and merging * Time Complexity: * Best Case: `Ω(nk)` * Worst Case: `O(nk)` * Average Case: `Θ(nk)` ### Graph Algorithms #### Depth First Search * *Depth First Search* is a graph traversal algorithm which explores as far as possible along each branch before backtracking * Time Complexity: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### Breadth First Search * *Breadth First Search* is a graph traversal algorithm which explores the neighbor nodes first, before moving to the next level neighbors * Time Complexity: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### Topological Sort * *Topological Sort* is the linear ordering of a directed graph's nodes such that for every edge from node u to node v, u comes before v in the ordering * Time Complexity: `O(|V| + |E|)` #### Dijkstra's Algorithm * *Dijkstra's Algorithm* is an algorithm for finding the shortest path between nodes in a graph * Time Complexity: `O(|V|^2)` ![Alt text](/images/dijkstra.gif?raw=true "Dijkstra's") #### Bellman-Ford Algorithm * *Bellman-Ford Algorithm* is an algorithm that computes the shortest paths from a single source node to all other nodes in a weighted graph * Although it is slower than Dijkstra's, it is more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers * Time Complexity: * Best Case: `O(|E|)` * Worst Case: `O(|V||E|)` ![Alt text](/images/bellman-ford.gif?raw=true "Bellman-Ford") #### Floyd-Warshall Algorithm * *Floyd-Warshall Algorithm* is an algorithm for finding the shortest paths in a weighted graph with positive or negative edge weights, but no negative cycles * A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between *all* pairs of nodes * Time Complexity: * Best Case: `O(|V|^3)` * Worst Case: `O(|V|^3)` * Average Case: `O(|V|^3)` #### Prim's Algorithm * *Prim's Algorithm* is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. In other words, Prim's find a subset of edges that forms a tree that includes every node in the graph * Time Complexity: `O(|V|^2)` ![Alt text](/images/prim.gif?raw=true "Prim's Algorithm") #### Kruskal's Algorithm * *Kruskal's Algorithm* is also a greedy algorithm that finds a minimum spanning tree in a graph. However, in Kruskal's, the graph does not have to be connected * Time Complexity: `O(|E|log|V|)` ![Alt text](/images/kruskal.gif?raw=true "Kruskal's Algorithm") ## Greedy Algorithms * *Greedy Algorithms* are algorithms that make locally optimal choices at each step in the hope of eventually reaching the globally optimal solution * Problems must exhibit two properties in order to implement a Greedy solution: * Optimal Substructure * An optimal solution to the problem contains optimal solutions to the given problem's subproblems * The Greedy Property * An optimal solution is reached by "greedily" choosing the locally optimal choice without ever reconsidering previous choices * Example - Coin Change * Given a target amount V cents and a list of denominations of n coins, i.e. we have coinValue[i] (in cents) for coin types i from [0...n - 1], what is the minimum number of coins that we must use to represent amount V? Assume that we have an unlimited supply of coins of any type * Coins - Penny (1 cent), Nickel (5 cents), Dime (10 cents), Quarter (25 cents) * Assume V = 41. We can use the Greedy algorithm of continuously selecting the largest coin denomination less than or equal to V, subtract that coin's value from V, and repeat. * V = 41 | 0 coins used * V = 16 | 1 coin used (41 - 25 = 16) * V = 6 | 2 coins used (16 - 10 = 6) * V = 1 | 3 coins used (6 - 5 = 1) * V = 0 | 4 coins used (1 - 1 = 0) * Using this algorithm, we arrive at a total of 4 coins which is optimal ## Bitmasks * Bitmasking is a technique used to perform operations at the bit level. Leveraging bitmasks often leads to faster runtime complexity and helps limit memory usage * Test kth bit: `s & (1 << k);` * Set kth bit: `s |= (1 << k);` * Turn off kth bit: `s &= ~(1 << k);` * Toggle kth bit: `s ^= (1 << k);` * Multiple by 2n: `s << n;` * Divide by 2n: `s >> n;` * Intersection: `s & t;` * Union: `s | t;` * Set Subtraction: `s & ~t;` * Extract lowest set bit: `s & (-s);` * Extract lowest unset bit: `~s & (s + 1);` * Swap Values: ``` x ^= y; y ^= x; x ^= y; ``` ## Runtime Analysis #### Big O Notation * *Big O Notation* is used to describe the upper bound of a particular algorithm. Big O is used to describe worst case scenarios ![Alt text](/images/bigO.png?raw=true "Theta Notation") #### Little O Notation * *Little O Notation* is also used to describe an upper bound of a particular algorithm; however, Little O provides a bound that is not asymptotically tight #### Big Ω Omega Notation * *Big Omega Notation* is used to provide an asymptotic lower bound on a particular algorithm ![Alt text](/images/bigOmega.png?raw=true "Theta Notation") #### Little ω Omega Notation * *Little Omega Notation* is used to provide a lower bound on a particular algorithm that is not asymptotically tight #### Theta Θ Notation * *Theta Notation* is used to provide a bound on a particular algorithm such that it can be "sandwiched" between two constants (one for an upper limit and one for a lower limit) for sufficiently large values ![Alt text](/images/theta.png?raw=true "Theta Notation") ## Video Lectures * Data Structures * [UC Berkeley Data Structures](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22) * [MIT Advanced Data Structures](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf&index=1) * Algorithms * [MIT Introduction to Algorithms](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&index=1) * [MIT Advanced Algorithms](https://www.youtube.com/playlist?list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c) * [UC Berkeley Algorithms](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22) ## Interview Books * [Competitive Programming 3 - Steven Halim & Felix Halim](https://www.amazon.com/Competitive-Programming-3rd-Steven-Halim/dp/B00FG8MNN8) * [Cracking The Coding Interview - Gayle Laakmann McDowell](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?s=books&ie=UTF8) * [Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro](https://www.amazon.com/Cracking-PM-Interview-Product-Technology-ebook/dp/B00ISYMUR6/ref=sr_1_1?s=books&ie=UTF8) * [Introduction to Algorithms - Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest & Clifford Stein](https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/ref=sr_1_1?ie=UTF8&qid=1490295989&sr=8-1&keywords=Introduction+to+Algorithms) ## Computer Science News * [Hacker News](https://news.ycombinator.com/) * [Lobsters](https://lobste.rs/) ## Directory Tree ``` . ├── Array │   ├── bestTimeToBuyAndSellStock.java │   ├── findTheCelebrity.java │   ├── gameOfLife.java │   ├── increasingTripletSubsequence.java │   ├── insertInterval.java │   ├── longestConsecutiveSequence.java │   ├── maximumProductSubarray.java │   ├── maximumSubarray.java │   ├── mergeIntervals.java │   ├── missingRanges.java │   ├── productOfArrayExceptSelf.java │   ├── rotateImage.java │   ├── searchInRotatedSortedArray.java │   ├── spiralMatrixII.java │   ├── subsetsII.java │   ├── subsets.java │   ├── summaryRanges.java │   ├── wiggleSort.java │   └── wordSearch.java ├── Backtracking │   ├── androidUnlockPatterns.java │   ├── generalizedAbbreviation.java │   └── letterCombinationsOfAPhoneNumber.java ├── BinarySearch │   ├── closestBinarySearchTreeValue.java │   ├── firstBadVersion.java │   ├── guessNumberHigherOrLower.java │   ├── pow(x,n).java │   └── sqrt(x).java ├── BitManipulation │   ├── binaryWatch.java │   ├── countingBits.java │   ├── hammingDistance.java │   ├── maximumProductOfWordLengths.java │   ├── numberOf1Bits.java │   ├── sumOfTwoIntegers.java │   └── utf-8Validation.java ├── BreadthFirstSearch │   ├── binaryTreeLevelOrderTraversal.java │   ├── cloneGraph.java │   ├── pacificAtlanticWaterFlow.java │   ├── removeInvalidParentheses.java │   ├── shortestDistanceFromAllBuildings.java │   ├── symmetricTree.java │   └── wallsAndGates.java ├── DepthFirstSearch │   ├── balancedBinaryTree.java │   ├── battleshipsInABoard.java │   ├── convertSortedArrayToBinarySearchTree.java │   ├── maximumDepthOfABinaryTree.java │   ├── numberOfIslands.java │   ├── populatingNextRightPointersInEachNode.java │   └── sameTree.java ├── Design │   └── zigzagIterator.java ├── DivideAndConquer │   ├── expressionAddOperators.java │   └── kthLargestElementInAnArray.java ├── DynamicProgramming │   ├── bombEnemy.java │   ├── climbingStairs.java │   ├── combinationSumIV.java │   ├── countingBits.java │   ├── editDistance.java │   ├── houseRobber.java │   ├── paintFence.java │   ├── paintHouseII.java │   ├── regularExpressionMatching.java │   ├── sentenceScreenFitting.java │   ├── uniqueBinarySearchTrees.java │   └── wordBreak.java ├── HashTable │   ├── binaryTreeVerticalOrderTraversal.java │   ├── findTheDifference.java │   ├── groupAnagrams.java │   ├── groupShiftedStrings.java │   ├── islandPerimeter.java │   ├── loggerRateLimiter.java │   ├── maximumSizeSubarraySumEqualsK.java │   ├── minimumWindowSubstring.java │   ├── sparseMatrixMultiplication.java │   ├── strobogrammaticNumber.java │   ├── twoSum.java │   └── uniqueWordAbbreviation.java ├── LinkedList │   ├── addTwoNumbers.java │   ├── deleteNodeInALinkedList.java │   ├── mergeKSortedLists.java │   ├── palindromeLinkedList.java │   ├── plusOneLinkedList.java │   ├── README.md │   └── reverseLinkedList.java ├── Queue │   └── movingAverageFromDataStream.java ├── README.md ├── Sort │   ├── meetingRoomsII.java │   └── meetingRooms.java ├── Stack │   ├── binarySearchTreeIterator.java │   ├── decodeString.java │   ├── flattenNestedListIterator.java │   └── trappingRainWater.java ├── String │   ├── addBinary.java │   ├── countAndSay.java │   ├── decodeWays.java │   ├── editDistance.java │   ├── integerToEnglishWords.java │   ├── longestPalindrome.java │   ├── longestSubstringWithAtMostKDistinctCharacters.java │   ├── minimumWindowSubstring.java │   ├── multiplyString.java │   ├── oneEditDistance.java │   ├── palindromePermutation.java │   ├── README.md │   ├── reverseVowelsOfAString.java │   ├── romanToInteger.java │   ├── validPalindrome.java │   └── validParentheses.java ├── Tree │   ├── binaryTreeMaximumPathSum.java │   ├── binaryTreePaths.java │   ├── inorderSuccessorInBST.java │   ├── invertBinaryTree.java │   ├── lowestCommonAncestorOfABinaryTree.java │   ├── sumOfLeftLeaves.java │   └── validateBinarySearchTree.java ├── Trie │   ├── addAndSearchWordDataStructureDesign.java │   ├── implementTrie.java │   └── wordSquares.java └── TwoPointers ├── 3Sum.java ├── 3SumSmaller.java ├── mergeSortedArray.java ├── minimumSizeSubarraySum.java ├── moveZeros.java ├── removeDuplicatesFromSortedArray.java ├── reverseString.java └── sortColors.java 18 directories, 124 files ``` ================================================ FILE: company/Company.iml ================================================ ================================================ FILE: company/adobe/AddDigits.java ================================================ //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } } ================================================ FILE: company/adobe/MajorityElement.java ================================================ //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. //You may assume that the array is non-empty and the majority element always exist in the array. class MajorityElement { public int majorityElement(int[] nums) { if(nums.length == 1) { return nums[0]; } HashMap map = new HashMap(); for(int current: nums) { if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) { return current; } else if(map.containsKey(current)) { map.put(current, map.get(current) + 1); } else { map.put(current, 1); } } //no majority element exists return -1; } } ================================================ FILE: company/airbnb/AddTwoNumbers.java ================================================ // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 0 -> 8 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode current1 = l1; ListNode current2 = l2; ListNode head = new ListNode(0); ListNode currentHead = head; int sum = 0; while(current1 != null || current2 != null) { sum /= 10; if(current1 != null) { sum += current1.val; current1 = current1.next; } if(current2 != null) { sum += current2.val; current2 = current2.next; } currentHead.next = new ListNode(sum % 10); currentHead = currentHead.next; } if(sum / 10 == 1) { currentHead.next = new ListNode(1); } return head.next; } } ================================================ FILE: company/airbnb/ContainsDuplicate.java ================================================ //Given an array of integers, find if the array contains any duplicates. Your function should return //true if any value appears at least twice in the array, and it should return false if every element is distinct. class ContainsDuplicate { public boolean containsDuplicate(int[] nums) { HashMap map = new HashMap(); for(int i: nums) { if(map.containsKey(i)) { return true; } else { map.put(i, 1); } } return false; } } ================================================ FILE: company/airbnb/ContainsDuplicatesII.java ================================================ //Given an array of integers and an integer k, find out whether there are two distinct indices i and //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class ContainsDuplicatesII { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap(); for(int i = 0; i < nums.length; i++) { int current = nums[i]; if(map.containsKey(current) && i - map.get(current) <= k) { return true; } else { map.put(current, i); } } return false; } } ================================================ FILE: company/airbnb/ConvertSortedArrayToBinarySearchTree.java ================================================ // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = helper(nums, 0, nums.length - 1); return root; } private TreeNode helper(int[] nums, int start, int end) { if(start <= end) { int mid = (start + end) / 2; TreeNode current = new TreeNode(nums[mid]); current.left = helper(nums, start, mid - 1); current.right = helper(nums, mid + 1, end); return current; } return null; } } ================================================ FILE: company/airbnb/HouseRobber.java ================================================ // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. public class HouseRobber { public int rob(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; for(int i = 2; i < nums.length; i++) { dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); } return dp[dp.length - 1]; } } ================================================ FILE: company/airbnb/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: company/airbnb/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '{') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: company/amazon/3Sum.java ================================================ // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // Note: The solution set must not contain duplicate triplets. // For example, given array S = [-1, 0, 1, 2, -1, -4], // A solution set is: // [ // [-1, 0, 1], // [-1, -1, 2] // ] public class 3Sum { public List> threeSum(int[] nums) { List> result = new ArrayList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; int target = -nums[i]; while(j < k) { if(nums[j] + nums[k] == target) { ArrayList temp = new ArrayList(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); result.add(temp); j++; k--; while(j < k && nums[j] == nums[j - 1]) { j++; } while(j < k && nums[k] == nums[k + 1]) { k--; } } else if(nums[j] + nums[k] > target) { k--; } else { j++; } } } return result; } } ================================================ FILE: company/amazon/AddTwoNumbers.java ================================================ // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 0 -> 8 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode current1 = l1; ListNode current2 = l2; ListNode head = new ListNode(0); ListNode currentHead = head; int sum = 0; while(current1 != null || current2 != null) { sum /= 10; if(current1 != null) { sum += current1.val; current1 = current1.next; } if(current2 != null) { sum += current2.val; current2 = current2.next; } currentHead.next = new ListNode(sum % 10); currentHead = currentHead.next; } if(sum / 10 == 1) { currentHead.next = new ListNode(1); } return head.next; } } ================================================ FILE: company/amazon/BestTimeToBuyAndSellStock.java ================================================ // Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Example 1: // Input: [7, 1, 5, 3, 6, 4] // Output: 5 // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) // Example 2: // Input: [7, 6, 4, 3, 1] // Output: 0 // In this case, no transaction is done, i.e. max profit = 0. public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { //Kadane's algorithm if(prices.length == 0) { return 0; } int max = 0; int min = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] > min) { max = Math.max(max, prices[i] - min); } else { min = prices[i]; } } return max; } } ================================================ FILE: company/amazon/BinaryTreeLevelOrderTraversal.java ================================================ // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree [3,9,20,null,null,15,7], // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeLevelOrderTraversal { public List> levelOrder(TreeNode root) { List> result = new ArrayList>(); if(root == null) { return result; } Queue queue = new LinkedList(); queue.add(root); List tempList = new ArrayList(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue currentLevel = new LinkedList(); List list = new ArrayList(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; } } ================================================ FILE: company/amazon/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: company/amazon/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: company/amazon/GroupAnagrams.java ================================================ // Given an array of strings, group anagrams together. // For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], // Return: // [ // ["ate", "eat","tea"], // ["nat","tan"], // ["bat"] // ] // Note: All inputs will be in lower-case. public class GroupAnagrams { public List> groupAnagrams(String[] strs) { if(strs == null || strs.length == 0) { return new ArrayList>(); } HashMap> map = new HashMap>(); Arrays.sort(strs); for(String s : strs) { char[] characters = s.toCharArray(); Arrays.sort(characters); String key = String.valueOf(characters); if(!map.containsKey(key)) { map.put(key, new ArrayList()); } map.get(key).add(s); } return new ArrayList>(map.values()); } } ================================================ FILE: company/amazon/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/amazon/KthLargestElementInAnArray.java ================================================ // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. // For example, // Given [3,2,1,5,6,4] and k = 2, return 5. // Note: // You may assume k is always valid, 1 ≤ k ≤ array's length. public class KthLargestElementInAnArray { public int findKthLargest(int[] nums, int k) { int length = nums.length; Arrays.sort(nums); return nums[length - k]; } } ================================================ FILE: company/amazon/LetterCombinationsOfAPhoneNumber.java ================================================ // Given a digit string, return all possible letter combinations that the number could represent. // A mapping of digit to letters (just like on the telephone buttons) is given below. // 2 - abc // 3 - def // 4 - ghi // 5 - jkl // 6 - mno // 7 - pqrs // 8 - tuv // 9 - wxyz // Input:Digit string "23" // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class LetterCombinationsOfAPhoneNumber { public List letterCombinations(String digits) { List result = new ArrayList(); if(digits == null || digits.length() == 0) { return result; } String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; letterCombinationsRecursive(result, digits, "", 0, mapping); return result; } public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) { if(index == digits.length()) { result.add(current); return; } String letters = mapping[digits.charAt(index) - '0']; for(int i = 0; i < letters.length(); i++) { letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); } } } ================================================ FILE: company/amazon/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: company/amazon/LongestPalindromicSubstring.java ================================================ //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. //Example: //Input: "babad" //Output: "bab" //Note: "aba" is also a valid answer. //Example: //Input: "cbbd" //Output: "bb" class LongestPalindromicSubstring { public String longestPalindrome(String s) { if(s == null || s.length() == 0) { return ""; } String longestPalindromicSubstring = ""; for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) { longestPalindromicSubstring = s.substring(i, j); } } } return longestPalindromicSubstring; } public boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; while(i <= j) { if(s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } } ================================================ FILE: company/amazon/LowestCommonAncestorOfABinaryTree.java ================================================ // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } } ================================================ FILE: company/amazon/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { return 0; } //set current index to 0 grid[i][j] = '0'; // sink all neighbors of current index sink(grid, i + 1, j); sink(grid, i - 1, j); sink(grid, i, j + 1); sink(grid, i, j - 1); //increment number of islands return 1; } } ================================================ FILE: company/amazon/PalindromeLinkedList.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class PalindromeLinkedList { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) { return true; } Stack stack = new Stack(); ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null) { stack.push(slow.val); fast = fast.next.next; slow = slow.next; } if(fast != null) { slow = slow.next; } while(slow != null) { if(stack.pop() != slow.val) { return false; } slow = slow.next; } return true; } } ================================================ FILE: company/amazon/ProductOfArrayExceptSelf.java ================================================ // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. // Solve it without division and in O(n). // For example, given [1,2,3,4], return [24,12,8,6]. // Follow up: // Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n]; int left = 1; for(int i = 0; i < nums.length; i++) { if(i > 0) { left *= nums[i - 1]; } result[i] = left; } int right = 1; for(int i = n - 1; i >= 0; i--) { if(i < n - 1) { right *= nums[i + 1]; } result[i] *= right; } return result; } } ================================================ FILE: company/amazon/ReverseLinkedList.java ================================================ // Reverse a singly linked list. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } } ================================================ FILE: company/amazon/RotateImage.java ================================================ // You are given an n x n 2D matrix representing an image. // Rotate the image by 90 degrees (clockwise). // Follow up: // Could you do this in-place? public class RotateImage { public void rotate(int[][] matrix) { for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < i; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length / 2; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[i][matrix[0].length - 1 - j]; matrix[i][matrix[0].length - 1 - j] = temp; } } } } ================================================ FILE: company/amazon/Subsets.java ================================================ // Given a set of distinct integers, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] public class Subsets { public List> subsets(int[] nums) { List> result = new ArrayList<>(); recurse(result, nums, new Stack<>(), 0); return result; } private void recurse(List> result, int[] nums, Stack path, int position) { if(position == nums.length) { result.add(new ArrayList<>(path)); return; } path.push(nums[position]); recurse(result, nums, path, position + 1); path.pop(); recurse(result, nums, path, position + 1); } } ================================================ FILE: company/amazon/TrappingRainWater.java ================================================ // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // For example, // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. public class TrappingRainWater { public int trap(int[] height) { int water = 0; int leftIndex = 0; int rightIndex = height.length - 1; int leftMax = 0; int rightMax = 0; while(leftIndex <= rightIndex) { leftMax = Math.max(leftMax, height[leftIndex]); rightMax = Math.max(rightMax, height[rightIndex]); if(leftMax < rightMax) { water += leftMax - height[leftIndex]; leftIndex++; } else { water += rightMax - height[rightIndex]; rightIndex--; } } return water; } } ================================================ FILE: company/amazon/TwoSum.java ================================================ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // Example: // Given nums = [2, 7, 11, 15], target = 9, // Because nums[0] + nums[1] = 2 + 7 = 9, // return [0, 1]. public class TwoSum { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: company/amazon/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: company/amazon/ValidateBinarySearchTree.java ================================================ // Given a binary tree, determine if it is a valid binary search tree (BST). // Assume a BST is defined as follows: // The left subtree of a node contains only nodes with keys less than the node's key. // The right subtree of a node contains only nodes with keys greater than the node's key. // Both the left and right subtrees must also be binary search trees. // Example 1: // 2 // / \ // 1 3 // Binary tree [2,1,3], return true. // Example 2: // 1 // / \ // 2 3 // Binary tree [1,2,3], return false. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ValidateBinarySearchTree { public boolean isValidBST(TreeNode root) { if(root == null) { return true; } return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) { if(root == null) { return true; } else if(root.val >= maxValue || root.val <= minValue) { return false; } else { return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue); } } } ================================================ FILE: company/amazon/WordBreak.java ================================================ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } } ================================================ FILE: company/apple/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: company/apple/ValidSudoku.java ================================================ //Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx) //The Sudoku board could be partially filled, where empty cells are filled with the character '.'. //A partially filled sudoku which is valid. //Note: //A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. class ValidSudoku { public boolean isValidSudoku(char[][] board) { for(int i = 0; i < board.length; i++){ HashSet rows = new HashSet(); HashSet columns = new HashSet(); HashSet box = new HashSet(); for (int j = 0; j < board[0].length; j++){ if(board[i][j] != '.' && !rows.add(board[i][j])) { return false; } if(board[j][i]!='.' && !columns.add(board[j][i])) { return false; } int rowIndex = (i / 3) * 3; int columnIndex = (i % 3) * 3; if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) { return false; } } } return true; } } ================================================ FILE: company/bloomberg/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: company/bloomberg/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: company/bloomberg/LongestPalindromicSubstring.java ================================================ //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. //Example: //Input: "babad" //Output: "bab" //Note: "aba" is also a valid answer. //Example: //Input: "cbbd" //Output: "bb" class LongestPalindromicSubstring { public String longestPalindrome(String s) { if(s == null || s.length() == 0) { return ""; } String longestPalindromicSubstring = ""; for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) { longestPalindromicSubstring = s.substring(i, j); } } } return longestPalindromicSubstring; } public boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; while(i <= j) { if(s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } } ================================================ FILE: company/bloomberg/MinStack.java ================================================ //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: company/bloomberg/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: company/bloomberg/UniquePaths.java ================================================ //A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } } ================================================ FILE: company/facebook/3Sum.java ================================================ // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // Note: The solution set must not contain duplicate triplets. // For example, given array S = [-1, 0, 1, 2, -1, -4], // A solution set is: // [ // [-1, 0, 1], // [-1, -1, 2] // ] public class 3Sum { public List> threeSum(int[] nums) { List> result = new ArrayList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; int target = -nums[i]; while(j < k) { if(nums[j] + nums[k] == target) { ArrayList temp = new ArrayList(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); result.add(temp); j++; k--; while(j < k && nums[j] == nums[j - 1]) { j++; } while(j < k && nums[k] == nums[k + 1]) { k--; } } else if(nums[j] + nums[k] > target) { k--; } else { j++; } } } return result; } } ================================================ FILE: company/facebook/AddAndSearchWordDataStructureDesign.java ================================================ // Design a data structure that supports the following two operations: // void addWord(word) // bool search(word) // search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. // For example: // addWord("bad") // addWord("dad") // addWord("mad") // search("pad") -> false // search("bad") -> true // search(".ad") -> true // search("b..") -> true // Note: // You may assume that all words are consist of lowercase letters a-z. public class AddAndSearchWordDataStructure { public class TrieNode { public TrieNode[] children = new TrieNode[26]; public String item = ""; } private TrieNode root = new TrieNode(); public void addWord(String word) { TrieNode node = root; for (char c : word.toCharArray()) { if (node.children[c - 'a'] == null) { node.children[c - 'a'] = new TrieNode(); } node = node.children[c - 'a']; } node.item = word; } public boolean search(String word) { return match(word.toCharArray(), 0, root); } private boolean match(char[] chs, int k, TrieNode node) { if (k == chs.length) { return !node.item.equals(""); } if (chs[k] != '.') { return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']); } else { for (int i = 0; i < node.children.length; i++) { if (node.children[i] != null) { if (match(chs, k + 1, node.children[i])) { return true; } } } } return false; } } ================================================ FILE: company/facebook/AddBinary.java ================================================ // Given two binary strings, return their sum (also a binary string). // For example, // a = "11" // b = "1" // Return "100" public class AddBinary { public String addBinary(String a, String b) { StringBuilder result = new StringBuilder(); int carry = 0; int i = a.length() - 1; int j = b.length() - 1; while(i >= 0 || j >= 0) { int sum = carry; if(i >= 0) { sum += a.charAt(i--) - '0'; } if(j >= 0) { sum += b.charAt(j--) - '0'; } result.append(sum % 2); carry = sum / 2; } if(carry != 0) { result.append(carry); } return result.reverse().toString(); } } ================================================ FILE: company/facebook/BestTimeToBuyAndSellStock.java ================================================ // Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Example 1: // Input: [7, 1, 5, 3, 6, 4] // Output: 5 // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) // Example 2: // Input: [7, 6, 4, 3, 1] // Output: 0 // In this case, no transaction is done, i.e. max profit = 0. public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { //Kadane's algorithm if(prices.length == 0) { return 0; } int max = 0; int min = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] > min) { max = Math.max(max, prices[i] - min); } else { min = prices[i]; } } return max; } } ================================================ FILE: company/facebook/BinarySearchTreeIterator.java ================================================ // Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. // Calling next() will return the next smallest number in the BST. // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeIterator { Stack stack; public BSTIterator(TreeNode root) { stack = new Stack(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/facebook/BinaryTreeLevelOrderTraversal.java ================================================ // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree [3,9,20,null,null,15,7], // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeLevelOrderTraversal { public List> levelOrder(TreeNode root) { List> result = new ArrayList>(); if(root == null) { return result; } Queue queue = new LinkedList(); queue.add(root); List tempList = new ArrayList(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue currentLevel = new LinkedList(); List list = new ArrayList(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; } } ================================================ FILE: company/facebook/BinaryTreePaths.java ================================================ // Given a binary tree, return all root-to-leaf paths. // For example, given the following binary tree: // 1 // / \ // 2 3 // \ // 5 // All root-to-leaf paths are: // ["1->2->5", "1->3"] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreePaths { public List binaryTreePaths(TreeNode root) { List result = new ArrayList(); if(root == null) { return result; } helper(new String(), root, result); return result; } public void helper(String current, TreeNode root, List result) { if(root.left == null && root.right == null) { result.add(current + root.val); } if(root.left != null) { helper(current + root.val + "->", root.left, result); } if(root.right != null) { helper(current + root.val + "->", root.right, result); } } } ================================================ FILE: company/facebook/BinaryTreeVerticalOrderTraversal.java ================================================ // Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). // If two nodes are in the same row and column, the order should be from left to right. // Examples: // Given binary tree [3,9,20,null,null,15,7], // 3 // /\ // / \ // 9 20 // /\ // / \ // 15 7 // return its vertical order traversal as: // [ // [9], // [3,15], // [20], // [7] // ] // Given binary tree [3,9,8,4,0,1,7], // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // return its vertical order traversal as: // [ // [4], // [9], // [3,0,1], // [8], // [7] // ] // Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // /\ // / \ // 5 2 // return its vertical order traversal as: // [ // [4], // [9,5], // [3,0,1], // [8,2], // [7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeVerticalOrderTraversal { public List> verticalOrder(TreeNode root) { List> result = new ArrayList<>(); if(root == null) { return result; } Map> map = new HashMap<>(); Queue q = new LinkedList<>(); Queue cols = new LinkedList<>(); q.add(root); cols.add(0); int min = 0; int max = 0; while(!q.isEmpty()) { TreeNode node = q.poll(); int col = cols.poll(); if(!map.containsKey(col)) { map.put(col, new ArrayList()); } map.get(col).add(node.val); if(node.left != null) { q.add(node.left); cols.add(col - 1); min = Math.min(min, col - 1); } if(node.right != null) { q.add(node.right); cols.add(col + 1); max = Math.max(max, col + 1); } } for(int i = min; i <= max; i++) { result.add(map.get(i)); } return result; } } ================================================ FILE: company/facebook/CloneGraph.java ================================================ // Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } * }; */ public class CloneGraph { public HashMap map = new HashMap(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } } ================================================ FILE: company/facebook/CombinationSumIV.java ================================================ // Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. // Example: // nums = [1, 2, 3] // target = 4 // The possible combination ways are: // (1, 1, 1, 1) // (1, 1, 2) // (1, 2, 1) // (1, 3) // (2, 1, 1) // (2, 2) // (3, 1) // Note that different sequences are counted as different combinations. // Therefore the output is 7. // Follow up: // What if negative numbers are allowed in the given array? // How does it change the problem? // What limitation we need to add to the question to allow negative numbers? public class Solution { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < nums.length; j++) { if(i - nums[j] >= 0) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } } ================================================ FILE: company/facebook/CountAndSay.java ================================================ // The count-and-say sequence is the sequence of integers beginning as follows: // 1, 11, 21, 1211, 111221, ... // 1 is read off as "one 1" or 11. // 11 is read off as "two 1s" or 21. // 21 is read off as "one 2, then one 1" or 1211. // Given an integer n, generate the nth sequence. // Note: The sequence of integers will be represented as a string. public class Solution { public String countAndSay(int n) { String s = "1"; for(int i = 1; i < n; i++) { s = helper(s); } return s; } public String helper(String s) { StringBuilder sb = new StringBuilder(); char c = s.charAt(0); int count = 1; for(int i = 1; i < s.length(); i++) { if(s.charAt(i) == c) count++; else { sb.append(count); sb.append(c); c = s.charAt(i); count = 1; } } sb.append(count); sb.append(c); return sb.toString(); } } ================================================ FILE: company/facebook/DecodeWays.java ================================================ // A message containing letters from A-Z is being encoded to numbers using the following mapping: // 'A' -> 1 // 'B' -> 2 // ... // 'Z' -> 26 // Given an encoded message containing digits, determine the total number of ways to decode it. // For example, // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). // The number of ways decoding "12" is 2. public class DecodeWays { public int numDecodings(String s) { int n = s.length(); if(n == 0) { return 0; } int[] dp = new int[n + 1]; dp[n] = 1; dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; for(int i = n - 2; i >= 0; i--) { if(s.charAt(i) == '0') { continue; } else { dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; } } return dp[0]; } } ================================================ FILE: company/facebook/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: company/facebook/ExclusiveTimeOfFunctions.java ================================================ //Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List logs) { Stack stack = new Stack (); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } } ================================================ FILE: company/facebook/ExpressionAddOperators.java ================================================ // Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. // Examples: // "123", 6 -> ["1+2+3", "1*2*3"] // "232", 8 -> ["2*3+2", "2+3*2"] // "105", 5 -> ["1*0+5","10-5"] // "00", 0 -> ["0+0", "0-0", "0*0"] // "3456237490", 9191 -> [] public class ExpressionAddOperators { public List addOperators(String num, int target) { List result = new ArrayList(); if(num == null || num.length() == 0) { return result; } helper(result, "", num, target, 0, 0, 0); return result; } public void helper(List result, String path, String num, int target, int pos, long eval, long multed) { if(pos == num.length()) { if(eval == target) { result.add(path); } return; } for(int i = pos; i < num.length(); i++) { if(i != pos && num.charAt(pos) == '0') { break; } long cur = Long.parseLong(num.substring(pos, i + 1)); if(pos == 0) { helper(result, path + cur, num, target, i + 1, cur, cur); } else { helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur); helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur); helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur); } } } } ================================================ FILE: company/facebook/FindTheCelebrity.java ================================================ // Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } } ================================================ FILE: company/facebook/FirstBadVersion.java ================================================ // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. // You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class FirstBadVersion extends VersionControl { public int firstBadVersion(int n) { int start = 1; int end = n; while(start < end) { int mid = start + (end - start) / 2; if(!isBadVersion(mid)) { start = mid + 1; } else { end = mid; } } return start; } } ================================================ FILE: company/facebook/FlattenNestedListIterator.java ================================================ // Given a nested list of integers, implement an iterator to flatten it. // Each element is either an integer, or a list -- whose elements may also be integers or other lists. // Example 1: // Given the list [[1,1],2,[1,1]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. // Example 2: // Given the list [1,[4,[6]]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List getList(); * } */ public class FlattenNestedListIterator implements Iterator { Stack stack = new Stack(); public NestedIterator(List nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger current = stack.peek(); if(current.isInteger()) { return true; } stack.pop(); for(int i = current.getList().size() - 1; i >= 0; i--) { stack.push(current.getList().get(i)); } } return false; } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/facebook/GroupAnagrams.java ================================================ // Given an array of strings, group anagrams together. // For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], // Return: // [ // ["ate", "eat","tea"], // ["nat","tan"], // ["bat"] // ] // Note: All inputs will be in lower-case. public class GroupAnagrams { public List> groupAnagrams(String[] strs) { if(strs == null || strs.length == 0) { return new ArrayList>(); } HashMap> map = new HashMap>(); Arrays.sort(strs); for(String s : strs) { char[] characters = s.toCharArray(); Arrays.sort(characters); String key = String.valueOf(characters); if(!map.containsKey(key)) { map.put(key, new ArrayList()); } map.get(key).add(s); } return new ArrayList>(map.values()); } } ================================================ FILE: company/facebook/HammingDistance.java ================================================ // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. // Given two integers x and y, calculate the Hamming distance. // Note: // 0 ≤ x, y < 2^31. // Example: // Input: x = 1, y = 4 // Output: 2 // Explanation: // 1 (0 0 0 1) // 4 (0 1 0 0) // ↑ ↑ // The above arrows point to positions where the corresponding bits are different. public class HammingDistance { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } } ================================================ FILE: company/facebook/ImplementTrie.java ================================================ // Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap(); this.character = character; this.last = false; } } public class ImplementTrie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } } ================================================ FILE: company/facebook/InorderSuccessorInBST.java ================================================ // Given a binary search tree and a node in it, find the in-order successor of that node in the BST. // Note: If the given node has no in-order successor in the tree, return null. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InorderSuccessorInBST { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode successor = null; while(root != null) { if(p.val < root.val) { successor = root; root = root.left; } else { root = root.right; } } return successor; } } ================================================ FILE: company/facebook/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/facebook/InsertInterval.java ================================================ // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). // You may assume that the intervals were initially sorted according to their start times. // Example 1: // Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. // Example 2: // Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. // This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class InsertInterval { public List insert(List intervals, Interval newInterval) { int i = 0; while(i < intervals.size() && intervals.get(i).end < newInterval.start) { i++; } while(i < intervals.size() && intervals.get(i).start <= newInterval.end) { newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end)); intervals.remove(i); } intervals.add(i, newInterval); return intervals; } } ================================================ FILE: company/facebook/IntegerToEnglishWords.java ================================================ // Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. // For example, // 123 -> "One Hundred Twenty Three" // 12345 -> "Twelve Thousand Three Hundred Forty Five" // 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" public class IntegerToEnglishWords { private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private final String[] TENS = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; private final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" }; public String numberToWords(int num) { if(num == 0) { return "Zero"; } int i = 0; String words = ""; while(num > 0) { if(num % 1000 != 0) { words = helper(num % 1000) + THOUSANDS[i] + " " + words; } num /= 1000; i++; } return words.trim(); } private String helper(int num) { if(num == 0) { return ""; } else if(num < 20) { return LESS_THAN_20[num] + " "; } else if(num < 100) { return TENS[num / 10] + " " + helper(num % 10); } else { return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); } } } ================================================ FILE: company/facebook/KthLargestElementInAnArray.java ================================================ // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. // For example, // Given [3,2,1,5,6,4] and k = 2, return 5. // Note: // You may assume k is always valid, 1 ≤ k ≤ array's length. public class KthLargestElementInAnArray { public int findKthLargest(int[] nums, int k) { int length = nums.length; Arrays.sort(nums); return nums[length - k]; } } ================================================ FILE: company/facebook/LetterCombinationsOfAPhoneNumber.java ================================================ // Given a digit string, return all possible letter combinations that the number could represent. // A mapping of digit to letters (just like on the telephone buttons) is given below. // 2 - abc // 3 - def // 4 - ghi // 5 - jkl // 6 - mno // 7 - pqrs // 8 - tuv // 9 - wxyz // Input:Digit string "23" // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class LetterCombinationsOfAPhoneNumber { public List letterCombinations(String digits) { List result = new ArrayList(); if(digits == null || digits.length() == 0) { return result; } String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; letterCombinationsRecursive(result, digits, "", 0, mapping); return result; } public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) { if(index == digits.length()) { result.add(current); return; } String letters = mapping[digits.charAt(index) - '0']; for(int i = 0; i < letters.length(); i++) { letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); } } } ================================================ FILE: company/facebook/LongestConsecutiveSequence.java ================================================ // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. // For example, // Given [100, 4, 200, 1, 3, 2], // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. // Your algorithm should run in O(n) complexity. class LongestConsecutiveSequence { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0) { return 0; } Set set = new HashSet(); for(int n: nums) { set.add(n); } int maxLength = 0; for(int n: set) { if(!set.contains(n - 1)) { int current = n; int currentMax = 1; while(set.contains(n + 1)) { currentMax++; n++; } maxLength = Math.max(maxLength, currentMax); } } return maxLength; } } ================================================ FILE: company/facebook/LowestCommonAncestorOfABinaryTree.java ================================================ // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorsOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } } ================================================ FILE: company/facebook/MaximumSizeSubarraySumEqualsK.java ================================================ // Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. // Note: // The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. // Example 1: // Given nums = [1, -1, 5, -2, 3], k = 3, // return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest) // Example 2: // Given nums = [-2, -1, 2, 1], k = 1, // return 2. (because the subarray [-1, 2] sums to 1 and is the longest) // Follow Up: // Can you do it in O(n) time? public class MaximumSizeSubarraySumEqualsK { public int maxSubArrayLen(int[] nums, int k) { if(nums.length == 0) { return 0; } HashMap map = new HashMap(); int maxLength = 0; int total = 0; map.put(0, -1); for(int i = 0; i < nums.length; i++) { total += nums[i]; if(map.containsKey(total - k)) { maxLength = Math.max(maxLength, i - map.get(total - k)); } if(!map.containsKey(total)) { map.put(total, i); } } return maxLength; } } ================================================ FILE: company/facebook/MeetingRooms.java ================================================ // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return false. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class MeetingRooms { public boolean canAttendMeetings(Interval[] intervals) { if(intervals == null) { return false; } // Sort the intervals by start time Arrays.sort(intervals, new Comparator() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); for(int i = 1; i < intervals.length; i++) { if(intervals[i].start < intervals[i - 1].end) { return false; } } return true; } } ================================================ FILE: company/facebook/MergeIntervals.java ================================================ // Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class MergeIntervals { public List merge(List intervals) { List result = new ArrayList(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } } ================================================ FILE: company/facebook/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val= 0 && j >= 0) { A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } while(j >= 0) { A[k--] = B[j--]; } } } ================================================ FILE: company/facebook/MinStack.java ================================================ /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: company/facebook/MinimumSizeSubarraySum.java ================================================ // Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. // For example, given the array [2,3,1,2,4,3] and s = 7, // the subarray [4,3] has the minimal length under the problem constraint. public class MinimumSizeSubarraySum { public int minSubArrayLen(int s, int[] nums) { if(nums == null || nums.length == 0) { return 0; } int i = 0; int j = 0; int result = Integer.MAX_VALUE; int total = 0; while(i < nums.length) { total += nums[i++]; while(total >= s) { result = Math.min(result, i - j); total -= nums[j++]; } } return result == Integer.MAX_VALUE ? 0 : result; } } ================================================ FILE: company/facebook/MinimumWindowSubstring.java ================================================ // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // For example, // S = "ADOBECODEBANC" // T = "ABC" // Minimum window is "BANC". // Note: // If there is no such window in S that covers all characters in T, return the empty string "". // If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. public class MinimumWindowSubstring { public String minWindow(String s, String t) { HashMap map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } } ================================================ FILE: company/facebook/MoveZeros.java ================================================ // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. // Note: // You must do this in-place without making a copy of the array. // Minimize the total number of operations. public class MoveZeros { public void moveZeroes(int[] nums) { if(nums == null || nums.length == 0) { return; } int index = 0; for(int num : nums) { if(num != 0) { nums[index] = num; index++; } } while(index < nums.length) { nums[index] = 0; index++; } } } ================================================ FILE: company/facebook/MultiplyStrings.java ================================================ // Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // Note: // The length of both num1 and num2 is < 110. // Both num1 and num2 contains only digits 0-9. // Both num1 and num2 does not contain any leading zero. // You must not use any built-in BigInteger library or convert the inputs to integer directly. public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } } ================================================ FILE: company/facebook/NumberOfIslands.java ================================================ // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. // Example 1: // 11110 // 11010 // 11000 // 00000 // Answer: 1 // Example 2: // 11000 // 11000 // 00100 // 00011 // Answer: 3 public class NumberOfIslands { char[][] gridCopy; public int numIslands(char[][] grid) { //set grid copy to the current grid gridCopy = grid; //initialize number of islands to zero int numberOfIslands = 0; //iterate through every index of the grid for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { //attempt to "sink" the current index of the grid numberOfIslands += sink(gridCopy, i, j); } } //return the total number of islands return numberOfIslands; } int sink(char[][] grid, int i, int j) { //check the bounds of i and j and if the current index is an island or not (1 or 0) if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { return 0; } //set current index to 0 grid[i][j] = '0'; // sink all neighbors of current index sink(grid, i + 1, j); sink(grid, i - 1, j); sink(grid, i, j + 1); sink(grid, i, j - 1); //increment number of islands return 1; } } ================================================ FILE: company/facebook/OneEditDistance.java ================================================ // Given two strings S and T, determine if they are both one edit distance apart. public class OneEditDistance { public boolean isOneEditDistance(String s, String t) { //iterate through the length of the smaller string for(int i = 0; i < Math.min(s.length(), t.length()); i++) { //if the current characters of the two strings are not equal if(s.charAt(i) != t.charAt(i)) { //return true if the remainder of the two strings are equal, false otherwise if(s.length() == t.length()) { return s.substring(i + 1).equals(t.substring(i + 1)); } else if(s.length() < t.length()) { //return true if the strings would be the same if you deleted a character from string t return s.substring(i).equals(t.substring(i + 1)); } else { //return true if the strings would be the same if you deleted a character from string s return t.substring(i).equals(s.substring(i + 1)); } } } //if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1 return Math.abs(s.length() - t.length()) == 1; } } ================================================ FILE: company/facebook/PaintHouseII.java ================================================ // There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. // Note: // All costs are positive integers. // Follow up: // Could you solve it in O(nk) runtime? public class PaintHouseII { public int minCostII(int[][] costs) { if(costs == null|| costs.length == 0) { return 0; } int m = costs.length; int n = costs[0].length; int min1 = -1; int min2 = -1; for(int i = 0; i < m; i++) { int last1 = min1; int last2 = min2; min1 = -1; min2 = -1; for(int j = 0; j < n; j++) { if(j != last1) { costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } if(min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if(min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[m - 1][min1]; } } ================================================ FILE: company/facebook/PalindromeLinkedList.java ================================================ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class PalindromeLinkedList { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) { return true; } Stack stack = new Stack(); ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null) { stack.push(slow.val); fast = fast.next.next; slow = slow.next; } if(fast != null) { slow = slow.next; } while(slow != null) { if(stack.pop() != slow.val) { return false; } slow = slow.next; } return true; } } ================================================ FILE: company/facebook/PalindromicSubstrings.java ================================================ //Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } } ================================================ FILE: company/facebook/PowerOfXToTheN.java ================================================ // Implement pow(x, n). public class PowerOfXToTheN { public double myPow(double x, int n) { if(n == 0) { return 1; } if(Double.isInfinite(x)) { return 0; } if(n < 0) { n = -n; x = 1 / x; } return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); } } ================================================ FILE: company/facebook/ProductOfArrayExceptSelf.java ================================================ // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. // Solve it without division and in O(n). // For example, given [1,2,3,4], return [24,12,8,6]. // Follow up: // Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n]; int left = 1; for(int i = 0; i < nums.length; i++) { if(i > 0) { left *= nums[i - 1]; } result[i] = left; } int right = 1; for(int i = n - 1; i >= 0; i--) { if(i < n - 1) { right *= nums[i + 1]; } result[i] *= right; } return result; } } ================================================ FILE: company/facebook/RegularExpressionMatching.java ================================================ // Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } } ================================================ FILE: company/facebook/RemoveDuplicatesFromSortedArray.java ================================================ // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. // Do not allocate extra space for another array, you must do this in place with constant memory. // For example, // Given input array nums = [1,1,2], // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. public class RemoveDuplicatesFromSortedArray { public int removeDuplicates(int[] nums) { if(nums.length == 0 || nums == null) { return 0; } if(nums.length < 2) { return nums.length; } int index = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[i - 1]) { nums[index++] = nums[i]; } } return index; } } ================================================ FILE: company/facebook/RemoveInvalidParentheses.java ================================================ // Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. // Note: The input string may contain letters other than the parentheses ( and ). // Examples: // "()())()" -> ["()()()", "(())()"] // "(a)())()" -> ["(a)()()", "(a())()"] // ")(" -> [""] public class RemoveInvalidParentheses { public List removeInvalidParentheses(String s) { List result = new ArrayList<>(); remove(s, result, 0, 0, new char[]{'(', ')'}); return result; } public void remove(String s, List result, int last_i, int last_j, char[] par) { for (int stack = 0, i = last_i; i < s.length(); i++) { if (s.charAt(i) == par[0]) { stack++; } if (s.charAt(i) == par[1]) { stack--; } if (stack >= 0) { continue; } for (int j = last_j; j <= i; j++) { if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) { remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par); } } return; } String reversed = new StringBuilder(s).reverse().toString(); if (par[0] == '(') { // finished left to right remove(reversed, result, 0, 0, new char[]{')', '('}); } else { // finished right to left result.add(reversed); } } } ================================================ FILE: company/facebook/ReverseLinkedList.java ================================================ // Reverse a singly linked list. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } } ================================================ FILE: company/facebook/RomanToInteger.java ================================================ // Given a roman numeral, convert it to an integer. // Input is guaranteed to be within the range from 1 to 3999 public class RomanToInteger { public int romanToInt(String s) { HashMap map = new HashMap(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int total = 0; for(int i = 0; i < s.length() - 1; i++) { if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { total -= map.get(s.charAt(i)); } else { total += map.get(s.charAt(i)); } } total += map.get(s.charAt(s.length() - 1)); return total; } } ================================================ FILE: company/facebook/SearchInRotatedSortedArray.java ================================================ // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } } ================================================ FILE: company/facebook/SortColors.java ================================================ // Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. // Note: // You are not suppose to use the library's sort function for this problem. public class SortColors { public void sortColors(int[] nums) { int wall = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] < 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } for(int i = 0; i < nums.length; i++) { if(nums[i] == 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } } } ================================================ FILE: company/facebook/SparseMatrixMultiplication.java ================================================ // Given two sparse matrices A and B, return the result of AB. // You may assume that A's column number is equal to B's row number. // Example: // A = [ // [ 1, 0, 0], // [-1, 0, 3] // ] // B = [ // [ 7, 0, 0 ], // [ 0, 0, 0 ], // [ 0, 0, 1 ] // ] // | 1 0 0 | | 7 0 0 | | 7 0 0 | // AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // | 0 0 1 | public class SparseMatrixMultiplication { public int[][] multiply(int[][] A, int[][] B) { int m = A.length; int n = A[0].length; int nB = B[0].length; int[][] C = new int[m][nB]; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(A[i][j] != 0) { for(int k = 0; k < nB; k++) { if(B[j][k] != 0) { C[i][k] += A[i][j] * B[j][k]; } } } } } return C; } } ================================================ FILE: company/facebook/SquareRootX.java ================================================ // Implement int sqrt(int x). // Compute and return the square root of x. public class SquareRootX { public int mySqrt(int x) { if(x == 0) { return 0; } int left = 1; int right = x; while(left <= right) { int mid = left + (right - left) / 2; if(mid == x / mid) { return mid; } else if(mid > x / mid) { right = mid - 1; } else if(mid < x / mid) { left = mid + 1; } } return right; } } ================================================ FILE: company/facebook/Subsets.java ================================================ // Given a set of distinct integers, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] public class Subsets { public List> subsets(int[] nums) { List> result = new ArrayList<>(); recurse(result, nums, new Stack<>(), 0); return result; } private void recurse(List> result, int[] nums, Stack path, int position) { if(position == nums.length) { result.add(new ArrayList<>(path)); return; } path.push(nums[position]); recurse(result, nums, path, position + 1); path.pop(); recurse(result, nums, path, position + 1); } } ================================================ FILE: company/facebook/SubsetsII.java ================================================ // Given a collection of integers that might contain duplicates, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,2], a solution is: // [ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] // ] public class SubsetsII { public List> subsetsWithDup(int[] nums) { Arrays.sort(nums); List> result = new ArrayList>(); if(nums.length == 0 || nums == null) { return result; } helper(nums, new ArrayList(), 0, result); return result; } public void helper(int[] nums, ArrayList current, int index, List> result) { result.add(current); for(int i = index; i < nums.length; i++) { if(i > index && nums[i] == nums[i - 1]) { continue; } ArrayList newCurrent = new ArrayList(current); newCurrent.add(nums[i]); helper(nums, newCurrent, i + 1, result); } } } ================================================ FILE: company/facebook/SumOfLeftLeaves.java ================================================ // Find the sum of all left leaves in a given binary tree. // Example: // 3 // / \ // 9 20 // / \ // 15 7 // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SumOfLeftLeaves { public int sumOfLeftLeaves(TreeNode root) { if(root == null) { return 0; } int total = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) { total += root.left.val; } else { total += sumOfLeftLeaves(root.left); } } total += sumOfLeftLeaves(root.right); return total; } } ================================================ FILE: company/facebook/TwoSum.java ================================================ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // Example: // Given nums = [2, 7, 11, 15], target = 9, // Because nums[0] + nums[1] = 2 + 7 = 9, // return [0, 1]. public class TwoSum { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: company/facebook/ValidPalindrome.java ================================================ public class ValidPalindrome { public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while(left < right) { while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { left++; } while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { right--; } if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } } ================================================ FILE: company/facebook/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: company/facebook/ValidateBinarySearchTree.java ================================================ // Given a binary tree, determine if it is a valid binary search tree (BST). // Assume a BST is defined as follows: // The left subtree of a node contains only nodes with keys less than the node's key. // The right subtree of a node contains only nodes with keys greater than the node's key. // Both the left and right subtrees must also be binary search trees. // Example 1: // 2 // / \ // 1 3 // Binary tree [2,1,3], return true. // Example 2: // 1 // / \ // 2 3 // Binary tree [1,2,3], return false. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ValidateBinarySearchTree { public boolean isValidBST(TreeNode root) { if(root == null) { return true; } return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) { if(root == null) { return true; } else if(root.val >= maxValue || root.val <= minValue) { return false; } else { return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue); } } } ================================================ FILE: company/facebook/WallsAndGates.java ================================================ // You are given a m x n 2D grid initialized with these three possible values. // -1 - A wall or an obstacle. // 0 - A gate. // INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. // Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. // For example, given the 2D grid: // INF -1 0 INF // INF INF INF -1 // INF -1 INF -1 // 0 -1 INF INF // After running your function, the 2D grid should be: // 3 -1 0 1 // 2 2 1 -1 // 1 -1 2 -1 // 0 -1 3 4 public class WallsAndGates { public void wallsAndGates(int[][] rooms) { //iterate through the matrix calling dfs on all indices that contain a zero for(int i = 0; i < rooms.length; i++) { for(int j = 0; j < rooms[0].length; j++) { if(rooms[i][j] == 0) { dfs(rooms, i, j, 0); } } } } void dfs(int[][] rooms, int i, int j, int distance) { //if you have gone out of the bounds of the array or you have run into a wall/obstacle, return // room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) { return; } //set current index's distance to distance rooms[i][j] = distance; //recurse on all adjacent neighbors of rooms[i][j] dfs(rooms, i + 1, j, distance + 1); dfs(rooms, i - 1, j, distance + 1); dfs(rooms, i, j + 1, distance + 1); dfs(rooms, i, j - 1, distance + 1); } } ================================================ FILE: company/facebook/WordBreak.java ================================================ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } } ================================================ FILE: company/facebook/WordSearch.java ================================================ // Given a 2D board and a word, find if the word exists in the grid. // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. // For example, // Given board = // [ // ['A','B','C','E'], // ['S','F','C','S'], // ['A','D','E','E'] // ] // word = "ABCCED", -> returns true, // word = "SEE", -> returns true, // word = "ABCB", -> returns false. public class WordSearch { public boolean exist(char[][] board, String word) { char[] w = word.toCharArray(); for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(search(board, i, j, w, 0)) { return true; } } } return false; } public boolean search(char[][] board, int i, int j, char[] w, int index) { if(index == w.length) { return true; } if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) { return false; } if(board[i][j] != w[index]) { return false; } board[i][j] ^= 256; boolean exist = search(board, i + 1, j, w, index + 1) || search(board, i - 1, j, w, index + 1) || search(board, i, j + 1, w, index + 1) || search(board, i, j - 1, w, index + 1); board[i][j] ^= 256; return exist; } } ================================================ FILE: company/google/3SumSmaller.java ================================================ // Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. // For example, given nums = [-2, 0, 1, 3], and target = 2. // Return 2. Because there are two triplets which sums are less than 2: // [-2, 0, 1] // [-2, 0, 3] // Follow up: // Could you solve it in O(n2) runtime? public class 3SumSmaller { public int threeSumSmaller(int[] nums, int target) { //initialize total count to zero int count = 0; //sort the array Arrays.sort(nums); //loop through entire array for(int i = 0; i < nums.length - 2; i++) { //set left to i + 1 int left = i + 1; //set right to end of array int right = nums.length - 1; //while left index < right index while(left < right) { //if the 3 indices add to less than the target increment count if(nums[i] + nums[left] + nums[right] < target) { //increment the count by the distance between left and right because the array is sorted count += right - left; //increment left pointer left++; } else { //if they sum to a value greater than target... //decrement right pointer right--; } } } return count; } } ================================================ FILE: company/google/AndroidUnlockPatterns.java ================================================ // Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys. // Rules for a valid pattern: // Each pattern must connect at least m keys and at most n keys. // All the keys must be distinct. // If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed. // The order of keys used matters. // Explanation: // | 1 | 2 | 3 | // | 4 | 5 | 6 | // | 7 | 8 | 9 | // Invalid move: 4 - 1 - 3 - 6 // Line 1 - 3 passes through key 2 which had not been selected in the pattern. // Invalid move: 4 - 1 - 9 - 2 // Line 1 - 9 passes through key 5 which had not been selected in the pattern. // Valid move: 2 - 4 - 1 - 3 - 6 // Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern // Valid move: 6 - 5 - 4 - 1 - 9 - 2 // Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern. // Example: // Given m = 1, n = 1, return 9. public class AndroidUnlockPatterns { public int numberOfPatterns(int m, int n) { //initialize a 10x10 matrix int skip[][] = new int[10][10]; //initialize indices of skip matrix (all other indices in matrix are 0 by default) skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip [7][3] = skip[6][4] = skip[4][6] = 5; //initialize visited array boolean visited[] = new boolean[10]; //initialize total number to 0 int totalNumber = 0; //run DFS for each length from m to n for(int i = m; i <= n; ++i) { totalNumber += DFS(visited, skip, 1, i - 1) * 4; //1, 3, 7, and 9 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 2, i - 1) * 4; //2, 4, 6, and 8 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 5, i - 1); //do not multiply by 4 because 5 is unique } return totalNumber; } int DFS(boolean visited[], int[][] skip, int current, int remaining) { //base cases if(remaining < 0) { return 0; } if(remaining == 0) { return 1; } //mark the current node as visited visited[current] = true; //initialize total number to 0 int totalNumber = 0; for(int i = 1; i <= 9; ++i) { //if the current node has not been visited and (two numbers are adjacent or skip number has already been visited) if(!visited[i] && (skip[current][i] == 0 || visited[skip[current][i]])) { totalNumber += DFS(visited, skip, i, remaining - 1); } } //mark the current node as not visited visited[current] = false; //return total number return totalNumber; } } ================================================ FILE: company/google/BinarySearchTreeIterator.java ================================================ // Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. // Calling next() will return the next smallest number in the BST. // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeIterator { Stack stack; public BSTIterator(TreeNode root) { stack = new Stack(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/google/BinaryTreePaths.java ================================================ // Given a binary tree, return all root-to-leaf paths. // For example, given the following binary tree: // 1 // / \ // 2 3 // \ // 5 // All root-to-leaf paths are: // ["1->2->5", "1->3"] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreePaths { public List binaryTreePaths(TreeNode root) { List result = new ArrayList(); if(root == null) { return result; } helper(new String(), root, result); return result; } public void helper(String current, TreeNode root, List result) { if(root.left == null && root.right == null) { result.add(current + root.val); } if(root.left != null) { helper(current + root.val + "->", root.left, result); } if(root.right != null) { helper(current + root.val + "->", root.right, result); } } } ================================================ FILE: company/google/BinaryTreeVerticalOrderTraversal.java ================================================ // Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). // If two nodes are in the same row and column, the order should be from left to right. // Examples: // Given binary tree [3,9,20,null,null,15,7], // 3 // /\ // / \ // 9 20 // /\ // / \ // 15 7 // return its vertical order traversal as: // [ // [9], // [3,15], // [20], // [7] // ] // Given binary tree [3,9,8,4,0,1,7], // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // return its vertical order traversal as: // [ // [4], // [9], // [3,0,1], // [8], // [7] // ] // Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // /\ // / \ // 5 2 // return its vertical order traversal as: // [ // [4], // [9,5], // [3,0,1], // [8,2], // [7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeVerticalOrderTraversal { public List> verticalOrder(TreeNode root) { List> result = new ArrayList<>(); if(root == null) { return result; } Map> map = new HashMap<>(); Queue q = new LinkedList<>(); Queue cols = new LinkedList<>(); q.add(root); cols.add(0); int min = 0; int max = 0; while(!q.isEmpty()) { TreeNode node = q.poll(); int col = cols.poll(); if(!map.containsKey(col)) { map.put(col, new ArrayList()); } map.get(col).add(node.val); if(node.left != null) { q.add(node.left); cols.add(col - 1); min = Math.min(min, col - 1); } if(node.right != null) { q.add(node.right); cols.add(col + 1); max = Math.max(max, col + 1); } } for(int i = min; i <= max; i++) { result.add(map.get(i)); } return result; } } ================================================ FILE: company/google/BinaryWatch.java ================================================ // A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). // Each LED represents a zero or one, with the least significant bit on the right. // For example, the above binary watch reads "3:25". // Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. // Example: // Input: n = 1 // Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] // Note: // The order of output does not matter. // The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". // The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". public class BinaryWatch { public List readBinaryWatch(int num) { ArrayList allTimes = new ArrayList(); //iterate through all possible time combinations for(int i = 0; i < 12; i++) { for(int j = 0; j < 60; j++) { //if the current number and n have the same number of bits the time is possible if(Integer.bitCount(i * 64 + j) == num) { //add the current time to all times arraylist allTimes.add(String.format("%d:%02d", i, j)); } } } return allTimes; } } ================================================ FILE: company/google/BombEnemy.java ================================================ // Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb. // The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. // Note that you can only put the bomb at an empty cell. // Example: // For the given grid // 0 E 0 0 // E 0 W E // 0 E 0 0 // return 3. (Placing a bomb at (1,1) kills 3 enemies) public class BombEnemy { public int maxKilledEnemies(char[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int max = 0; int row = 0; int[] col = new int[grid[0].length]; for(int i = 0; i max) ? row + col[j] : max; } } } return max; } //calculate killed enemies for row i from column j private int killedEnemiesRow(char[][] grid, int i, int j) { int num = 0; while(j <= grid[0].length-1 && grid[i][j] != 'W') { if(grid[i][j] == 'E') { num++; } j++; } return num; } //calculate killed enemies for column j from row i private int killedEnemiesCol(char[][] grid, int i, int j) { int num = 0; while(i <= grid.length -1 && grid[i][j] != 'W'){ if(grid[i][j] == 'E') { num++; } i++; } return num; } } ================================================ FILE: company/google/BullsAndCows.java ================================================ //You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. // //Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. // //Please note that both secret number and friend's guess may contain duplicate digits. // //Example 1: // //Input: secret = "1807", guess = "7810" // //Output: "1A3B" // //Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. //Example 2: // //Input: secret = "1123", guess = "0111" // //Output: "1A1B" // //Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. //Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. class BullsAndCows { public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] counts = new int[10]; for(int i = 0; i < secret.length(); i++) { if(secret.charAt(i) == guess.charAt(i)) { bulls++; } else { if(counts[secret.charAt(i) - '0']++ < 0) { cows++; } if(counts[guess.charAt(i) - '0']-- > 0) { cows++; } } } return bulls + "A" + cows + "B"; } } ================================================ FILE: company/google/CloneGraph.java ================================================ // Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } * }; */ public class CloneGraph { public HashMap map = new HashMap(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } } ================================================ FILE: company/google/ClosestBinarySearchTreeValue.java ================================================ // Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. // Note: // Given target value is a floating point. // You are guaranteed to have only one unique value in the BST that is closest to the target. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ClosestBinarySearchTreeValue { public int closestValue(TreeNode root, double target) { int value = root.val; TreeNode child = root.val < target ? root.right : root.left; if(child == null) { return value; } int childValue = closestValue(child, target); return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue; } } ================================================ FILE: company/google/CombinationSumIV.java ================================================ // Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. // Example: // nums = [1, 2, 3] // target = 4 // The possible combination ways are: // (1, 1, 1, 1) // (1, 1, 2) // (1, 2, 1) // (1, 3) // (2, 1, 1) // (2, 2) // (3, 1) // Note that different sequences are counted as different combinations. // Therefore the output is 7. // Follow up: // What if negative numbers are allowed in the given array? // How does it change the problem? // What limitation we need to add to the question to allow negative numbers? public class CombinationSumIV { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < nums.length; j++) { if(i - nums[j] >= 0) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } } ================================================ FILE: company/google/DailyTemperatures.java ================================================ //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack stack = new Stack(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } } ================================================ FILE: company/google/DecodeString.java ================================================ // Given an encoded string, return it's decoded string. // The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. // You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. // Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. public class DecodeString { public String decodeString(String s) { //declare empty string String decoded = ""; //initialize stack to hold counts Stack countStack = new Stack(); //initalize stack to hold decoded string Stack decodedStack = new Stack(); //initialize index to zero int index = 0; //iterate through entire string while(index < s.length()) { //if the current character is numeric... if(Character.isDigit(s.charAt(index))) { int count = 0; //determine the number while(Character.isDigit(s.charAt(index))) { count = 10 * count + (s.charAt(index) - '0'); index++; } //push the number onto the count stack countStack.push(count); } else if(s.charAt(index) == '[') { //if the current character is an opening bracket decodedStack.push(decoded); decoded = ""; index++; } else if(s.charAt(index) == ']') { //if the current character is a closing bracket StringBuilder temp = new StringBuilder(decodedStack.pop()); int repeatTimes = countStack.pop(); for(int i = 0; i < repeatTimes; i++) { temp.append(decoded); } decoded = temp.toString(); index++; } else { //otherwise, append the current character to the decoded string decoded += s.charAt(index); index++; } } //return the decoded string return decoded; } } ================================================ FILE: company/google/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: company/google/ExpressionAddOperators.java ================================================ // Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. // Examples: // "123", 6 -> ["1+2+3", "1*2*3"] // "232", 8 -> ["2*3+2", "2+3*2"] // "105", 5 -> ["1*0+5","10-5"] // "00", 0 -> ["0+0", "0-0", "0*0"] // "3456237490", 9191 -> [] public class ExpressionAddOperator { public List addOperators(String num, int target) { List result = new ArrayList(); if(num == null || num.length() == 0) { return result; } helper(result, "", num, target, 0, 0, 0); return result; } public void helper(List result, String path, String num, int target, int pos, long eval, long multed) { if(pos == num.length()) { if(eval == target) { result.add(path); } return; } for(int i = pos; i < num.length(); i++) { if(i != pos && num.charAt(pos) == '0') { break; } long cur = Long.parseLong(num.substring(pos, i + 1)); if(pos == 0) { helper(result, path + cur, num, target, i + 1, cur, cur); } else { helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur); helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur); helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur); } } } } ================================================ FILE: company/google/FindAllNumbersDisappearedInAnArray.java ================================================ //Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. // //Find all the elements of [1, n] inclusive that do not appear in this array. // //Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. // //Example: // //Input: //[4,3,2,7,8,2,3,1] // //Output: //[5,6] class FindAllNumbersDisappearedInAnArray { public List findDisappearedNumbers(int[] nums) { List result = new ArrayList(); HashMap map = new HashMap(); for(int i = 1; i <= nums.length; i++) { map.put(i, 1); } for(int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])) { map.put(nums[i], -1); } } for(int i: map.keySet()) { if(map.get(i) != -1) { result.add(i); } } return result; } } ================================================ FILE: company/google/FindTheDifference.java ================================================ // Given two strings s and t which consist of only lowercase letters. // String t is generated by random shuffling string s and then add one more letter at a random position. // Find the letter that was added in t. // Example: // Input: // s = "abcd" // t = "abcde" // Output: // e // Explanation: // 'e' is the letter that was added. public class FindTheDifference { public char findTheDifference(String s, String t) { int charCodeS = 0; int charCodeT = 0; for(int i = 0; i < s.length(); i++) { charCodeS += (int)(s.charAt(i)); } for(int i = 0; i < t.length(); i++) { charCodeT += (int)(t.charAt(i)); } return (char)(charCodeT - charCodeS); } } ================================================ FILE: company/google/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: company/google/FlattenNestedListIterator.java ================================================ // Given a nested list of integers, implement an iterator to flatten it. // Each element is either an integer, or a list -- whose elements may also be integers or other lists. // Example 1: // Given the list [[1,1],2,[1,1]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. // Example 2: // Given the list [1,[4,[6]]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List getList(); * } */ public class FlattenNestedListIterator implements Iterator { Stack stack = new Stack(); public NestedIterator(List nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger current = stack.peek(); if(current.isInteger()) { return true; } stack.pop(); for(int i = current.getList().size() - 1; i >= 0; i--) { stack.push(current.getList().get(i)); } } return false; } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/google/GameOfLife.java ================================================ // According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." // Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies, as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population.. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // Write a function to compute the next state (after one update) of the board given its current state. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? public class GameOfLife { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3; } if(board[i][j] == 0 && lives == 3) { board[i][j] = 2; } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; } } } private int liveNeighbors(int[][] board, int m, int n, int i, int j) { int lives = 0; for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) { for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) { lives += board[x][y] & 1; } } lives -= board[i][j] & 1; return lives; } } ================================================ FILE: company/google/GeneralizedAbbreviation.java ================================================ // Write a function to generate the generalized abbreviations of a word. // Example: // Given word = "word", return the following list (order does not matter): // ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] public class GeneralizedAbbreviation { public List generateAbbreviations(String word) { List result = new ArrayList(); backtrack(result, word, 0, "", 0); return result; } void backtrack(List result, String word, int position, String current, int count) { if(position == word.length()) { if(count > 0) { current += count; } result.add(current); } else { backtrack(result, word, position + 1, current, count + 1); backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0); } } } ================================================ FILE: company/google/GenerateParentheses.java ================================================ //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. // //For example, given n = 3, a solution set is: // //[ //"((()))", //"(()())", //"(())()", //"()(())", //"()()()" //] class GenerateParentheses { public List generateParenthesis(int n) { List result = new ArrayList(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } } ================================================ FILE: company/google/GroupShiftedStrings.java ================================================ // Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List> groupStrings(String[] strings) { List> result = new ArrayList>(); HashMap> map = new HashMap>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List list = new ArrayList(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List list = map.get(key); Collections.sort(list); result.add(list); } return result; } } ================================================ FILE: company/google/GuessNumberHigherOrLower.java ================================================ // We are playing the Guess Game. The game is as follows: // I pick a number from 1 to n. You have to guess which number I picked. // Every time you guess wrong, I'll tell you whether the number is higher or lower. // You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): // -1 : My number is lower // 1 : My number is higher // 0 : Congrats! You got it! // Example: // n = 10, I pick 6. // Return 6. /* The guess API is defined in the parent class GuessGame. @param num, your guess @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); */ public class GuessNumberHigherOrLower extends GuessGame { public int guessNumber(int n) { int left = 1; int right = n; while(left <= right) { int mid = left + (right - left) / 2; if(guess(mid) == 0) { return mid; } else if(guess(mid) > 0) { left = mid + 1; } else { right = mid; } } return -1; } } ================================================ FILE: company/google/ImplementTrie.java ================================================ // Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap(); this.character = character; this.last = false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } } ================================================ FILE: company/google/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/google/InsertInterval.java ================================================ // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). // You may assume that the intervals were initially sorted according to their start times. // Example 1: // Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. // Example 2: // Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. // This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class InsertInterval { public List insert(List intervals, Interval newInterval) { int i = 0; while(i < intervals.size() && intervals.get(i).end < newInterval.start) { i++; } while(i < intervals.size() && intervals.get(i).start <= newInterval.end) { newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end)); intervals.remove(i); } intervals.add(i, newInterval); return intervals; } } ================================================ FILE: company/google/IslandPerimeter.java ================================================ // You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. // Example: // [[0,1,0,0], // [1,1,1,0], // [0,1,0,0], // [1,1,0,0]] // Answer: 16 class IslandPerimeter { public int islandPerimeter(int[][] grid) { int perimeter = 0; if(grid == null || grid.length == 0) { return perimeter; } for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[i].length; j++) { if(grid[i][j] == 1) { perimeter += numNeighbors(grid, i, j); return perimeter; } } } return perimeter; } public int numNeighbors(int[][] grid, int x, int y) { if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] == 0) { return 1; } if(grid[x][y] == -1) { return 0; } grid[x][y] = -1; return numNeighbors(grid, x + 1, y) + numNeighbors(grid, x - 1, y) + numNeighbors(grid, x, y + 1) + numNeighbors(grid, x, y - 1); } } ================================================ FILE: company/google/JudgeRouteCircle.java ================================================ //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. // //The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. // //Example 1: //Input: "UD" //Output: true //Example 2: //Input: "LL" //Output: false class JudgeRouteCircle { public boolean judgeCircle(String moves) { int UD = 0; int LR = 0; for(int i = 0; i < moves.length(); i++) { if(moves.charAt(i) == 'U') { UD++; } else if(moves.charAt(i) == 'D') { UD--; } else if(moves.charAt(i) == 'L') { LR++; } else if(moves.charAt(i) == 'R') { LR--; } } return UD == 0 && LR == 0; } } ================================================ FILE: company/google/LetterCombinationsOfAPhoneNumber.java ================================================ // Given a digit string, return all possible letter combinations that the number could represent. // A mapping of digit to letters (just like on the telephone buttons) is given below. // 2 - abc // 3 - def // 4 - ghi // 5 - jkl // 6 - mno // 7 - pqrs // 8 - tuv // 9 - wxyz // Input:Digit string "23" // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class LetterCombinationsOfAPhoneNumber { public List letterCombinations(String digits) { List result = new ArrayList(); if(digits == null || digits.length() == 0) { return result; } String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; letterCombinationsRecursive(result, digits, "", 0, mapping); return result; } public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) { if(index == digits.length()) { result.add(current); return; } String letters = mapping[digits.charAt(index) - '0']; for(int i = 0; i < letters.length(); i++) { letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); } } } ================================================ FILE: company/google/LoggerRateLimiter.java ================================================ // Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. // Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false. // It is possible that several messages arrive roughly at the same time. // Example: // Logger logger = new Logger(); // // logging string "foo" at timestamp 1 // logger.shouldPrintMessage(1, "foo"); returns true; // // logging string "bar" at timestamp 2 // logger.shouldPrintMessage(2,"bar"); returns true; // // logging string "foo" at timestamp 3 // logger.shouldPrintMessage(3,"foo"); returns false; // // logging string "bar" at timestamp 8 // logger.shouldPrintMessage(8,"bar"); returns false; // // logging string "foo" at timestamp 10 // logger.shouldPrintMessage(10,"foo"); returns false; // // logging string "foo" at timestamp 11 // logger.shouldPrintMessage(11,"foo"); returns true; public class LoggerRateLimiter { HashMap messages; /** Initialize your data structure here. */ public Logger() { this.messages = new HashMap(); } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */ public boolean shouldPrintMessage(int timestamp, String message) { if(messages.containsKey(message)) { if(timestamp - messages.get(message) >= 10) { messages.put(message, timestamp); return true; } else { return false; } } else { messages.put(message, timestamp); return true; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */ ================================================ FILE: company/google/LongestConsecutiveSequence.java ================================================ // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. // For example, // Given [100, 4, 200, 1, 3, 2], // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. // Your algorithm should run in O(n) complexity. class LongestConsecutiveSequence { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0) { return 0; } Set set = new HashSet(); for(int n: nums) { set.add(n); } int maxLength = 0; for(int n: set) { if(!set.contains(n - 1)) { int current = n; int currentMax = 1; while(set.contains(n + 1)) { currentMax++; n++; } maxLength = Math.max(maxLength, currentMax); } } return maxLength; } } ================================================ FILE: company/google/LongestSubstringWithAtMostKDistinctCharacters.java ================================================ // Given a string, find the length of the longest substring T that contains at most k distinct characters. // For example, Given s = “eceba” and k = 2, // T is "ece" which its length is 3. public class LongestSubstringWithAtMostKDistinctCharacters { public int lengthOfLongestSubstringKDistinct(String s, int k) { int[] count = new int[256]; // there are 256 ASCII characters in the world int i = 0; // i will be behind j int num = 0; int res = 0; for (int j = 0; j < s.length(); j++) { if (count[s.charAt(j)] == 0) { // if count[s.charAt(j)] == 0, we know that it is a distinct character num++; } count[s.charAt(j)]++; while (num > k && i < s.length()) { // sliding window count[s.charAt(i)]--; if (count[s.charAt(i)] == 0){ num--; } i++; } res = Math.max(res, j - i + 1); } return res; } } ================================================ FILE: company/google/MaximumProductOfWordLengths.java ================================================ // Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. // Example 1: // Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] // Return 16 // The two words can be "abcw", "xtfn". // Example 2: // Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] // Return 4 // The two words can be "ab", "cd". // Example 3: // Given ["a", "aa", "aaa", "aaaa"] // Return 0 // No such pair of words. public class MaximumProductOfWordLengths { public int maxProduct(String[] words) { if(words.length == 0 || words == null) { return 0; } int length = words.length; int[] value = new int[length]; int max = 0; for(int i = 0; i < length; i++) { String temp = words[i]; value[i] = 0; for(int j = 0; j < temp.length(); j++) { value[i] |= 1 << (temp.charAt(j) - 'a'); } } for(int i = 0; i < length; i++) { for(int j = 1; j < length; j++) { if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length()) > max) { max = words[i].length() * words[j].length(); } } } return max; } } ================================================ FILE: company/google/MergeIntervals.java ================================================ // Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class MergeIntervals { public List merge(List intervals) { List result = new ArrayList(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } } ================================================ FILE: company/google/MinStack.java ================================================ //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: company/google/MissingRanges.java ================================================ // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. // For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. public class MissingRanges { public List findMissingRanges(int[] nums, int lower, int upper) { ArrayList result = new ArrayList(); for(int i = 0; i <= nums.length; i++) { long start = i == 0 ? lower : (long)nums[i - 1] + 1; long end = i == nums.length ? upper : (long)nums[i] - 1; addMissing(result, start, end); } return result; } void addMissing(ArrayList result, long start, long end) { if(start > end) { return; } else if(start == end) { result.add(start + ""); } else { result.add(start + "->" + end); } } } ================================================ FILE: company/google/MovingAverageFromDataStream.java ================================================ // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. // For example, // MovingAverage m = new MovingAverage(3); // m.next(1) = 1 // m.next(10) = (1 + 10) / 2 // m.next(3) = (1 + 10 + 3) / 3 // m.next(5) = (10 + 3 + 5) / 3 /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */ public class MovingAverageFromDataStream { double previousSum = 0.0; int maxSize; Queue window; /** Initialize your data structure here. */ public MovingAverage(int size) { this.maxSize = size; window = new LinkedList(); } public double next(int val) { if(window.size() == maxSize) { previousSum -= window.remove(); } window.add(val); previousSum += val; return previousSum / window.size(); } } ================================================ FILE: company/google/NumberOfIslands.java ================================================ // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. // Example 1: // 11110 // 11010 // 11000 // 00000 // Answer: 1 // Example 2: // 11000 // 11000 // 00100 // 00011 // Answer: 3 public class NumberOfIslands { char[][] gridCopy; public int numIslands(char[][] grid) { //set grid copy to the current grid gridCopy = grid; //initialize number of islands to zero int numberOfIslands = 0; //iterate through every index of the grid for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { //attempt to "sink" the current index of the grid numberOfIslands += sink(gridCopy, i, j); } } //return the total number of islands return numberOfIslands; } int sink(char[][] grid, int i, int j) { //check the bounds of i and j and if the current index is an island or not (1 or 0) if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { return 0; } //set current index to 0 grid[i][j] = '0'; // sink all neighbors of current index sink(grid, i + 1, j); sink(grid, i - 1, j); sink(grid, i, j + 1); sink(grid, i, j - 1); //increment number of islands return 1; } } ================================================ FILE: company/google/PacificAtlanticWaterFlow.java ================================================ // Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. // Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower. // Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. // Note: // The order of returned grid coordinates does not matter. // Both m and n are less than 150. // Example: // Given the following 5x5 matrix: // Pacific ~ ~ ~ ~ ~ // ~ 1 2 2 3 (5) * // ~ 3 2 3 (4) (4) * // ~ 2 4 (5) 3 1 * // ~ (6) (7) 1 4 5 * // ~ (5) 1 1 2 4 * // * * * * * Atlantic // Return: // [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). public class PacificAtlanticWaterFlow { public List pacificAtlantic(int[][] matrix) { List result = new LinkedList<>(); //error checking if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { return result; } int n = matrix.length; int m = matrix[0].length; boolean[][] pacific = new boolean[n][m]; boolean[][] atlantic = new boolean[n][m]; for(int i = 0; i < n; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, i, 0); dfs(matrix, atlantic, Integer.MIN_VALUE, i, m - 1); } for(int i = 0; i < m; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, 0, i); dfs(matrix, atlantic, Integer.MIN_VALUE, n - 1, i); } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(pacific[i][j] && atlantic[i][j]) { result.add(new int[] {i, j}); } } } return result; } public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) { int n = matrix.length; int m = matrix[0].length; if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < height) { return; } visited[x][y] = true; dfs(matrix, visited, matrix[x][y], x + 1, y); dfs(matrix, visited, matrix[x][y], x - 1, y); dfs(matrix, visited, matrix[x][y], x, y + 1); dfs(matrix, visited, matrix[x][y], x, y - 1); } } ================================================ FILE: company/google/PaintFence.java ================================================ // There is a fence with n posts, each post can be painted with one of the k colors. // You have to paint all the posts such that no more than two adjacent fence posts have the same color. // Return the total number of ways you can paint the fence. // Note: // n and k are non-negative integers. public class PaintFence { public int numWays(int n, int k) { if(n <= 0) { return 0; } int sameColorCounts = 0; int differentColorCounts = k; for(int i = 2; i <= n; i++) { int temp = differentColorCounts; differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); sameColorCounts = temp; } return sameColorCounts + differentColorCounts; } } ================================================ FILE: company/google/PlusOne.java ================================================ //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. // //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. // //You may assume the integer does not contain any leading zero, except the number 0 itself. // //Example 1: // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. //Example 2: // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ================================================ FILE: company/google/PlusOneLinkedList.java ================================================ // Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. // You may assume the integer do not contain any leading zero, except the number 0 itself. // The digits are stored such that the most significant digit is at the head of the list. // Example: // Input: // 1->2->3 // Output: // 1->2->4 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class PlusOneLinkedList { public ListNode plusOne(ListNode head) { if(plusOneRecursive(head) == 0) { return head; } else { ListNode newHead = new ListNode(1); newHead.next = head; return newHead; } } private int plusOneRecursive(ListNode head) { if(head == null) { return 1; } int carry = plusOneRecursive(head.next); if(carry == 0) { return 0; } int value = head.val + 1; head.val = value % 10; return value/10; } } ================================================ FILE: company/google/PowerOfTwo.java ================================================ //Given an integer, write a function to determine if it is a power of two. // //Example 1: // //Input: 1 //Output: true //Example 2: // //Input: 16 //Output: true //Example 3: // //Input: 218 //Output: false class PowerOfTwo { public boolean isPowerOfTwo(int n) { long i = 1; while(i < n) { i <<= 1; } return i == n; } } ================================================ FILE: company/google/PowerOfXToTheN.java ================================================ // Implement pow(x, n). public class PowerOfXToTheN { public double myPow(double x, int n) { if(n == 0) { return 1; } if(Double.isInfinite(x)) { return 0; } if(n < 0) { n = -n; x = 1 / x; } return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); } } ================================================ FILE: company/google/RegularExpressionMatching.javaa ================================================ // Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } } ================================================ FILE: company/google/ReverseVowelsOfAString.java ================================================ // Write a function that takes a string as input and reverse only the vowels of a string. // Example 1: // Given s = "hello", return "holle". // Example 2: // Given s = "leetcode", return "leotcede". // Note: // The vowels does not include the letter "y". public class ReverseVowelsOfAString { public String reverseVowels(String s) { if(s == null || s.length() == 0) { return s; } String vowels = "aeiouAEIOU"; char[] chars = s.toCharArray(); int start = 0; int end = s.length() - 1; while(start < end) { while(start < end && !vowels.contains(chars[start] + "")) { start++; } while(start < end && !vowels.contains(chars[end] + "")) { end--; } char temp = chars[start]; chars[start] = chars[end]; chars[end] = temp; start++; end--; } return new String(chars); } } ================================================ FILE: company/google/SentenceScreenFitting.java ================================================ // Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. // Note: // A word cannot be split into two lines. // The order of words in the sentence must remain unchanged. // Two consecutive words in a line must be separated by a single space. // Total words in the sentence won't exceed 100. // Length of each word is greater than 0 and won't exceed 10. // 1 ≤ rows, cols ≤ 20,000. // Example 1: // Input: // rows = 2, cols = 8, sentence = ["hello", "world"] // Output: // 1 // Explanation: // hello--- // world--- // The character '-' signifies an empty space on the screen. // Example 2: // Input: // rows = 3, cols = 6, sentence = ["a", "bcd", "e"] // Output: // 2 // Explanation: // a-bcd- // e-a--- // bcd-e- // The character '-' signifies an empty space on the screen. // Example 3: // Input: // rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] // Output: // 1 // Explanation: // I-had // apple // pie-I // had-- // The character '-' signifies an empty space on the screen. public class SentenceScreenFitting { public int wordsTyping(String[] sentence, int rows, int cols) { String s = String.join(" ", sentence) + " "; int start = 0; int l = s.length(); for(int i = 0; i < rows; i++) { start += cols; if(s.charAt(start % l) == ' ') { start++; } else { while(start > 0 && s.charAt((start - 1) % l) != ' ') { start--; } } } return start / s.length(); } } ================================================ FILE: company/google/ShortestDistanceFromAllBuildings.java ================================================ // You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: // Each 0 marks an empty land which you can pass by freely. // Each 1 marks a building which you cannot pass through. // Each 2 marks an obstacle which you cannot pass through. // For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2): // 1 - 0 - 2 - 0 - 1 // | | | | | // 0 - 0 - 0 - 0 - 0 // | | | | | // 0 - 0 - 1 - 0 - 0 // The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. // Note: // There will be at least one building. If it is not possible to build such house according to the above rules, return -1. public class ShortestDistanceFromAllBuildings { public int shortestDistance(int[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return -1; } final int[] shift = {0, 1, 0, -1, 0}; int rows = grid.length; int columns = grid[0].length; int[][] distance = new int[rows][columns]; int[][] reach = new int[rows][columns]; int numberOfBuildings = 0; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 1) { numberOfBuildings++; Queue queue = new LinkedList(); queue.offer(new int[] {i, j}); boolean[][] visited = new boolean[rows][columns]; int relativeDistance = 1; while(!queue.isEmpty()) { int qSize = queue.size(); for(int q = 0; q < qSize; q++) { int[] current = queue.poll(); for(int k = 0; k < 4; k++) { int nextRow = current[0] + shift[k]; int nextColumn = current[1] + shift[k + 1]; if(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && grid[nextRow][nextColumn] == 0 && !visited[nextRow][nextColumn]) { distance[nextRow][nextColumn] += relativeDistance; reach[nextRow][nextColumn]++; visited[nextRow][nextColumn] = true; queue.offer(new int[] {nextRow, nextColumn}); } } } relativeDistance++; } } } } int shortest = Integer.MAX_VALUE; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 0 && reach[i][j] == numberOfBuildings) { shortest = Math.min(shortest, distance[i][j]); } } } return shortest == Integer.MAX_VALUE ? -1 : shortest; } } ================================================ FILE: company/google/SpiralMatrix.java ================================================ //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // //Example 1: // //Input: //[ //[ 1, 2, 3 ], //[ 4, 5, 6 ], //[ 7, 8, 9 ] //] //Output: [1,2,3,6,9,8,7,4,5] //Example 2: // //Input: //[ //[1, 2, 3, 4], //[5, 6, 7, 8], //[9,10,11,12] //] //Output: [1,2,3,4,8,12,11,10,9,5,6,7] class SpiralMatrix { public List spiralOrder(int[][] matrix) { List result = new ArrayList(); if(matrix == null || matrix.length == 0) { return result; } int rowStart = 0; int rowEnd = matrix.length - 1; int colStart = 0; int colEnd = matrix[0].length - 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { result.add(matrix[rowStart][i]); } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { result.add(matrix[i][colEnd]); } colEnd--; if(rowStart <= rowEnd) { for(int i = colEnd; i >= colStart; i--) { result.add(matrix[rowEnd][i]); } } rowEnd--; if(colStart <= colEnd) { for(int i = rowEnd; i >= rowStart; i--) { result.add(matrix[i][colStart]); } } colStart++; } return result; } } ================================================ FILE: company/google/StrobogrammaticNumber.java ================================================ // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). // Write a function to determine if a number is strobogrammatic. The number is represented as a string. // For example, the numbers "69", "88", and "818" are all strobogrammatic. public class StrobogrammaticNumber { public boolean isStrobogrammatic(String num) { for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { return false; } } return true; } } ================================================ FILE: company/google/SummaryRanges.java ================================================ // Given a sorted integer array without duplicates, return the summary of its ranges. // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. public class SummaryRanges { public List summaryRanges(int[] nums) { List result = new ArrayList(); if(nums.length == 1) { result.add(nums[0] + ""); return result; } for(int i = 0; i < nums.length; i++) { int current = nums[i]; while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) { i++; } if(current != nums[i]) { result.add(current + "->" + nums[i]); } else { result.add(current + ""); } } return result; } } ================================================ FILE: company/google/TrappingRainWater.java ================================================ // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // For example, // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. public class TrappingRainWater { public int trap(int[] height) { int water = 0; int leftIndex = 0; int rightIndex = height.length - 1; int leftMax = 0; int rightMax = 0; while(leftIndex <= rightIndex) { leftMax = Math.max(leftMax, height[leftIndex]); rightMax = Math.max(rightMax, height[rightIndex]); if(leftMax < rightMax) { water += leftMax - height[leftIndex]; leftIndex++; } else { water += rightMax - height[rightIndex]; rightIndex--; } } return water; } } ================================================ FILE: company/google/UniqueWordAbbreviation.java ================================================ // An abbreviation of a word follows the form . Below are some examples of word abbreviations: // a) it --> it (no abbreviation) // 1 // b) d|o|g --> d1g // 1 1 1 // 1---5----0----5--8 // c) i|nternationalizatio|n --> i18n // 1 // 1---5----0 // d) l|ocalizatio|n --> l10n // Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. // Example: // Given dictionary = [ "deer", "door", "cake", "card" ] // isUnique("dear") -> // false // isUnique("cart") -> // true // isUnique("cane") -> // false // isUnique("make") -> // true import java.util.ArrayList; public class UniqueWordAbbreviation { HashMap map; public ValidWordAbbr(String[] dictionary) { this.map = new HashMap(); for(String word : dictionary) { String key = getKey(word); if(map.containsKey(key)) { if(!map.get(key).equals(word)) { map.put(key, ""); } } else { map.put(key, word); } } } public boolean isUnique(String word) { return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word); } public String getKey(String word) { if(word.length() <= 2) { return word; } return word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1); } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord"); ================================================ FILE: company/google/Utf8Validation.java ================================================ // A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: // For 1-byte character, the first bit is a 0, followed by its unicode code. // For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. // This is how the UTF-8 encoding would work: // Char. number range | UTF-8 octet sequence // (hexadecimal) | (binary) // --------------------+--------------------------------------------- // 0000 0000-0000 007F | 0xxxxxxx // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // Given an array of integers representing the data, return whether it is a valid utf-8 encoding. // Note: // The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. // Example 1: // data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. // Return true. // It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. // Example 2: // data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. // Return false. // The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. // The next byte is a continuation byte which starts with 10 and that's correct. // But the second continuation byte does not start with 10, so it is invalid. public class Utf8Validation { public boolean validUtf8(int[] data) { int count = 0; for(int i : data) { if(count == 0) { if((i >> 5) == 0b110) { count = 1; } else if((i >> 4) == 0b1110) { count = 2; } else if((i >> 3) == 0b11110) { count = 3; } else if((i >> 7) == 0b1) { return false; } } else { if((i >> 6) != 0b10) { return false; } count--; } } return count == 0; } } ================================================ FILE: company/google/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: company/google/WallsAndGates.java ================================================ // You are given a m x n 2D grid initialized with these three possible values. // -1 - A wall or an obstacle. // 0 - A gate. // INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. // Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. // For example, given the 2D grid: // INF -1 0 INF // INF INF INF -1 // INF -1 INF -1 // 0 -1 INF INF // After running your function, the 2D grid should be: // 3 -1 0 1 // 2 2 1 -1 // 1 -1 2 -1 // 0 -1 3 4 public class WallsAndGates { public void wallsAndGates(int[][] rooms) { //iterate through the matrix calling dfs on all indices that contain a zero for(int i = 0; i < rooms.length; i++) { for(int j = 0; j < rooms[0].length; j++) { if(rooms[i][j] == 0) { dfs(rooms, i, j, 0); } } } } void dfs(int[][] rooms, int i, int j, int distance) { //if you have gone out of the bounds of the array or you have run into a wall/obstacle, return // room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) { return; } //set current index's distance to distance rooms[i][j] = distance; //recurse on all adjacent neighbors of rooms[i][j] dfs(rooms, i + 1, j, distance + 1); dfs(rooms, i - 1, j, distance + 1); dfs(rooms, i, j + 1, distance + 1); dfs(rooms, i, j - 1, distance + 1); } } ================================================ FILE: company/google/WiggleSort.java ================================================ // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. public class WiggleSort { public void wiggleSort(int[] nums) { for(int i = 1; i < nums.length; i++) { int current = nums[i - 1]; if((i % 2 == 1) == (current > nums[i])) { nums[i - 1] = nums[i]; nums[i] = current; } } } } ================================================ FILE: company/google/WordBreak.java ================================================ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } } ================================================ FILE: company/google/WordSquares.java ================================================ // Given a set of words (without duplicates), find all word squares you can build from them. // A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). // For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. // b a l l // a r e a // l e a d // l a d y // Note: // There are at least 1 and at most 1000 words. // All words will have the exact same length. // Word length is at least 1 and at most 5. // Each word contains only lowercase English alphabet a-z. public class WordSquares { public List> wordSquares(String[] words) { List> ret = new ArrayList>(); if(words.length==0 || words[0].length()==0) { return ret; } Map> map = new HashMap<>(); int squareLen = words[0].length(); // create all prefix for(int i=0;i()); } map.get(words[i].substring(0, j+1)).add(words[i]); } } helper(ret, new ArrayList(), 0, squareLen, map); return ret; } public void helper(List> ret, List cur, int matched, int total, Map> map){ if(matched == total) { ret.add(new ArrayList(cur)); return; } // build search string StringBuilder sb = new StringBuilder(); for(int i=0;i<=matched-1;i++) { sb.append(cur.get(i).charAt(matched)); } // bachtracking Set cand = map.get(sb.toString()); if(cand==null) { return; } for(String str:cand){ cur.add(str); helper(ret, cur, matched+1, total, map); cur.remove(cur.size()-1); } } } ================================================ FILE: company/google/ZigZagIterator.java ================================================ // Given two 1d vectors, implement an iterator to return their elements alternately. // For example, given two 1d vectors: // v1 = [1, 2] // v2 = [3, 4, 5, 6] // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. // Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i = new ZigzagIterator(v1, v2); * while (i.hasNext()) v[f()] = i.next(); */ public class ZigZagIterator { private Iterator i; private Iterator j; private Iterator temp; public ZigzagIterator(List v1, List v2) { i = v1.iterator(); j = v2.iterator(); } public int next() { if(i.hasNext()) { temp = i; i = j; j = temp; } return j.next(); } public boolean hasNext() { return i.hasNext() || j.hasNext(); } } ================================================ FILE: company/linkedin/BinarySearchTreeIterator.java ================================================ // Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. // Calling next() will return the next smallest number in the BST. // Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeIterator { Stack stack; public BSTIterator(TreeNode root) { stack = new Stack(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/linkedin/BinaryTreeLevelOrderTraversal.java ================================================ // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree [3,9,20,null,null,15,7], // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeLevelOrderTraversal { public List> levelOrder(TreeNode root) { List> result = new ArrayList>(); if(root == null) { return result; } Queue queue = new LinkedList(); queue.add(root); List tempList = new ArrayList(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue currentLevel = new LinkedList(); List list = new ArrayList(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; } } ================================================ FILE: company/linkedin/FindTheCelebrity.java ================================================ // Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } } ================================================ FILE: company/linkedin/HouseRobber.java ================================================ // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. public class HouseRobber { public int rob(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; for(int i = 2; i < nums.length; i++) { dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); } return dp[dp.length - 1]; } } ================================================ FILE: company/linkedin/InsertInterval.java ================================================ // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). // You may assume that the intervals were initially sorted according to their start times. // Example 1: // Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. // Example 2: // Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. // This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class InsertInterval { public List insert(List intervals, Interval newInterval) { int i = 0; while(i < intervals.size() && intervals.get(i).end < newInterval.start) { i++; } while(i < intervals.size() && intervals.get(i).start <= newInterval.end) { newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end)); intervals.remove(i); } intervals.add(i, newInterval); return intervals; } } ================================================ FILE: company/linkedin/LowestCommonAncestorOfABinaryTree.java ================================================ // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } } ================================================ FILE: company/linkedin/MaximumDepthOfABinaryTree.java ================================================ // Given a binary tree, find its maximum depth. // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class MaximumDepthOfABinaryTree { public int maxDepth(TreeNode root) { if(root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } } ================================================ FILE: company/linkedin/MaximumProductSubarray.java ================================================ // Find the contiguous subarray within an array (containing at least one number) which has the largest product. // For example, given the array [2,3,-2,4], // the contiguous subarray [2,3] has the largest product = 6. public class MaximumProductSubarray { public int maxProduct(int[] nums) { if(nums == null || nums.length == 0) { return 0; } int result = nums[0]; int max = nums[0]; int min = nums[0]; for(int i = 1; i < nums.length; i++) { int temp = max; max = Math.max(Math.max(nums[i] * max, nums[i] * min), nums[i]); min = Math.min(Math.min(nums[i] * temp, nums[i] * min), nums[i]); if(max > result) { result = max; } } return result; } } ================================================ FILE: company/linkedin/MaximumSubarray.java ================================================ // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], // the contiguous subarray [4,-1,2,1] has the largest sum = 6. public class MaximumSubarray { public int maxSubArray(int[] nums) { int[] dp = new int[nums.length]; dp[0] = nums[0]; int max = dp[0]; for(int i = 1; i < nums.length; i++) { dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); max = Math.max(dp[i], max); } return max; } } ================================================ FILE: company/linkedin/MergeIntervals.java ================================================ // Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class MergeIntervals { public List merge(List intervals) { List result = new ArrayList(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } } ================================================ FILE: company/linkedin/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } } ================================================ FILE: company/linkedin/PaintHouse.java ================================================ //There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. //The cost of painting each house with a certain color is different. You have to paint all the houses such //that no two adjacent houses have the same color. //The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, //costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 //with color green, and so on... Find the minimum cost to paint all houses. //Note: //All costs are positive integers. class PaintHouse { public int minCost(int[][] costs) { if(costs == null || costs.length == 0) { return 0; } for(int i = 1; i < costs.length; i++) { costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]); costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]); } return Math.min(Math.min(costs[costs.length - 1][0], costs[costs.length - 1][1]), costs[costs.length - 1][2]); } } ================================================ FILE: company/linkedin/PalindromicSubstrings.java ================================================ //Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } } ================================================ FILE: company/linkedin/Permutations.java ================================================ //Given a collection of distinct numbers, return all possible permutations. // //For example, //[1,2,3] have the following permutations: //[ //[1,2,3], //[1,3,2], //[2,1,3], //[2,3,1], //[3,1,2], //[3,2,1] //] class Permutations { public List> permute(int[] nums) { LinkedList> result = new LinkedList>(); result.add(new ArrayList()); for (int n: nums) { int size = result.size(); while(size > 0) { List current = result.pollFirst(); for (int i = 0; i <= current.size(); i++) { List temp = new ArrayList(current); temp.add(i, n); result.add(temp); } size--; } } return result; } } ================================================ FILE: company/linkedin/PowerOfXToTheN.java ================================================ // Implement pow(x, n). public class PowerOfXToTheN { public double myPow(double x, int n) { if(n == 0) { return 1; } if(Double.isInfinite(x)) { return 0; } if(n < 0) { n = -n; x = 1 / x; } return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); } } ================================================ FILE: company/linkedin/ProductOfArrayExceptSelf.java ================================================ // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. // Solve it without division and in O(n). // For example, given [1,2,3,4], return [24,12,8,6]. // Follow up: // Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n]; int left = 1; for(int i = 0; i < nums.length; i++) { if(i > 0) { left *= nums[i - 1]; } result[i] = left; } int right = 1; for(int i = n - 1; i >= 0; i--) { if(i < n - 1) { right *= nums[i + 1]; } result[i] *= right; } return result; } } ================================================ FILE: company/linkedin/SearchInRotatedSortedArray.java ================================================ // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } } ================================================ FILE: company/linkedin/SparseMatrixMultiplication.java ================================================ // Given two sparse matrices A and B, return the result of AB. // You may assume that A's column number is equal to B's row number. // Example: // A = [ // [ 1, 0, 0], // [-1, 0, 3] // ] // B = [ // [ 7, 0, 0 ], // [ 0, 0, 0 ], // [ 0, 0, 1 ] // ] // | 1 0 0 | | 7 0 0 | | 7 0 0 | // AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // | 0 0 1 | public class SparseMatrixMultiplication { public int[][] multiply(int[][] A, int[][] B) { int m = A.length; int n = A[0].length; int nB = B[0].length; int[][] C = new int[m][nB]; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(A[i][j] != 0) { for(int k = 0; k < nB; k++) { if(B[j][k] != 0) { C[i][k] += A[i][j] * B[j][k]; } } } } } return C; } } ================================================ FILE: company/linkedin/SymmetricTree.java ================================================ // Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). // For example, this binary tree [1,2,2,3,4,4,3] is symmetric: // 1 // / \ // 2 2 // / \ / \ // 3 4 4 3 // But the following [1,2,2,null,3,null,3] is not: // 1 // / \ // 2 2 // \ \ // 3 3 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SymmetricTree { public boolean isSymmetric(TreeNode root) { if(root == null) { return true; } return helper(root.left, root.right); } public boolean helper(TreeNode left, TreeNode right) { if(left == null && right == null) { return true; } if(left == null || right == null || left.val != right.val) { return false; } return helper(left.right, right.left) && helper(left.left, right.right); } } ================================================ FILE: company/linkedin/TwoSum.java ================================================ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // Example: // Given nums = [2, 7, 11, 15], target = 9, // Because nums[0] + nums[1] = 2 + 7 = 9, // return [0, 1]. public class TwoSum { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: company/microsoft/AddDigits.java ================================================ //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } } ================================================ FILE: company/microsoft/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: company/microsoft/HouseRobberII.java ================================================ //Note: This is an extension of House Robber. (security system is tripped if two ajacent houses are robbed) //After robbing those houses on that street, the thief has found himself a new place for his thievery so that //he will not get too much attention. This time, all houses at this place are arranged in a circle. That means //the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the //same as for those in the previous street. //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. class HouseRobberII { public int rob(int[] nums) { if (nums.length == 0) { return 0; } if (nums.length < 2) { return nums[0]; } int[] first = new int[nums.length + 1]; int[] second = new int[nums.length + 1]; first[0] = 0; first[1] = nums[0]; second[0] = 0; second[1] = 0; for (int i = 2; i <= nums.length; i++) { first[i] = Math.max(first[i - 1], first[i - 2] + nums[i - 1]); second[i] = Math.max(second[i - 1], second[i - 2] + nums[i - 1]); } return Math.max(first[nums.length - 1], second[nums.length]); } } ================================================ FILE: company/microsoft/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: company/microsoft/LongestIncreasingSubsequence.java ================================================ //Given an unsorted array of integers, find the length of longest increasing subsequence. //For example, //Given [10, 9, 2, 5, 3, 7, 101, 18], //The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. //Your algorithm should run in O(n2) complexity. //Follow up: Could you improve it to O(n log n) time complexity? class LongestIncreasingSubsequence { public int lengthOfLIS(int[] nums) { if(nums == null || nums.length < 1) { return 0; } int[] dp = new int[nums.length]; dp[0] = 1; int max = 1; for(int i = 1; i < dp.length; i++) { int currentMax = 0; for(int j = 0; j < i; j++) { if(nums[i] > nums[j]) { currentMax = Math.max(currentMax, dp[j]); } } dp[i] = 1 + currentMax; max = Math.max(max, dp[i]); } return max; } } ================================================ FILE: company/microsoft/LongestPalindromicSubstring.java ================================================ //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. //Example: //Input: "babad" //Output: "bab" //Note: "aba" is also a valid answer. //Example: //Input: "cbbd" //Output: "bb" class LongestPalindromicSubstring { public String longestPalindrome(String s) { if(s == null || s.length() == 0) { return ""; } String longestPalindromicSubstring = ""; for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) { longestPalindromicSubstring = s.substring(i, j); } } } return longestPalindromicSubstring; } public boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; while(i <= j) { if(s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } } ================================================ FILE: company/microsoft/Permutations.java ================================================ //Given a collection of distinct numbers, return all possible permutations. // //For example, //[1,2,3] have the following permutations: //[ //[1,2,3], //[1,3,2], //[2,1,3], //[2,3,1], //[3,1,2], //[3,2,1] //] class Permutations { public List> permute(int[] nums) { LinkedList> result = new LinkedList>(); result.add(new ArrayList()); for (int n: nums) { int size = result.size(); while(size > 0) { List current = result.pollFirst(); for (int i = 0; i <= current.size(); i++) { List temp = new ArrayList(current); temp.add(i, n); result.add(temp); } size--; } } return result; } } ================================================ FILE: company/microsoft/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: company/microsoft/SpiralMatrix.java ================================================ //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // //Example 1: // //Input: //[ //[ 1, 2, 3 ], //[ 4, 5, 6 ], //[ 7, 8, 9 ] //] //Output: [1,2,3,6,9,8,7,4,5] //Example 2: // //Input: //[ //[1, 2, 3, 4], //[5, 6, 7, 8], //[9,10,11,12] //] //Output: [1,2,3,4,8,12,11,10,9,5,6,7] class SpiralMatrix { public List spiralOrder(int[][] matrix) { List result = new ArrayList(); if(matrix == null || matrix.length == 0) { return result; } int rowStart = 0; int rowEnd = matrix.length - 1; int colStart = 0; int colEnd = matrix[0].length - 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { result.add(matrix[rowStart][i]); } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { result.add(matrix[i][colEnd]); } colEnd--; if(rowStart <= rowEnd) { for(int i = colEnd; i >= colStart; i--) { result.add(matrix[rowEnd][i]); } } rowEnd--; if(colStart <= colEnd) { for(int i = rowEnd; i >= rowStart; i--) { result.add(matrix[i][colStart]); } } colStart++; } return result; } } ================================================ FILE: company/palantir/ContainsDuplicate.java ================================================ //Given an array of integers, find if the array contains any duplicates. Your function should return //true if any value appears at least twice in the array, and it should return false if every element is distinct. class ContainsDuplicate { public boolean containsDuplicate(int[] nums) { HashMap map = new HashMap(); for(int i: nums) { if(map.containsKey(i)) { return true; } else { map.put(i, 1); } } return false; } } ================================================ FILE: company/palantir/ContainsDuplicatesII.java ================================================ //Given an array of integers and an integer k, find out whether there are two distinct indices i and //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class ContainsDuplicatesII { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap(); for(int i = 0; i < nums.length; i++) { int current = nums[i]; if(map.containsKey(current) && i - map.get(current) <= k) { return true; } else { map.put(current, i); } } return false; } } ================================================ FILE: company/snapchat/MinStack.java ================================================ //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: company/snapchat/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: company/snapchat/ValidSudoku.java ================================================ //Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx) //The Sudoku board could be partially filled, where empty cells are filled with the character '.'. //A partially filled sudoku which is valid. //Note: //A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. class ValidSudoku { public boolean isValidSudoku(char[][] board) { for(int i = 0; i < board.length; i++){ HashSet rows = new HashSet(); HashSet columns = new HashSet(); HashSet box = new HashSet(); for (int j = 0; j < board[0].length; j++){ if(board[i][j] != '.' && !rows.add(board[i][j])) { return false; } if(board[j][i]!='.' && !columns.add(board[j][i])) { return false; } int rowIndex = (i / 3) * 3; int columnIndex = (i % 3) * 3; if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) { return false; } } } return true; } } ================================================ FILE: company/twitter/FlattenNestedListIterator.java ================================================ // Given a nested list of integers, implement an iterator to flatten it. // Each element is either an integer, or a list -- whose elements may also be integers or other lists. // Example 1: // Given the list [[1,1],2,[1,1]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. // Example 2: // Given the list [1,[4,[6]]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List getList(); * } */ public class FlattenNestedListIterator implements Iterator { Stack stack = new Stack(); public NestedIterator(List nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger current = stack.peek(); if(current.isInteger()) { return true; } stack.pop(); for(int i = current.getList().size() - 1; i >= 0; i--) { stack.push(current.getList().get(i)); } } return false; } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: company/twitter/ImplementTrie.java ================================================ // Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap(); this.character = character; this.last = false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } } ================================================ FILE: company/twitter/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/twitter/LowestCommonAncestorOfABinaryTree.java ================================================ // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } } ================================================ FILE: company/twitter/MergeIntervals.java ================================================ // Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class MergeIntervals { public List merge(List intervals) { List result = new ArrayList(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } } ================================================ FILE: company/twitter/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } } ================================================ FILE: company/twitter/OneEditDistance.java ================================================ // Given two strings S and T, determine if they are both one edit distance apart. public class OneEditDistance { public boolean isOneEditDistance(String s, String t) { //iterate through the length of the smaller string for(int i = 0; i < Math.min(s.length(), t.length()); i++) { //if the current characters of the two strings are not equal if(s.charAt(i) != t.charAt(i)) { //return true if the remainder of the two strings are equal, false otherwise if(s.length() == t.length()) { return s.substring(i + 1).equals(t.substring(i + 1)); } else if(s.length() < t.length()) { //return true if the strings would be the same if you deleted a character from string t return s.substring(i).equals(t.substring(i + 1)); } else { //return true if the strings would be the same if you deleted a character from string s return t.substring(i).equals(s.substring(i + 1)); } } } //if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1 return Math.abs(s.length() - t.length()) == 1; } } ================================================ FILE: company/twitter/RegularExpressionMatching.java ================================================ // Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } } ================================================ FILE: company/twitter/ReverseLinkedList.java ================================================ // Reverse a singly linked list. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } } ================================================ FILE: company/twitter/TrappingRainWater.java ================================================ // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // For example, // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. public class TrappingRainWater { public int trap(int[] height) { int water = 0; int leftIndex = 0; int rightIndex = height.length - 1; int leftMax = 0; int rightMax = 0; while(leftIndex <= rightIndex) { leftMax = Math.max(leftMax, height[leftIndex]); rightMax = Math.max(rightMax, height[rightIndex]); if(leftMax < rightMax) { water += leftMax - height[leftIndex]; leftIndex++; } else { water += rightMax - height[rightIndex]; rightIndex--; } } return water; } } ================================================ FILE: company/twitter/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: company/uber/BestTimeToBuyOrSellStock.java ================================================ // Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Example 1: // Input: [7, 1, 5, 3, 6, 4] // Output: 5 // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) // Example 2: // Input: [7, 6, 4, 3, 1] // Output: 0 // In this case, no transaction is done, i.e. max profit = 0. public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { //Kadane's algorithm if(prices.length == 0) { return 0; } int max = 0; int min = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] > min) { max = Math.max(max, prices[i] - min); } else { min = prices[i]; } } return max; } } ================================================ FILE: company/uber/CloneGraph.java ================================================ // Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } * }; */ public class CloneGraph { public HashMap map = new HashMap(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } } ================================================ FILE: company/uber/DecodeWays.java ================================================ // A message containing letters from A-Z is being encoded to numbers using the following mapping: // 'A' -> 1 // 'B' -> 2 // ... // 'Z' -> 26 // Given an encoded message containing digits, determine the total number of ways to decode it. // For example, // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). // The number of ways decoding "12" is 2. public class DecodeWays { public int numDecodings(String s) { int n = s.length(); if(n == 0) { return 0; } int[] dp = new int[n + 1]; dp[n] = 1; dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; for(int i = n - 2; i >= 0; i--) { if(s.charAt(i) == '0') { continue; } else { dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; } } return dp[0]; } } ================================================ FILE: company/uber/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: company/uber/ExclusiveTimeOfFunctions.java ================================================ //Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List logs) { Stack stack = new Stack (); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } } ================================================ FILE: company/uber/GenerateParentheses.java ================================================ class GenerateParentheses { public List generateParenthesis(int n) { List result = new ArrayList(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } } ================================================ FILE: company/uber/GroupAnagrams.java ================================================ // Given an array of strings, group anagrams together. // For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], // Return: // [ // ["ate", "eat","tea"], // ["nat","tan"], // ["bat"] // ] // Note: All inputs will be in lower-case. public class GroupAnagrams { public List> groupAnagrams(String[] strs) { if(strs == null || strs.length == 0) { return new ArrayList>(); } HashMap> map = new HashMap>(); Arrays.sort(strs); for(String s : strs) { char[] characters = s.toCharArray(); Arrays.sort(characters); String key = String.valueOf(characters); if(!map.containsKey(key)) { map.put(key, new ArrayList()); } map.get(key).add(s); } return new ArrayList>(map.values()); } } ================================================ FILE: company/uber/GroupShiftedStrings.java ================================================ // Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List> groupStrings(String[] strings) { List> result = new ArrayList>(); HashMap> map = new HashMap>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List list = new ArrayList(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List list = map.get(key); Collections.sort(list); result.add(list); } return result; } } ================================================ FILE: company/uber/ImplementTrie.java ================================================ // Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap(); this.character = character; this.last = false; } } public class ImplementTrie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } } ================================================ FILE: company/uber/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/uber/LetterCombinationsOfAPhoneNumber.java ================================================ // Given a digit string, return all possible letter combinations that the number could represent. // A mapping of digit to letters (just like on the telephone buttons) is given below. // 2 - abc // 3 - def // 4 - ghi // 5 - jkl // 6 - mno // 7 - pqrs // 8 - tuv // 9 - wxyz // Input:Digit string "23" // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class LetterCombinationsOfAPhoneNumber { public List letterCombinations(String digits) { List result = new ArrayList(); if(digits == null || digits.length() == 0) { return result; } String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; letterCombinationsRecursive(result, digits, "", 0, mapping); return result; } public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) { if(index == digits.length()) { result.add(current); return; } String letters = mapping[digits.charAt(index) - '0']; for(int i = 0; i < letters.length(); i++) { letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); } } } ================================================ FILE: company/uber/MaximumDepthOfABinaryTree.java ================================================ // Given a binary tree, find its maximum depth. // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class MaximumDepthOfABinaryTree { public int maxDepth(TreeNode root) { if(root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } } ================================================ FILE: company/uber/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } } ================================================ FILE: company/uber/OneEditDistance.java ================================================ // Given two strings S and T, determine if they are both one edit distance apart. public class OneEditDistance { public boolean isOneEditDistance(String s, String t) { //iterate through the length of the smaller string for(int i = 0; i < Math.min(s.length(), t.length()); i++) { //if the current characters of the two strings are not equal if(s.charAt(i) != t.charAt(i)) { //return true if the remainder of the two strings are equal, false otherwise if(s.length() == t.length()) { return s.substring(i + 1).equals(t.substring(i + 1)); } else if(s.length() < t.length()) { //return true if the strings would be the same if you deleted a character from string t return s.substring(i).equals(t.substring(i + 1)); } else { //return true if the strings would be the same if you deleted a character from string s return t.substring(i).equals(s.substring(i + 1)); } } } //if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1 return Math.abs(s.length() - t.length()) == 1; } } ================================================ FILE: company/uber/PalindromePermutation.java ================================================ public class PalindromePermutation { public boolean canPermutePalindrome(String s) { char[] characters = new char[256]; for(int i = 0; i < s.length(); i++) { characters[s.charAt(i)]++; } int oddCount = 0; for(int i = 0; i < characters.length; i++) { if(!(characters[i] % 2 == 0)) { oddCount++; if(oddCount > 1) { return false; } } } return true; } } ================================================ FILE: company/uber/RegularExpressionMatching.java ================================================ // Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } } ================================================ FILE: company/uber/ReverseLinkedList.java ================================================ // Reverse a singly linked list. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } } ================================================ FILE: company/uber/RomanToInteger.java ================================================ // Given a roman numeral, convert it to an integer. // Input is guaranteed to be within the range from 1 to 3999 public class RomanToInteger { public int romanToInt(String s) { HashMap map = new HashMap(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int total = 0; for(int i = 0; i < s.length() - 1; i++) { if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { total -= map.get(s.charAt(i)); } else { total += map.get(s.charAt(i)); } } total += map.get(s.charAt(s.length() - 1)); return total; } } ================================================ FILE: company/uber/SearchInRotatedSortedArray.java ================================================ // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } } ================================================ FILE: company/uber/SpiralMatrix.java ================================================ //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // //Example 1: // //Input: //[ //[ 1, 2, 3 ], //[ 4, 5, 6 ], //[ 7, 8, 9 ] //] //Output: [1,2,3,6,9,8,7,4,5] //Example 2: // //Input: //[ //[1, 2, 3, 4], //[5, 6, 7, 8], //[9,10,11,12] //] //Output: [1,2,3,4,8,12,11,10,9,5,6,7] class SpiralMatrix { public List spiralOrder(int[][] matrix) { List result = new ArrayList(); if(matrix == null || matrix.length == 0) { return result; } int rowStart = 0; int rowEnd = matrix.length - 1; int colStart = 0; int colEnd = matrix[0].length - 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { result.add(matrix[rowStart][i]); } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { result.add(matrix[i][colEnd]); } colEnd--; if(rowStart <= rowEnd) { for(int i = colEnd; i >= colStart; i--) { result.add(matrix[rowEnd][i]); } } rowEnd--; if(colStart <= colEnd) { for(int i = rowEnd; i >= rowStart; i--) { result.add(matrix[i][colStart]); } } colStart++; } return result; } } ================================================ FILE: company/uber/Subsets.java ================================================ // Given a set of distinct integers, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] public class Subsets { public List> subsets(int[] nums) { List> result = new ArrayList<>(); recurse(result, nums, new Stack<>(), 0); return result; } private void recurse(List> result, int[] nums, Stack path, int position) { if(position == nums.length) { result.add(new ArrayList<>(path)); return; } path.push(nums[position]); recurse(result, nums, path, position + 1); path.pop(); recurse(result, nums, path, position + 1); } } ================================================ FILE: company/uber/TwoSum.java ================================================ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // Example: // Given nums = [2, 7, 11, 15], target = 9, // Because nums[0] + nums[1] = 2 + 7 = 9, // return [0, 1]. public class TwoSum { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: company/uber/ValidPalindrome.java ================================================ public class ValidPalindrome { public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while(left < right) { while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { left++; } while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { right--; } if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } } ================================================ FILE: company/uber/ValidSudoku.java ================================================ //Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx) //The Sudoku board could be partially filled, where empty cells are filled with the character '.'. //A partially filled sudoku which is valid. //Note: //A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. class ValidSudoku { public boolean isValidSudoku(char[][] board) { for(int i = 0; i < board.length; i++){ HashSet rows = new HashSet(); HashSet columns = new HashSet(); HashSet box = new HashSet(); for (int j = 0; j < board[0].length; j++){ if(board[i][j] != '.' && !rows.add(board[i][j])) { return false; } if(board[j][i]!='.' && !columns.add(board[j][i])) { return false; } int rowIndex = (i / 3) * 3; int columnIndex = (i % 3) * 3; if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) { return false; } } } return true; } } ================================================ FILE: company/uber/WordBreak.java ================================================ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } } ================================================ FILE: company/yahoo/ContainsDuplicate.java ================================================ //Given an array of integers, find if the array contains any duplicates. Your function should return //true if any value appears at least twice in the array, and it should return false if every element is distinct. class ContainsDuplicate { public boolean containsDuplicate(int[] nums) { HashMap map = new HashMap(); for(int i: nums) { if(map.containsKey(i)) { return true; } else { map.put(i, 1); } } return false; } } ================================================ FILE: company/yahoo/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: company/yelp/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: company/yelp/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: cracking-the-coding-interview/CrackingTheCodingInterview.iml ================================================ ================================================ FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/BinaryRepresentation.java ================================================ /* given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print * the binary representation. If the number cannot be represented accurately in binary * with at most 32 characters, print "ERROR" */ public class BinaryRepresentation { public static String printBinary(double num) { if(num >= 1 || num <= 0) { return "ERROR"; } StrinBuilder binary = new StringBuilder(); binary.append("."); while(num > 0) { /* setting a limit on length: 32 characters */ if(binary.length() >= 32) { return "ERROR"; } double r = num * 2; if(r >= 1) { binary.append(1); num = r - 1; } else { binary.append(0); num = r; } } return binary.toString(); } } ================================================ FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/FindMissingInteger.java ================================================ /* An array A contains all the integers from 0 through n, except for one number which is * missing. In this problem, we cannot access an entire integer in A with a single operation. * The elements of A are represented in binary, and the only operation we can use to acces them * is "fetch the jth bit of A[i]," which takes constant time. Write code to find the missing * integer. Can you do it in O(n) time? */ public class FindMissingInteger { public int findMissing(ArrayList array) { /* start from the least significant bit, and work our way up */ return findMissing(array, 0); } public int findMissing(ArrayList input, int column) { if(column >= BigInteger.INTEGER_SIZE) { //we're done! return 0; } ArrayList oneBits = new ArrayList(input.size() / 2); ArrayList zeroBits = new ArrayList(input.size() / 2); for(BigInteger t : input) { if(t.fetch(column) == 0) { zeroBits.add(t); } else { oneBits.add(t); } } if(zeroBits.size() <= oneBits.size()) { int v = findMissing(zeroBits, column + 1); return (v << 1) | 0; } else { int v = findMissing(oneBits, column + 1); return (v << 1) | 1; } } } ================================================ FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/InsertMIntoN.java ================================================ /* you are given two 32-bit numbers, N and M, are two bit positions, i and j. Write * a method to insert M into N such that M starts at bit j and ends at bit i. You can * assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, * you can assume that there are at least 5 bits between j and i. You would not, for example, * have j = 3 and i = 2, because M could not fully bit between bit 3 and bit 2. EXAMPLE: Input: N = 10000000000, m = 10011, i = 2, j = 6 Output: N = 10001001100 */ public class InsertMIntoN { int updateBits(int n, int m, int i, int j) { /* create a mask to clear bits i through j in n * EXAMPLE: i = 2, j = 4. Result should be 11100011. * For simplicity, we'll just use 8 bits for the example. */ int allones = ~0; //wil equal sequence of all 1s //1s before position j, then 0s. Left = 11100000 int left = allOnes << (j + 1); //1s after position i. Right = 00000011 int right = ((1 << i) - 1); //all 1s, except for 0s between i and j. Mask = 11100011 int mask = left | right; /* clear bits j through i then put m in there */ int n_cleared = n & mask; //clear bits j through i int m_shifted = m << i; //move m into correct position return n_cleared | m_shifted; //OR them, and we're done! } } ================================================ FILE: cracking-the-coding-interview/chapter-five-bit-manipulation/SwapBits.java ================================================ /* write a program to swap odd and even bits in an integer with as few instructions as * possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) */ public class SwapBits { public int swapOddEvenBits(int x) { return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) ); } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/BinaryTreeIsBalanced.java ================================================ /* implement a function to check if a binary tree is balanced. For the purpose of this * question, a balanced tree is defined to be a tree such that the heights of the two * subtrees of any node never differ by more than one */ public class BinaryTreeIsBalanaced { public static int getHeight(TreeNode root) { if(root == null) { return 0; //base case } return Math.max(getHeight(root.left), getHeight(root.right)) + 1; } public static boolean isBalanced(TreeNode root) { if(root == null) { //base case return true; } int heightDiff = getHeight(root.left) - getHeight(root.right); if(Math.abs(heightDiff) > 1) { return false; } else { //recurse return isBalanced(root.left) && isBalanced(root.right); } } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateBinarySearchTree.java ================================================ /* given a sorted (increasing order) array with unique integer elements, write an algorithm * to create a binary search tree with minimal height */ public class CreateBinarySearchTree { TreeNode createMinimalBST(int arr[], int start, int end) { if(end < start) { return null; } int mid = (start + end) / 2; TreeNode n = new TreeNode(arr[mid]); n.left = createMinimalBST(arr, start, mid - 1); n.right = createMinimalBST(arr, mid + 1, end); return n; } TreeNode createMinimalBST(int array[]) { return createMinimalBST(array, 0, array.length - 1); } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateLinkedListForEachLevel.java ================================================ /* given a binary tree, design an algorithm which creates a linked list of all the nodes * at each depth (e.g., if you have a tree with depth D, you'll have D linked lists) */ public class CreateLinkedListForEachLevel { ArrayList> createLinkedList(TreeNode root) { ArrayList> result = new ArrayList>(); /* "visit" the root */ LinkedList current = new LinkedList(); if(root != null) { current.add(root); } while(current.size() > 0) { result.add(current); //add previous level LinkedList parents = current; //go to next level current = new LinkedList(); for(TreeNode parent : parents) { /* visit the children */ if(parent.left != null) { current.add(parrent.left); } if(parent.right != null) { current.add(parent.right); } } } return result; } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/FindPath.java ================================================ /* give a directed graph, design an algorithm to find out whether there is a route between two nodes */ public class FindPath { public enum State { Unvisited, Visited, Visiting; } public static boolean search(Graph g, Node start, Node end) { if(start == end) return true; //operates as Queue LinkedList q = new LinkedList(); for(Node u : g.getNodes()) { u.state = State.Unvisited; } start.state = State.Visiting; q.add(start); Node u; while(!q.isEmpty()) { u = q.removeFirst(); //i.e., dequeue() if(u != null) { for(Node v : u.getAdjacent()) { if(v.state == State.Unvisited) { if(v == end) { return true; } else { v.state = State.Visiting; q.add(v); } } } } u.state = State.Visited; } return false; } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/IsSubtree.java ================================================ /* you have two very large binary trees: T1, with millions of nodes, and T2, with hundreds * of nodes. Create an algorithm to decide if T2 is a subtree of T1. * A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n * is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical */ public class IsSubtree { boolean containsTree(TreeNode t1, TreeNode t2) { if(t2 == null) { //the empty tree is always a subtree return true; } return subTree(t1, t2); } boolean subTree(TreeNode r1, TreeNode r2) { if(r1 == null) { return false; //big tree empty & subtree still not found } if(r1.data == r2.data) { if(matchTree(r1, r2)) return true; } return (subTree(r1.left, r2) || subTree(r1.right, r2)); } boolean matchTree(TreeNode r1, TreeNode r2) { if(r2 == null && r1 == null) //if both are empty return true; //nothing left in the subtree //if one, but not both, are empty if(r1 == null || r2 == null) { return false; } if(r1.data != r2.data) return false; //data doesn't match return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right)); } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/PrintPaths.java ================================================ /* you are given a binary tree in which each ndoe contains an integer value (which might be positive * or negative). Design an algorithm to print all paths which sum to a given value. The path does not need * to start or end at the root or a leaf, but it must go in a straight line */ public class PrintPaths { void findSum(TreeNode node, int sum, int[] path, int level) { if(node == null) { return; } /* insert current node into path */ path[level] = node.data; /* look for paths with a sum that ends at this node */ int t = 0; for(int i = level; i >= 0; i--) { t += path[i]; if(t == sum) { print(path, i, level); } } /* search nodes beneath this one */ findSum(node.left, sum, path, level + 1); findSum(node.right, sum, path, level + 1); /* remove current node from path. Not strictly necessary, since * we would ignore this value, but it's good practice */ path[level] = Integer.MIN_VALUE; } void findSum(TreeNode node, int sum) { int depth = depth(node); int[] path = new int[depth]; findSum(node, sum, path, 0); } void print(int[] path, int start, int end) { for(int i = start; i <= end; i++) { System.out.print(path[i] + " "); } System.out.println(); } int depth(TreeNode node) { if(node == null) { return 0; } else { return 1 + Math.max(depth(node.left), depth(node.right)); } } } ================================================ FILE: cracking-the-coding-interview/chapter-four-trees-and-graphs/ValidBinarySearchTree.java ================================================ /* implement a function to check if a binary tree is a binary search tree */ public class ValidBinarySearchTree { boolean checkBST(TreeNode n) { return checkBST(n, null, null); } boolean checkBST(TreeNode n, Integer min, Integer max) { if(n == null) { return true; } if((min != null && n.data <= min) || (max != null && n.data > max)) { return false; } if(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)) { return false; } return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllPermutations.java ================================================ /* write a method to compute all permutations of a string of unique characters */ public class AllPermutations { public static ArrayList getPerms(String str) { if(str == null) { return null; } ArrayList permutations = new ArrayList(); if(str.length() == 0) { //base case permutations.add(""); return permutations; } char first = str.charAt(0); //get the first character String remainder = str.substring(1); //remove the 1st character ArrayList words = getPerms(remainder); for(String word : words) { for(int j = 0; j <= word.length(); j++) { String s = insertCharAt(word, first, j); permutations.add(s); } } return permutations; } public static String insertCharAt(String word, char c, int i) { String start = word.substring(0, i); String end = word.substring(i); return start + c + end; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllSubsets.java ================================================ /* write a method to return all subsets of a set */ public class AllSubsets { ArrayList> getSubsets(ArrayList set, int index) { ArrayList> allsubsets; if(set.size() == index) { //base case - add empty set allsubsets = new ArrayList>(); allsubsets.add(new ArrayList()); //empty set } else { allsubsets = getSubsets(set, index + 1); int item = set.get(index); ArrayList> moresubsets = new ArrayList>(); for(ArrayList subset : allsubsets) { ArrayList newsubset = new ArrayList(); newsubset.addAll(subset); newsubset.add(item); moresubsets.add(newsubset); } allsubsets.addAll(moresubsets); } return allsubsets; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/EightQueens.java ================================================ /* write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them * share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two * that bisect the board */ public class EightQueens { public static final int GRID_SIZE = 8; void placeQueens(int row, Integer[] columns, ArrayList results) { if(row == GRID_SIZE) { //found valid placement results.add(columns.clone()); } else { for(int col = 0; col < GRID_SIZE; col++) { if(checkValid(columns, row, col)) { columns[row] = col; //place queen placeQueens(row + 1, columns, results); } } } } /* check if (row1, column1) is a valid spot for a queen by checking if there * is a queen in the same column or diagonal. We don't need to check it for * queens in the same row because the calling placeQueen only attempts to * place one queen at a time. We know thi srow is empty */ boolean checkValid(Integer[] columns, int row1, int column1) { for(int row2 = 0; row2 < row1; row2++) { int column2 = columns[row2]; /* check if (row2, column2) invalides (row1, column1) as a queen spot */ /* check if rows have a queen in the same column */ if(column1 == column2) { return false; } /* check diagonals: if the distance between the columns equals the distance * between the rows, then they're in the same diagonal */ int columnDistance = Math.abs(column2 - column1); /* row1 > row2, so no need for abs */ int rowDistance = row1 - row2; if(columnDistance == rowDistance) { return false; } } return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/MagicIndex.java ================================================ /* a magic index is an array A[1...n - 1] is defined to be an index such that A[i] = i. Given a sorted * array of distinct integers, write a method to find a magic index, if one exists, in array A */ public class MagicIndex { public static int magicFast(int[] array, int start, int end) { if(end < start || start < 0 || end >= array.length) { return -1; } int mid = (start + end) / 2; if(array[mid] == mid) { return mid; } else if(array[mid] > mid) { return magicFast(array, start, mid - 1); } else { return magicFast(array, mid + 1, end); } } public static int magicFast(int[] array) { return magicFast(array, 0, array.length - 1); } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/RepresentingNCents.java ================================================ /* given an infinite number of quars (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), * write code to calculate the number of ways of representing n cents */ public class RepresentingNCents { int makeChange(int n) { int[] denoms = {25, 10, 5, 1}; int[][] map = new int[n + 1][denoms.length]; //precomputed vals return makeChange(n, denoms, 0, map); } int makeChange(int amount, int[] denoms, int index, int[][] map) { if(map[amount][index] > 0) { //retrieve value return map[amount][index]; } if(index >= denoms.length - 1) return 1; //one denom remaining int denomAmount = denoms[index]; int ways = 0; for(int i = 0; i * denomAmount <= amount; i++) { //go to next denom, assuming i coints of denomAmount int amountRemaining = amount - i * denomAmount; ways += makeChange(amountRemaining, denoms, index + 1, map); } map[amount][index] = ways; return ways; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/StackBoxes.java ================================================ /* you have a stack of n boxes, with widths wi, heights hi, and depths di. The boxes cannot be rotated * and can only be stacked on top of one another if each box in the stack is strictly larger than the * the box above it in width, height, and depth. Implement a method to build the tallest stack possible, * where the height of a stack is the sum of the heights of each box */ public class StackBoxes { public ArrayList createStackDP(Box[] boxes, Box bottom, HashMap> stack_map) { if(bottom != null && stack_map.containsKey(bottom)) { return (ArrayList) stack_map.get(bottom).clone(); } int max_height = 0; ArrayList max_stack = null; for(int i = 0; i < boxes.length; i++) { if(boxes[i].canBeAbove(bottom)) { ArrayList new_stack = createStackDP(boxes, boxes[i], stack_map); int new_height = stackHeight(new_stack); if(new_height > max_height) { max_stack = new_stack; max_height = new_height; } } } if(max_stack == null) { max_stack = new ArrayList(); } if(bottom != null) { max_stack.add(0, bottom); } stack_map.put(bottom, max_stack); return max_stack; } } ================================================ FILE: cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/Staircase.java ================================================ /* a child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps * at a time. Implement a method to count how many possible ways the child can run up the stairs */ public class Staircase { public static int countWaysDP(int n, int[] map) { if(n < 0) { return 0; } else if(n == 0) { return 1; } else if(map[n] > -1) { return map[n]; } else { map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map); return map[n]; } } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java ================================================ //Write code to remove duplicates from an unsorted linked list public class RemoveDups { void deleteDups(LinkedListNode n) { HashSet set = new HashSet(); LinkedListNode previous = null; while(n != null) { if(set.contains(n.data)) { previous.next = n.next; } else { set.add(n.data); previous = n; } n = n.next; } } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/IsRotation.java ================================================ // Assume you have a method isSubstring which checks if one word is a isSubstring of another. // Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only // one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat"). public class IsRotation { public boolean isRotation(String s1, String s2) { int len = s1.length(); /*check that s1 and s2 are equal length and not empty */ if(len == s2.length() && len > 0) { /* concatenate s1 and s1 within new buffer */ String s1s1 = s1 + s1; return isSubstring(s1s1, s2); } return false; } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/IsUniqueChars.java ================================================ //Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? public class IsUniqueChars { public boolean isUniqueChars(String str) { int checker = 0; for(int i = 0; i < str.length(); i++) { int val = str.charAt(i) - 'a'; if((checker & (1 << val)) > 0) { return false; } checker |= (1 << val); } return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/NthToLast.java ================================================ //Implement an algorithm to find the kth to last element of a single linked list public class NthToLast { LinkedListNode nthToLast(LinkedListNode head, int k) { if(k <= 0) return null; LinkedListNode p1 = head; LinkedListNode p2 = head; //move p2 forward k nodes into the list for(int i = 0; i < k - 1; i++) { if(p2 == null) return null; //error check p2 = p2.next; } if(p2 == null) return null; /* now, move p1 and p2 at the same speed. When p2 hits the end, * p1 will be at the right element */ while(p2.next != null) { p1 = p1.next; p2 = p2.next; } return p1; } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/Permutation.java ================================================ // Given two strings, write a method to decide if one is a permutation of the other public class Permutation { public boolean permutation(String s, String t) { if(s.length() != t.length()) { return false; } int[] letters = new int[256]; char[] s_array = s.toCharArray(); for(char c : s_array) { letters[c]++; } for(int i = 0; i < t.length(); i++) { int c = (int)t.charAt(i); if(--letters[c] < 0) { return false; } } return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java ================================================ // Write a method to replace all spaces in a string with '%20.' You may assume that the string // has sufficient space at the end of the string to hold the additional characters, and that you // are given the "true" length of the string. (Note: if implementing in Java, please use a characters // array so that you can perform this operation in place) public class ReplaceSpaces { public void replaceSpaces(char[] str, int length) { int spaceCount = 0, newLength; for(int i = 0; i < length; i++) { if(str[i] == ' ') { spaceCount++; } } newLength = length + spaceCount * 2; str[newLength] = '\0'; for(int i = length - 1; i >= 0; i--) { if(str[i] == ' ') { str[newLength - 1] = '0'; str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength = newLength - 1; } } } } ================================================ FILE: cracking-the-coding-interview/chapter-seven-mathematics-and-probability/Operations.java ================================================ /* write methods to implement the multiply, subtract, and divide operations for integers. Use only the add operator */ public class Operations { /* flip a positive sign to negative or negative sign to positive */ public static int negate(int a) { int neg = 0; int d = a < 0 ? 1 : -1; while(a != 0) { neg += d; a += d; } return neg; } /* subtract two numbers by negating b and adding them */ public static int minus(int a, int b) { return a + negate(b); } /* multiply a by b by adding a to itself b times */ public static int multiply(int a, int b) { if(a < b) { return multiply(b, a); //algorithm is faster is b < a } int sum = 0; for(int i = abs(b); i > 0; i--) { sum += a; } if(b < 0) { sum = negate(sum); } return sum; } /* return absolute value */ public static int abs(int a) { if(a < 0) { return negate(a); } else { return a; } } public int divide(int a, int b) throws ArithmeticException { if(b == 0) { throw new java.lang.ArithmeticException("ERROR"); } int absa = abs(a); int absb = abs(b); int product = 0; int x = 0; while(product + absb <= absa) { //don't go past a product += absb; x++; } if((a < 0 && b < 0) || (a > 0 && b > 0)) { return x; } else { return negate(x); } } } ================================================ FILE: cracking-the-coding-interview/chapter-seven-mathematics-and-probability/WouldIntersect.java ================================================ /* give two lines on a Cartesian plane, determine whether the two lines would intersect */ public class WouldIntersect { //placeholder for class name } class Line { static double epsilon = 0.000001; public double slope; public double yintercept; public Line(double s, double y) { this.slope = s; this.yintercept = y; } public boolean Intersect(Line line2) { return Math.abs(this.slope - line2.slope) > epsilon || Math.abs(this.yintercept - line2.yintercept) < epsilon; } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/BinaryTreeIsBalanced.java ================================================ /* implement a function to check if a binary tree is balanced. For the purpose of this * question, a balanced tree is defined to be a tree such that the heights of the two * subtrees of any node never differ by more than one */ public class BinaryTreeIsBalanaced { public static int getHeight(TreeNode root) { if(root == null) { return 0; //base case } return Math.max(getHeight(root.left), getHeight(root.right)) + 1; } public static boolean isBalanced(TreeNode root) { if(root == null) { //base case return true; } int heightDiff = getHeight(root.left) - getHeight(root.right); if(Math.abs(heightDiff) > 1) { return false; } else { //recurse return isBalanced(root.left) && isBalanced(root.right); } } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQUeue.java ================================================ /* implement a MyQueue class which implements a queue using two stacks */ public class MyQueue { Stack stackNewest, stackOldest; public MyQueue() { stackNewest = new Stack(); stackOldest = new Stack(); } public int size() { return stackNewest.size() + stackOldest.size(); } public void add(T value) { /* push onto stackNewest, which always has the newest * elements on top */ stackNewest.push(value); } /* Move elements from stackNewest into stackOldest. This * is usually done so that we can do operations on stackOldest */ private void shiftStacks() { if(stackOldest.isEmpty()) { while(!stackNewest.isEmpty()) { stackOldest.push(stackNewest.pop()); } } } public T peek() { shiftStacks(); //ensure stackOldest has the current elements return stackOldest.peek(); //retrieve the oldest item } public T remove() { shiftStacks(); //ensure stackOldest has the current elements return stackOldest.pop(); } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQueue.java ================================================ /* implement a MyQueue class which implements a queue using two stacks */ public class MyQueue { Stack stackNewest, stackOldest; public MyQueue() { stackNewest = new Stack(); stackOldest = new Stack(); } public int size() { return stackNewest.size() + stackOldest.size(); } public void add(T value) { /* push onto stackNewest, which always has the newest * elements on top */ stackNewest.push(value); } /* Move elements from stackNewest into stackOldest. This * is usually done so that we can do operations on stackOldest */ private void shiftStacks() { if(stackOldest.isEmpty()) { while(!stackNewest.isEmpty()) { stackOldest.push(stackNewest.pop()); } } } public T peek() { shiftStacks(); //ensure stackOldest has the current elements return stackOldest.peek(); //retrieve the oldest item } public T remove() { shiftStacks(); //ensure stackOldest has the current elements return stackOldest.pop(); } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java ================================================ /* implement a MyQueue class which implements a queue using two stacks */ public class QueueUsingTwoStacks { } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/SetOfStacks.java ================================================ /* imagine a (literal) stack of plates. If the stack gets too high, it might topple. * Therefore, in real life, we would likely start a new stack when the previous stack * exceeds some threshold. Implement a data structure SetOfStacks that mimics this. * SetOfStacks should be composed of several stacks and should create a new stack once * the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should * behave identically to a single stack (that is, pop() should return the same values as * it would if there were just a single stack) */ //in this problem, we've been told what our data structure should look like: public class SetOfStacks { ArrayList stacks = new ArrayList(); //public void push(int v) {...} //public int pop() {...} public void push(int v) { Stack last = getLastStack(); if(last != null && !last.isFull()) { //add to the last stack last.push(v); } else { //must create new stack Stack stack = new Stack(capacity); stack.push(v); stacks.add(stack); } } public void pop() { Stack last = getLastStack(); int v = last.pop(); if(last.size == 0) { stacks.remove(stacks.size() - 1); } return v; } public Stack getLastStack() { if(stacks.size() == 0) { return null; } return stacks.get(stacks.size() - 1); } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/SortStack.java ================================================ /* write a program to sort a stack in ascending order (with biggest items on top). * you may use at most one additional stack to hold items, but you may not copy the * elements into any other data strcuture (such as an array). The stack supports the * folowing operations: push, pop, peek, and isEmpty */ public class SortStack { public static Stack sort(Stack s) { Stack r = new Stack(); while(!s.isEmpty()) { int tmp = s.pop(); //step 1 while(!r.isEmpty() && r.peek() > tmp) { //step 2 s.push(r.pop()); } r.push(tmp); //step 3 } return r; } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/StackWithMin.java ================================================ //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 public class StackWithMin extends Stack { public void push(int value) { int newMin = Math.min(value, min()); super.push(new NodeWithMin(value, newMin)); } public int min() { if(this.isEmpty()) { return Integer.MAX_VALUE; //error value } else { return peek().min; } } } class NodeWithMin { public int value; public int min; public NodeWithMin(int v, int min) { this.value = v; this.min = min; } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/ThreeStacks.java ================================================ //Describe how you could use a single array to implement three stacks public class ThreeStacks { int stackSize = 100; int[] buffer = new int[stackSize * 3]; int[] stackPointer = {-1, -1, -1}; //pointers to track top element void push(int stackNum, int value) throws Exception { /* check if we have space */ if(stackPointer[stackNum] + 1 >= stackSize) { //last element throw new FullStackException(); } /* increment stack pointer and then update top value */ stackPointer[stackNum]++; buffer[absTopOfStack(stackNum)] = value; } int pop(int stackNum) throws Exception { if(isEmpty(stackNum)) { throw new EmptyStackException(); } int value = buffer[absTopOfStack(stackNum)]; //get top buffer[absTopOfStack(stackNum)] = 0; //clear index stackPointer[stackNum]--; //decrement pointer return value; } int peek(int stackNum) { if(isEmpty(stackNum)) { throw new EmptyStackException(); } int index = absTopOfStack(stackNum); return buffer[index]; } boolean isEmpty(int stackNum) { return stackPointer[stackNum] == -1; } /* returns index of top of stack "stackNum", in absolute terms */ int absTopOfStack(int stasckNum) { return stackNum * stackSize + stackPointer[stackNum]; } } ================================================ FILE: cracking-the-coding-interview/chapter-three-stacks-and-queues/TowersOfHanoi.java ================================================ /* in the classic problem of the Towers of Hanoi, you have 3 towers and N disks of * different sizes which can slide onto any tower. The puzzle starts with disks sorted * in ascending order of size from top to bottom (i.e. each disk sits on top of an even * larger one). You have the following constraints: * (1) Only one disk can be moved at a time * (2) A disk is slid off the top of one tower onto the next rod * (3) A disk can only be placed on top of a larger disk * Write a program to move the disks from the first tower to the last tower using Stacks */ public class TowersOfHanoi { public static void main(String args[]) { int n = 3; Tower[] towers = new Tower[n]; for(int i = 0; i < 3; i++) { towers[i] = new Tower(i); } for(int i = n - 1; i >= 0; i--) { towers[0].add(i); } towers[0].moveDisks(n, towers[2], towers[1]); } } public class Tower { private Stack disks; private int index; public Tower(int i) { disks = new Stack(); index = i; } public int index() { return index; } public void add(int d) { if(!disks.isEmpty() && disks.peek() <= d) { System.out.println("Error placing disk " + d); } else { disks.push(d); } } public void moveTopTo(Tower t) { int top = disks.pop(); t.add(top); System.out.println("Move disk " + top + " from " + index() + " to " + t.index()); } public void moveDisks(int n, Tower destination, Tower buffer) { if(n > 0) { moveDisks(n - 1, buffer, destination); moveTopTo(destination); buffer.moveDisks(n - 1, destination, this); } } } ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/DeleteDups.java ================================================ //Write code to remove duplicates from an unsorted linked list public class RemoveDups { void deleteDups(LinkedListNode n) { HashSet set = new HashSet(); LinkedListNode previous = null; while(n != null) { if(set.contains(n.data)) { previous.next = n.next; } else { set.add(n.data); previous = n; } n = n.next; } } } ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/DeleteNode.java ================================================ //Implement an algorithm to delete a node in the middle of a singly linked list, give only access to that node public class DeleteNode { public static boolean deleteNode(LinkedListNode n) { if(n == null || n.next == null) { return false; } LinkedListNode next = n.next; n.data = next.data; n.next = next.next; return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/FindBeginning.java ================================================ //Given a circular linked list, implement an algorithm which returns //the node at the beginning of the loop public class FindBeginning { LinkedListNode findBeginning(LinkedListNode head) { LinkedListNode slow = head; LinkedListNode fast = head; /* find meeting point. This will be LOOP_SIZE - k * steps int othe linked list */ while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if(fast == slow) { break; } } /* error checking - no meeting point, and therefore no loop */ if(fast == null || fast.next == null) { return null; } /* move slow to head. Keep fast at meeting point. Each are k * steps from the loop start. If they move at the same pace, * they must meet at the loop start */ slow = head; while(slow != fast) { slow = slow.next; fast = fast.next; } /* both now point to the start of the loop */ return fast; } } ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/IsPalindrome.java ================================================ //Implement a function to check if a linked list is a palindrome //don't forget import statements! public class IsPalindrome { boolean isPalindrome(LinkedListNode head) { LinkedListNode fast = head; LinkedListNode slow = head; Stack stack = new Stack(); /* push elements from first half of linked list onto stack. * When fast runner (which is moving at 2x speed) reaches the * end of the linked list, then we know we're at the middle */ while(fast != null && fast.next != null) { stack.push(slow.data); slow = slow.next; fast = fast.next.next; } /*has odd number of elements, so skip the middle element */ if(fast != null) { slow = slow.next; } while(slow != null) { int top = stack.pop().intValue(); /* if values are different, then it's not a palindrome */ if(top != slow.data) { return false; } slow = slow.next; } return true; } } ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java ================================================ ================================================ FILE: cracking-the-coding-interview/chapter-two-linked-lists/Partition.java ================================================ //Write code to partition a linked list around a value x, such that //all nodes less than x come before all nodes greater than or equal to x. public class Partition { LinkedListNode partition(LinkedListNode node, int x) { LinkedListNode head = node; LinkedListNode tail = node; while(node != null) { LinkedListNode next = node.next; if(node.data < x) { /* insert node at head */ node.next = head; head = node; } else { /* insert node at tail */ tail.next = node; tail = node; } node = next; } tail.next = null; //the head has changed, so we need to return it to the user return head; } } ================================================ FILE: interviews.iml ================================================ ================================================ FILE: leetcode/LeetCode.iml ================================================ ================================================ FILE: leetcode/array/BestTimeToBuyAndSellStock.java ================================================ // Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Example 1: // Input: [7, 1, 5, 3, 6, 4] // Output: 5 // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) // Example 2: // Input: [7, 6, 4, 3, 1] // Output: 0 // In this case, no transaction is done, i.e. max profit = 0. public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { //Kadane's algorithm if(prices.length == 0) { return 0; } int min = prices[0]; int max = 0; for(int i = 1; i < prices.length; i++) { if(prices[i] > min) { max = Math.max(max, prices[i] - min); } else { min = prices[i]; } } return max; } } ================================================ FILE: leetcode/array/ContainsDuplicatesII.java ================================================ //Given an array of integers and an integer k, find out whether there are two distinct indices i and //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class ContainsDuplicatesII { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap(); for(int i = 0; i < nums.length; i++) { int current = nums[i]; if(map.containsKey(current) && i - map.get(current) <= k) { return true; } else { map.put(current, i); } } return false; } } ================================================ FILE: leetcode/array/FindAllNumbersDisappearedInAnArray.java ================================================ //Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. // //Find all the elements of [1, n] inclusive that do not appear in this array. // //Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. // //Example: // //Input: //[4,3,2,7,8,2,3,1] // //Output: //[5,6] class FindAllNumbersDisappearedInAnArray { public List findDisappearedNumbers(int[] nums) { List result = new ArrayList(); HashMap map = new HashMap(); for(int i = 1; i <= nums.length; i++) { map.put(i, 1); } for(int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])) { map.put(nums[i], -1); } } for(int i: map.keySet()) { if(map.get(i) != -1) { result.add(i); } } return result; } } ================================================ FILE: leetcode/array/FindTheCelebrity.java ================================================ // Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } } ================================================ FILE: leetcode/array/GameOfLife.java ================================================ // According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." // Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies, as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population.. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // Write a function to compute the next state (after one update) of the board given its current state. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? public class GameOfLife { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3; } if(board[i][j] == 0 && lives == 3) { board[i][j] = 2; } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; } } } private int liveNeighbors(int[][] board, int m, int n, int i, int j) { int lives = 0; for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) { for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) { lives += board[x][y] & 1; } } lives -= board[i][j] & 1; return lives; } } ================================================ FILE: leetcode/array/IncreasingTripletSubsequence.java ================================================ // Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. // Formally the function should: // Return true if there exists i, j, k // such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. // Your algorithm should run in O(n) time complexity and O(1) space complexity. // Examples: // Given [1, 2, 3, 4, 5], // return true. // Given [5, 4, 3, 2, 1], // return false. public class IncreasingTripletSequence { public boolean increasingTriplet(int[] nums) { int firstMin = Integer.MAX_VALUE; int secondMin = Integer.MAX_VALUE; for(int n : nums) { if(n <= firstMin) { firstMin = n; } else if(n < secondMin) { secondMin = n; } else if(n > secondMin) { return true; } } return false; } } ================================================ FILE: leetcode/array/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: leetcode/array/InsertInterval.java ================================================ // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). // You may assume that the intervals were initially sorted according to their start times. // Example 1: // Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. // Example 2: // Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. // This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class InsertInterval { public List insert(List intervals, Interval newInterval) { int i = 0; while(i < intervals.size() && intervals.get(i).end < newInterval.start) { i++; } while(i < intervals.size() && intervals.get(i).start <= newInterval.end) { newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end)); intervals.remove(i); } intervals.add(i, newInterval); return intervals; } } ================================================ FILE: leetcode/array/LongestConsecutiveSequence.java ================================================ // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. // For example, // Given [100, 4, 200, 1, 3, 2], // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. // Your algorithm should run in O(n) complexity. class LongestConsecutiveSequence { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0) { return 0; } Set set = new HashSet(); for(int n: nums) { set.add(n); } int maxLength = 0; for(int n: set) { if(!set.contains(n - 1)) { int current = n; int currentMax = 1; while(set.contains(n + 1)) { currentMax++; n++; } maxLength = Math.max(maxLength, currentMax); } } return maxLength; } } ================================================ FILE: leetcode/array/MajorityElement.java ================================================ //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. //You may assume that the array is non-empty and the majority element always exist in the array. class MajorityElement { public int majorityElement(int[] nums) { if(nums.length == 1) { return nums[0]; } HashMap map = new HashMap(); for(int current: nums) { if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) { return current; } else if(map.containsKey(current)) { map.put(current, map.get(current) + 1); } else { map.put(current, 1); } } //no majority element exists return -1; } } ================================================ FILE: leetcode/array/MaximumProductSubarray.java ================================================ // Find the contiguous subarray within an array (containing at least one number) which has the largest product. // For example, given the array [2,3,-2,4], // the contiguous subarray [2,3] has the largest product = 6. public class MaximumProductSubarray { public int maxProduct(int[] nums) { if(nums == null || nums.length == 0) { return 0; } int result = nums[0]; int max = nums[0]; int min = nums[0]; for(int i = 1; i < nums.length; i++) { int temp = max; max = Math.max(Math.max(nums[i] * max, nums[i] * min), nums[i]); min = Math.min(Math.min(nums[i] * temp, nums[i] * min), nums[i]); if(max > result) { result = max; } } return result; } } ================================================ FILE: leetcode/array/MaximumSubarray.java ================================================ // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], // the contiguous subarray [4,-1,2,1] has the largest sum = 6. public class Solution { public int maxSubArray(int[] nums) { int[] dp = new int[nums.length]; dp[0] = nums[0]; int max = dp[0]; for(int i = 1; i < nums.length; i++) { dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); max = Math.max(dp[i], max); } return max; } } ================================================ FILE: leetcode/array/MergeIntervals.java ================================================ // Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class MergeIntervals { public List merge(List intervals) { List result = new ArrayList(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } } ================================================ FILE: leetcode/array/MinCostClimbingStairs.java ================================================ //On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). // //Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. // //Example 1: //Input: cost = [10, 15, 20] //Output: 15 //Explanation: Cheapest is start on cost[1], pay that cost and go to the top. //Example 2: //Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] //Output: 6 //Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. //Note: //cost will have a length in the range [2, 1000]. //Every cost[i] will be an integer in the range [0, 999]. class MinCostClimbingStairs { public int minCostClimbingStairs(int[] cost) { if(cost == null || cost.length == 0) { return 0; } if(cost.length == 1) { return cost[0]; } if(cost.length == 2) { return Math.min(cost[0], cost[1]); } int[] dp = new int[cost.length]; dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < cost.length; i++) { dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]); } return Math.min(dp[cost.length - 1], dp[cost.length -2]); } } ================================================ FILE: leetcode/array/MinimumPathSum.java ================================================ //Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right //which minimizes the sum of all numbers along its path. //Note: You can only move either down or right at any point in time. //Example 1: //[[1,3,1], //[1,5,1], //[4,2,1]] //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. class MinimumPathSum { public int minPathSum(int[][] grid) { for(int i = 1; i < grid.length; i++) { grid[i][0] += grid[i - 1][0]; } for(int i = 1; i < grid[0].length; i++) { grid[0][i] += grid[0][i - 1]; } for(int i = 1; i < grid.length; i++) { for(int j = 1; j < grid[0].length; j++) { grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); } } return grid[grid.length - 1][grid[0].length - 1]; } } ================================================ FILE: leetcode/array/MissingRanges.java ================================================ // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. // For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. public class MissingRanges { public List findMissingRanges(int[] nums, int lower, int upper) { ArrayList result = new ArrayList(); for(int i = 0; i <= nums.length; i++) { long start = i == 0 ? lower : (long)nums[i - 1] + 1; long end = i == nums.length ? upper : (long)nums[i] - 1; addMissing(result, start, end); } return result; } void addMissing(ArrayList result, long start, long end) { if(start > end) { return; } else if(start == end) { result.add(start + ""); } else { result.add(start + "->" + end); } } } ================================================ FILE: leetcode/array/PlusOne.java ================================================ //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. // //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. // //You may assume the integer does not contain any leading zero, except the number 0 itself. // //Example 1: // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. //Example 2: // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ================================================ FILE: leetcode/array/ProductofArrayExceptSelf.java ================================================ // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. // Solve it without division and in O(n). // For example, given [1,2,3,4], return [24,12,8,6]. // Follow up: // Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) public class ProductOfArrayExceptSelf { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n]; int left = 1; for(int i = 0; i < nums.length; i++) { if(i > 0) { left *= nums[i - 1]; } result[i] = left; } int right = 1; for(int i = n - 1; i >= 0; i--) { if(i < n - 1) { right *= nums[i + 1]; } result[i] *= right; } return result; } } ================================================ FILE: leetcode/array/RemoveElement.java ================================================ //Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums = [3,2,2,3], val = 3, //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } } ================================================ FILE: leetcode/array/RotateImage.java ================================================ // You are given an n x n 2D matrix representing an image. // Rotate the image by 90 degrees (clockwise). // Follow up: // Could you do this in-place? public class RotateImage { public void rotate(int[][] matrix) { for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < i; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length / 2; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[i][matrix[0].length - 1 - j]; matrix[i][matrix[0].length - 1 - j] = temp; } } } } ================================================ FILE: leetcode/array/SearchInRotatedSortedArray.java ================================================ // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } } ================================================ FILE: leetcode/array/SpiralMatrix.java ================================================ //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // //Example 1: // //Input: //[ //[ 1, 2, 3 ], //[ 4, 5, 6 ], //[ 7, 8, 9 ] //] //Output: [1,2,3,6,9,8,7,4,5] //Example 2: // //Input: //[ //[1, 2, 3, 4], //[5, 6, 7, 8], //[9,10,11,12] //] //Output: [1,2,3,4,8,12,11,10,9,5,6,7] class SpiralMatrix { public List spiralOrder(int[][] matrix) { List result = new ArrayList(); if(matrix == null || matrix.length == 0) { return result; } int rowStart = 0; int rowEnd = matrix.length - 1; int colStart = 0; int colEnd = matrix[0].length - 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { result.add(matrix[rowStart][i]); } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { result.add(matrix[i][colEnd]); } colEnd--; if(rowStart <= rowEnd) { for(int i = colEnd; i >= colStart; i--) { result.add(matrix[rowEnd][i]); } } rowEnd--; if(colStart <= colEnd) { for(int i = rowEnd; i >= rowStart; i--) { result.add(matrix[i][colStart]); } } colStart++; } return result; } } ================================================ FILE: leetcode/array/SpiralMatrixII.java ================================================ // Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. // For example, // Given n = 3, // You should return the following matrix: // [ // [ 1, 2, 3 ], // [ 8, 9, 4 ], // [ 7, 6, 5 ] // ] public class SpiralMatrix { public int[][] generateMatrix(int n) { int[][] spiral = new int[n][n]; if(n == 0) { return spiral; } int rowStart = 0; int colStart = 0; int rowEnd = n - 1; int colEnd = n -1; int number = 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { spiral[rowStart][i] = number++; } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { spiral[i][colEnd] = number++; } colEnd--; for(int i = colEnd; i >= colStart; i--) { if(rowStart <= rowEnd) { spiral[rowEnd][i] = number++; } } rowEnd--; for(int i = rowEnd; i >= rowStart; i--) { if(colStart <= colEnd) { spiral[i][colStart] = number++; } } colStart++; } return spiral; } } ================================================ FILE: leetcode/array/Subsets.java ================================================ // Given a set of distinct integers, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] public class Subsets { public List> subsets(int[] nums) { List> result = new ArrayList<>(); recurse(result, nums, new Stack<>(), 0); return result; } private void recurse(List> result, int[] nums, Stack path, int position) { if(position == nums.length) { result.add(new ArrayList<>(path)); return; } path.push(nums[position]); recurse(result, nums, path, position + 1); path.pop(); recurse(result, nums, path, position + 1); } } ================================================ FILE: leetcode/array/SubsetsII.java ================================================ // Given a collection of integers that might contain duplicates, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,2], a solution is: // [ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] // ] public class SubsetsII { public List> subsetsWithDup(int[] nums) { Arrays.sort(nums); List> result = new ArrayList>(); if(nums.length == 0 || nums == null) { return result; } helper(nums, new ArrayList(), 0, result); return result; } public void helper(int[] nums, ArrayList current, int index, List> result) { result.add(current); for(int i = index; i < nums.length; i++) { if(i > index && nums[i] == nums[i - 1]) { continue; } ArrayList newCurrent = new ArrayList(current); newCurrent.add(nums[i]); helper(nums, newCurrent, i + 1, result); } } } ================================================ FILE: leetcode/array/SummaryRanges.java ================================================ // Given a sorted integer array without duplicates, return the summary of its ranges. // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. public class SummaryRanges { public List summaryRanges(int[] nums) { List result = new ArrayList(); if(nums.length == 1) { result.add(nums[0] + ""); return result; } for(int i = 0; i < nums.length; i++) { int current = nums[i]; while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) { i++; } if(current != nums[i]) { result.add(current + "->" + nums[i]); } else { result.add(current + ""); } } return result; } } ================================================ FILE: leetcode/array/UniquePaths.java ================================================ //A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } } ================================================ FILE: leetcode/array/WiggleSort.java ================================================ // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. public class WiggleSort { public void wiggleSort(int[] nums) { for(int i = 1; i < nums.length; i++) { int current = nums[i - 1]; if((i % 2 == 1) == (current > nums[i])) { nums[i - 1] = nums[i]; nums[i] = current; } } } } ================================================ FILE: leetcode/array/WordSearch.java ================================================ // Given a 2D board and a word, find if the word exists in the grid. // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. // For example, // Given board = // [ // ['A','B','C','E'], // ['S','F','C','S'], // ['A','D','E','E'] // ] // word = "ABCCED", -> returns true, // word = "SEE", -> returns true, // word = "ABCB", -> returns false. public class WordSearch { public boolean exist(char[][] board, String word) { char[] w = word.toCharArray(); for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(search(board, i, j, w, 0)) { return true; } } } return false; } public boolean search(char[][] board, int i, int j, char[] w, int index) { if(index == w.length) { return true; } if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) { return false; } if(board[i][j] != w[index]) { return false; } board[i][j] ^= 256; boolean exist = search(board, i + 1, j, w, index + 1) || search(board, i - 1, j, w, index + 1) || search(board, i, j + 1, w, index + 1) || search(board, i, j - 1, w, index + 1); board[i][j] ^= 256; return exist; } } ================================================ FILE: leetcode/backtracking/AndroidUnlockPatterns.java ================================================ // Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys. // Rules for a valid pattern: // Each pattern must connect at least m keys and at most n keys. // All the keys must be distinct. // If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed. // The order of keys used matters. // Explanation: // | 1 | 2 | 3 | // | 4 | 5 | 6 | // | 7 | 8 | 9 | // Invalid move: 4 - 1 - 3 - 6 // Line 1 - 3 passes through key 2 which had not been selected in the pattern. // Invalid move: 4 - 1 - 9 - 2 // Line 1 - 9 passes through key 5 which had not been selected in the pattern. // Valid move: 2 - 4 - 1 - 3 - 6 // Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern // Valid move: 6 - 5 - 4 - 1 - 9 - 2 // Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern. // Example: // Given m = 1, n = 1, return 9. public class AndroidUnlockPatterns { public int numberOfPatterns(int m, int n) { //initialize a 10x10 matrix int skip[][] = new int[10][10]; //initialize indices of skip matrix (all other indices in matrix are 0 by default) skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip [7][3] = skip[6][4] = skip[4][6] = 5; //initialize visited array boolean visited[] = new boolean[10]; //initialize total number to 0 int totalNumber = 0; //run DFS for each length from m to n for(int i = m; i <= n; ++i) { totalNumber += DFS(visited, skip, 1, i - 1) * 4; //1, 3, 7, and 9 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 2, i - 1) * 4; //2, 4, 6, and 8 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 5, i - 1); //do not multiply by 4 because 5 is unique } return totalNumber; } int DFS(boolean visited[], int[][] skip, int current, int remaining) { //base cases if(remaining < 0) { return 0; } if(remaining == 0) { return 1; } //mark the current node as visited visited[current] = true; //initialize total number to 0 int totalNumber = 0; for(int i = 1; i <= 9; ++i) { //if the current node has not been visited and (two numbers are adjacent or skip number has already been visited) if(!visited[i] && (skip[current][i] == 0 || visited[skip[current][i]])) { totalNumber += DFS(visited, skip, i, remaining - 1); } } //mark the current node as not visited visited[current] = false; //return total number return totalNumber; } } ================================================ FILE: leetcode/backtracking/GeneralizedAbbreviation.java ================================================ // Write a function to generate the generalized abbreviations of a word. // Example: // Given word = "word", return the following list (order does not matter): // ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] public class GeneralizedAbbreviation { public List generateAbbreviations(String word) { List result = new ArrayList(); backtrack(result, word, 0, "", 0); return result; } void backtrack(List result, String word, int position, String current, int count) { if(position == word.length()) { if(count > 0) { current += count; } result.add(current); } else { backtrack(result, word, position + 1, current, count + 1); backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0); } } } ================================================ FILE: leetcode/backtracking/GenerateParentheses.java ================================================ //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. // //For example, given n = 3, a solution set is: // //[ //"((()))", //"(()())", //"(())()", //"()(())", //"()()()" //] class GenerateParentheses { public List generateParenthesis(int n) { List result = new ArrayList(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } } ================================================ FILE: leetcode/backtracking/LetterCombinationsOfAPhoneNumber.java ================================================ // Given a digit string, return all possible letter combinations that the number could represent. // A mapping of digit to letters (just like on the telephone buttons) is given below. // 2 - abc // 3 - def // 4 - ghi // 5 - jkl // 6 - mno // 7 - pqrs // 8 - tuv // 9 - wxyz // Input:Digit string "23" // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class LetterCombinationsOfAPhoneNumber { public List letterCombinations(String digits) { List result = new ArrayList(); if(digits == null || digits.length() == 0) { return result; } String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; letterCombinationsRecursive(result, digits, "", 0, mapping); return result; } public void letterCombinationsRecursive(List result, String digits, String current, int index, String[] mapping) { if(index == digits.length()) { result.add(current); return; } String letters = mapping[digits.charAt(index) - '0']; for(int i = 0; i < letters.length(); i++) { letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); } } } ================================================ FILE: leetcode/backtracking/Permutations.java ================================================ //Given a collection of distinct numbers, return all possible permutations. // //For example, //[1,2,3] have the following permutations: //[ //[1,2,3], //[1,3,2], //[2,1,3], //[2,3,1], //[3,1,2], //[3,2,1] //] class Permutations { public List> permute(int[] nums) { LinkedList> result = new LinkedList>(); result.add(new ArrayList()); for (int n: nums) { int size = result.size(); while(size > 0) { List current = result.pollFirst(); for (int i = 0; i <= current.size(); i++) { List temp = new ArrayList(current); temp.add(i, n); result.add(temp); } size--; } } return result; } } ================================================ FILE: leetcode/binary-search/ClosestBinarySearchTreeValue.java ================================================ // Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. // Note: // Given target value is a floating point. // You are guaranteed to have only one unique value in the BST that is closest to the target. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ClosestBinarySearchTreeValue { public int closestValue(TreeNode root, double target) { int value = root.val; TreeNode child = root.val < target ? root.right : root.left; if(child == null) { return value; } int childValue = closestValue(child, target); return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue; } } ================================================ FILE: leetcode/binary-search/FirstBadVersion.java ================================================ // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. // You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class FirstBadVersion extends VersionControl { public int firstBadVersion(int n) { int start = 1; int end = n; while(start < end) { int mid = start + (end - start) / 2; if(!isBadVersion(mid)) { start = mid + 1; } else { end = mid; } } return start; } } ================================================ FILE: leetcode/binary-search/GuessNumberHigherOrLower.java ================================================ // We are playing the Guess Game. The game is as follows: // I pick a number from 1 to n. You have to guess which number I picked. // Every time you guess wrong, I'll tell you whether the number is higher or lower. // You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): // -1 : My number is lower // 1 : My number is higher // 0 : Congrats! You got it! // Example: // n = 10, I pick 6. // Return 6. public class GuessNumberHigherOrLower extends GuessGame { public int guessNumber(int n) { int left = 1; int right = n; while(left <= right) { int mid = left + (right - left) / 2; if(guess(mid) == 0) { return mid; } else if(guess(mid) > 0) { left = mid + 1; } else { right = mid; } } return -1; } } ================================================ FILE: leetcode/binary-search/PowerOfXToTheN.java ================================================ // Implement pow(x, n). public class PowerOfXToTheN { public double myPow(double x, int n) { if(n == 0) { return 1; } if(Double.isInfinite(x)) { return 0; } if(n < 0) { n = -n; x = 1 / x; } return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); } } ================================================ FILE: leetcode/binary-search/SquareRootX.java ================================================ // Implement int sqrt(int x). // Compute and return the square root of x. public class Solution { public int mySqrt(int x) { if(x == 0) { return 0; } int left = 1; int right = x; while(left <= right) { int mid = left + (right - left) / 2; if(mid == x / mid) { return mid; } else if(mid > x / mid) { right = mid - 1; } else if(mid < x / mid) { left = mid + 1; } } return right; } } ================================================ FILE: leetcode/bit-manipulation/BinaryWatch.java ================================================ // A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). // Each LED represents a zero or one, with the least significant bit on the right. // For example, the above binary watch reads "3:25". // Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. // Example: // Input: n = 1 // Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] // Note: // The order of output does not matter. // The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". // The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". public class BinaryWatch { public List readBinaryWatch(int num) { ArrayList allTimes = new ArrayList(); //iterate through all possible time combinations for(int i = 0; i < 12; i++) { for(int j = 0; j < 60; j++) { //if the current number and n have the same number of bits the time is possible if(Integer.bitCount(i * 64 + j) == num) { //add the current time to all times arraylist allTimes.add(String.format("%d:%02d", i, j)); } } } return allTimes; } } ================================================ FILE: leetcode/bit-manipulation/CountingBits.java ================================================ // 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. // Example: // For num = 5 you should return [0,1,1,2,1,2]. public class CountingBits { public int[] countBits(int num) { int[] bits = new int[num + 1]; bits[0] = 0; for(int i = 1; i <= num; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } } ================================================ FILE: leetcode/bit-manipulation/HammingDistance.java ================================================ // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. // Given two integers x and y, calculate the Hamming distance. // Note: // 0 ≤ x, y < 2^31. // Example: // Input: x = 1, y = 4 // Output: 2 // Explanation: // 1 (0 0 0 1) // 4 (0 1 0 0) // ↑ ↑ // The above arrows point to positions where the corresponding bits are different. public class HammingDistance { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } } ================================================ FILE: leetcode/bit-manipulation/MaximumProductOfWordLengths.java ================================================ // Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. // Example 1: // Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] // Return 16 // The two words can be "abcw", "xtfn". // Example 2: // Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] // Return 4 // The two words can be "ab", "cd". // Example 3: // Given ["a", "aa", "aaa", "aaaa"] // Return 0 // No such pair of words. public class MaximumProductOfWordLengths { public int maxProduct(String[] words) { if(words.length == 0 || words == null) { return 0; } int length = words.length; int[] value = new int[length]; int max = 0; for(int i = 0; i < length; i++) { String temp = words[i]; value[i] = 0; for(int j = 0; j < temp.length(); j++) { value[i] |= 1 << (temp.charAt(j) - 'a'); } } for(int i = 0; i < length; i++) { for(int j = 1; j < length; j++) { if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length()) > max) { max = words[i].length() * words[j].length(); } } } return max; } } ================================================ FILE: leetcode/bit-manipulation/NumberOfOneBits.java ================================================ // Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). // For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. public class NumberOfOneBits { // you need to treat n as an unsigned value public int hammingWeight(int n) { if(n == 0) { return 0; } int count = 0; while(n != 0) { count += (n) & 1; n >>>= 1; } return count; } } ================================================ FILE: leetcode/bit-manipulation/PowerOfTwo.java ================================================ //Given an integer, write a function to determine if it is a power of two. // //Example 1: // //Input: 1 //Output: true //Example 2: // //Input: 16 //Output: true //Example 3: // //Input: 218 //Output: false class PowerOfTwo { public boolean isPowerOfTwo(int n) { long i = 1; while(i < n) { i <<= 1; } return i == n; } } ================================================ FILE: leetcode/bit-manipulation/SumOfTwoInteger.java ================================================ // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. // Example: // Given a = 1 and b = 2, return 3. public class SumOfTwoIntegers { public int getSum(int a, int b) { if(a == 0) { return b; } if(b == 0) { return a; } while(b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } } ================================================ FILE: leetcode/bit-manipulation/Utf8Validation.java ================================================ // A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: // For 1-byte character, the first bit is a 0, followed by its unicode code. // For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. // This is how the UTF-8 encoding would work: // Char. number range | UTF-8 octet sequence // (hexadecimal) | (binary) // --------------------+--------------------------------------------- // 0000 0000-0000 007F | 0xxxxxxx // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // Given an array of integers representing the data, return whether it is a valid utf-8 encoding. // Note: // The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. // Example 1: // data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. // Return true. // It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. // Example 2: // data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. // Return false. // The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. // The next byte is a continuation byte which starts with 10 and that's correct. // But the second continuation byte does not start with 10, so it is invalid. public class Utf8Validation { public boolean validUtf8(int[] data) { int count = 0; for(int i : data) { if(count == 0) { if((i >> 5) == 0b110) { count = 1; } else if((i >> 4) == 0b1110) { count = 2; } else if((i >> 3) == 0b11110) { count = 3; } else if((i >> 7) == 0b1) { return false; } } else { if((i >> 6) != 0b10) { return false; } count--; } } return count == 0; } } ================================================ FILE: leetcode/brainteaser/BulbSwitcher.java ================================================ //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. //Example: //Given n = 3. //At first, the three bulbs are [off, off, off]. //After first round, the three bulbs are [on, on, on]. //After second round, the three bulbs are [on, off, on]. //After third round, the three bulbs are [on, off, off]. //So you should return 1, because there is only one bulb is on. class BulbSwitcher { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } } ================================================ FILE: leetcode/breadth-first-search/BinaryTreeLevelOrderTraversal.java ================================================ // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // For example: // Given binary tree [3,9,20,null,null,15,7], // 3 // / \ // 9 20 // / \ // 15 7 // return its level order traversal as: // [ // [3], // [9,20], // [15,7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinarySearchTreeLevelOrderTraversal { public List> levelOrder(TreeNode root) { List> result = new ArrayList>(); if(root == null) { return result; } Queue queue = new LinkedList(); queue.add(root); List tempList = new ArrayList(); tempList.add(root.val); result.add(tempList); while(!queue.isEmpty()) { Queue currentLevel = new LinkedList(); List list = new ArrayList(); while(!queue.isEmpty()) { TreeNode current = queue.remove(); if(current.left != null) { currentLevel.add(current.left); list.add(current.left.val); } if(current.right != null) { currentLevel.add(current.right); list.add(current.right.val); } } if(list.size() > 0) { result.add(list); } queue = currentLevel; } return result; } } ================================================ FILE: leetcode/breadth-first-search/CloneGraph.java ================================================ // Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } * }; */ public class CloneGraph { public HashMap map = new HashMap(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } } ================================================ FILE: leetcode/breadth-first-search/PacificAtlanticWaterFlow.java ================================================ // Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. // Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower. // Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. // Note: // The order of returned grid coordinates does not matter. // Both m and n are less than 150. // Example: // Given the following 5x5 matrix: // Pacific ~ ~ ~ ~ ~ // ~ 1 2 2 3 (5) * // ~ 3 2 3 (4) (4) * // ~ 2 4 (5) 3 1 * // ~ (6) (7) 1 4 5 * // ~ (5) 1 1 2 4 * // * * * * * Atlantic // Return: // [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). public class PacificAtlanticWaterFlow { public List pacificAtlantic(int[][] matrix) { List result = new LinkedList<>(); //error checking if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { return result; } int n = matrix.length; int m = matrix[0].length; boolean[][] pacific = new boolean[n][m]; boolean[][] atlantic = new boolean[n][m]; for(int i = 0; i < n; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, i, 0); dfs(matrix, atlantic, Integer.MIN_VALUE, i, m - 1); } for(int i = 0; i < m; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, 0, i); dfs(matrix, atlantic, Integer.MIN_VALUE, n - 1, i); } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(pacific[i][j] && atlantic[i][j]) { result.add(new int[] {i, j}); } } } return result; } public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) { int n = matrix.length; int m = matrix[0].length; if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < height) { return; } visited[x][y] = true; dfs(matrix, visited, matrix[x][y], x + 1, y); dfs(matrix, visited, matrix[x][y], x - 1, y); dfs(matrix, visited, matrix[x][y], x, y + 1); dfs(matrix, visited, matrix[x][y], x, y - 1); } } ================================================ FILE: leetcode/breadth-first-search/RemoveInvalidParentheses.java ================================================ // Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. // Note: The input string may contain letters other than the parentheses ( and ). // Examples: // "()())()" -> ["()()()", "(())()"] // "(a)())()" -> ["(a)()()", "(a())()"] // ")(" -> [""] public class RemoveInvalidParentheses { public List removeInvalidParentheses(String s) { List result = new ArrayList<>(); remove(s, result, 0, 0, new char[]{'(', ')'}); return result; } public void remove(String s, List result, int last_i, int last_j, char[] par) { for (int stack = 0, i = last_i; i < s.length(); i++) { if (s.charAt(i) == par[0]) { stack++; } if (s.charAt(i) == par[1]) { stack--; } if (stack >= 0) { continue; } for (int j = last_j; j <= i; j++) { if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) { remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par); } } return; } String reversed = new StringBuilder(s).reverse().toString(); if (par[0] == '(') { // finished left to right remove(reversed, result, 0, 0, new char[]{')', '('}); } else { // finished right to left result.add(reversed); } } } ================================================ FILE: leetcode/breadth-first-search/ShortestDistanceFromAllBuildings.java ================================================ // You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: // Each 0 marks an empty land which you can pass by freely. // Each 1 marks a building which you cannot pass through. // Each 2 marks an obstacle which you cannot pass through. // For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2): // 1 - 0 - 2 - 0 - 1 // | | | | | // 0 - 0 - 0 - 0 - 0 // | | | | | // 0 - 0 - 1 - 0 - 0 // The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. // Note: // There will be at least one building. If it is not possible to build such house according to the above rules, return -1. public class Shortest { public int shortestDistance(int[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return -1; } final int[] shift = {0, 1, 0, -1, 0}; int rows = grid.length; int columns = grid[0].length; int[][] distance = new int[rows][columns]; int[][] reach = new int[rows][columns]; int numberOfBuildings = 0; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 1) { numberOfBuildings++; Queue queue = new LinkedList(); queue.offer(new int[] {i, j}); boolean[][] visited = new boolean[rows][columns]; int relativeDistance = 1; while(!queue.isEmpty()) { int qSize = queue.size(); for(int q = 0; q < qSize; q++) { int[] current = queue.poll(); for(int k = 0; k < 4; k++) { int nextRow = current[0] + shift[k]; int nextColumn = current[1] + shift[k + 1]; if(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && grid[nextRow][nextColumn] == 0 && !visited[nextRow][nextColumn]) { distance[nextRow][nextColumn] += relativeDistance; reach[nextRow][nextColumn]++; visited[nextRow][nextColumn] = true; queue.offer(new int[] {nextRow, nextColumn}); } } } relativeDistance++; } } } } int shortest = Integer.MAX_VALUE; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 0 && reach[i][j] == numberOfBuildings) { shortest = Math.min(shortest, distance[i][j]); } } } return shortest == Integer.MAX_VALUE ? -1 : shortest; } } ================================================ FILE: leetcode/breadth-first-search/SymmetricTree.java ================================================ // Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). // For example, this binary tree [1,2,2,3,4,4,3] is symmetric: // 1 // / \ // 2 2 // / \ / \ // 3 4 4 3 // But the following [1,2,2,null,3,null,3] is not: // 1 // / \ // 2 2 // \ \ // 3 3 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SymmetricTree { public boolean isSymmetric(TreeNode root) { if(root == null) { return true; } return helper(root.left, root.right); } public boolean helper(TreeNode left, TreeNode right) { if(left == null && right == null) { return true; } if(left == null || right == null || left.val != right.val) { return false; } return helper(left.right, right.left) && helper(left.left, right.right); } } ================================================ FILE: leetcode/breadth-first-search/WallsAndGates.java ================================================ // You are given a m x n 2D grid initialized with these three possible values. // -1 - A wall or an obstacle. // 0 - A gate. // INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. // Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. // For example, given the 2D grid: // INF -1 0 INF // INF INF INF -1 // INF -1 INF -1 // 0 -1 INF INF // After running your function, the 2D grid should be: // 3 -1 0 1 // 2 2 1 -1 // 1 -1 2 -1 // 0 -1 3 4 public class Solution { public void wallsAndGates(int[][] rooms) { //iterate through the matrix calling dfs on all indices that contain a zero for(int i = 0; i < rooms.length; i++) { for(int j = 0; j < rooms[0].length; j++) { if(rooms[i][j] == 0) { dfs(rooms, i, j, 0); } } } } void dfs(int[][] rooms, int i, int j, int distance) { //if you have gone out of the bounds of the array or you have run into a wall/obstacle, return // room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) { return; } //set current index's distance to distance rooms[i][j] = distance; //recurse on all adjacent neighbors of rooms[i][j] dfs(rooms, i + 1, j, distance + 1); dfs(rooms, i - 1, j, distance + 1); dfs(rooms, i, j + 1, distance + 1); dfs(rooms, i, j - 1, distance + 1); } } ================================================ FILE: leetcode/depth-first-search/BalancedBinaryTree.java ================================================ // Given a binary tree, determine if it is height-balanced. // 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. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BalancedBinaryTree { boolean balanced = true; public boolean isBalanced(TreeNode root) { height(root); return balanced; } private int height(TreeNode root) { if(root == null) { return 0; } int leftHeight = height(root.left); int rightHeight = height(root.right); if(Math.abs(leftHeight - rightHeight) > 1) { balanced = false; } return 1 + Math.max(leftHeight, rightHeight); } } ================================================ FILE: leetcode/depth-first-search/BattleshipsInABoard.java ================================================ // Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: // You receive a valid board, made of only battleships or empty slots. // Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. // At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. // Example: // X..X // ...X // ...X // In the above board there are 2 battleships. // Invalid Example: // ...X // XXXX // ...X // This is an invalid board that you will not receive - as battleships will always have a cell separating between them. // Follow up: // Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board? public class BattleshipsInABoard { public int countBattleships(char[][] board) { int ships = 0; for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(board[i][j] == 'X') { ships++; sink(board, i, j, 1); } } } return ships; } public void sink(char[][] board, int i, int j, int numberOfShips) { if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] == '.') { return; } board[i][j] = '.'; sink(board, i + 1, j, numberOfShips + 1); sink(board, i, j + 1, numberOfShips + 1); } } ================================================ FILE: leetcode/depth-first-search/ConvertSortedArrayToBinarySearchTree.java ================================================ // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ConvertSortedArrayToBinarySearchTree { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = helper(nums, 0, nums.length - 1); return root; } private TreeNode helper(int[] nums, int start, int end) { if(start <= end) { int mid = (start + end) / 2; TreeNode current = new TreeNode(nums[mid]); current.left = helper(nums, start, mid - 1); current.right = helper(nums, mid + 1, end); return current; } return null; } } ================================================ FILE: leetcode/depth-first-search/MaximumDepthOfABinaryTree.java ================================================ // Given a binary tree, find its maximum depth. // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class MaximumDepthOfABinaryTree { public int maxDepth(TreeNode root) { if(root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } } ================================================ FILE: leetcode/depth-first-search/NumberOfIslands.java ================================================ // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. // Example 1: // 11110 // 11010 // 11000 // 00000 // Answer: 1 // Example 2: // 11000 // 11000 // 00100 // 00011 // Answer: 3 public class NumberOfIslands { char[][] gridCopy; public int numIslands(char[][] grid) { //set grid copy to the current grid gridCopy = grid; //initialize number of islands to zero int numberOfIslands = 0; //iterate through every index of the grid for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { //attempt to "sink" the current index of the grid numberOfIslands += sink(gridCopy, i, j); } } //return the total number of islands return numberOfIslands; } int sink(char[][] grid, int i, int j) { //check the bounds of i and j and if the current index is an island or not (1 or 0) if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { return 0; } //set current index to 0 grid[i][j] = '0'; // sink all neighbors of current index sink(grid, i + 1, j); sink(grid, i - 1, j); sink(grid, i, j + 1); sink(grid, i, j - 1); //increment number of islands return 1; } } ================================================ FILE: leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java ================================================ // Given a binary tree // struct TreeLinkNode { // TreeLinkNode *left; // TreeLinkNode *right; // TreeLinkNode *next; // } // Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. // Initially, all next pointers are set to NULL. // Note: // You may only use constant extra space. // You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). // For example, // Given the following perfect binary tree, // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 // After calling your function, the tree should look like: // 1 -> NULL // / \ // 2 -> 3 -> NULL // / \ / \ // 4->5->6->7 -> NULL /** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class PopulatingNextRightPointersInEachNode { public void connect(TreeLinkNode root) { if(root == null) { return; } Queue queue = new LinkedList(); queue.add(root); while(!queue.isEmpty()) { Queue currentLevel = new LinkedList(); TreeLinkNode temp = null; while(!queue.isEmpty()) { TreeLinkNode current = queue.remove(); current.next = temp; temp = current; if(current.right != null) { currentLevel.add(current.right); } if(current.left!= null) { currentLevel.add(current.left); } } queue = currentLevel; } } } ================================================ FILE: leetcode/depth-first-search/SameTree.java ================================================ // Given two binary trees, write a function to check if they are equal or not. // Two binary trees are considered equal if they are structurally identical and the nodes have the same value. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SameTree { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) { return true; } if(p == null && q != null || q == null && p != null) { return false; } if(p.val != q.val) { return false; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } } ================================================ FILE: leetcode/design/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: leetcode/design/MinStack.java ================================================ //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: leetcode/design/ZigZagIterator.java ================================================ // Given two 1d vectors, implement an iterator to return their elements alternately. // For example, given two 1d vectors: // v1 = [1, 2] // v2 = [3, 4, 5, 6] // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. // Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i = new ZigzagIterator(v1, v2); * while (i.hasNext()) v[f()] = i.next(); */ public class ZigZagIterator { private Iterator i; private Iterator j; private Iterator temp; public ZigzagIterator(List v1, List v2) { i = v1.iterator(); j = v2.iterator(); } public int next() { if(i.hasNext()) { temp = i; i = j; j = temp; } return j.next(); } public boolean hasNext() { return i.hasNext() || j.hasNext(); } } ================================================ FILE: leetcode/divide-and-conquer/ExpressionAddOperators.java ================================================ // Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. // Examples: // "123", 6 -> ["1+2+3", "1*2*3"] // "232", 8 -> ["2*3+2", "2+3*2"] // "105", 5 -> ["1*0+5","10-5"] // "00", 0 -> ["0+0", "0-0", "0*0"] // "3456237490", 9191 -> [] public class ExpressionAddOperators { public List addOperators(String num, int target) { List result = new ArrayList(); if(num == null || num.length() == 0) { return result; } helper(result, "", num, target, 0, 0, 0); return result; } public void helper(List result, String path, String num, int target, int pos, long eval, long multed) { if(pos == num.length()) { if(eval == target) { result.add(path); } return; } for(int i = pos; i < num.length(); i++) { if(i != pos && num.charAt(pos) == '0') { break; } long cur = Long.parseLong(num.substring(pos, i + 1)); if(pos == 0) { helper(result, path + cur, num, target, i + 1, cur, cur); } else { helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur); helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur); helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur); } } } } ================================================ FILE: leetcode/divide-and-conquer/KthLargestElementInAnArray.java ================================================ // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. // For example, // Given [3,2,1,5,6,4] and k = 2, return 5. // Note: // You may assume k is always valid, 1 ≤ k ≤ array's length. public class KthLargestElementInAnArray { public int findKthLargest(int[] nums, int k) { int length = nums.length; Arrays.sort(nums); return nums[length - k]; } } ================================================ FILE: leetcode/dynamic-programming/BombEnemy.java ================================================ // Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb. // The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. // Note that you can only put the bomb at an empty cell. // Example: // For the given grid // 0 E 0 0 // E 0 W E // 0 E 0 0 // return 3. (Placing a bomb at (1,1) kills 3 enemies) public class BombEnemy { public int maxKilledEnemies(char[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int max = 0; int row = 0; int[] col = new int[grid[0].length]; for(int i = 0; i max) ? row + col[j] : max; } } } return max; } //calculate killed enemies for row i from column j private int killedEnemiesRow(char[][] grid, int i, int j) { int num = 0; while(j <= grid[0].length-1 && grid[i][j] != 'W') { if(grid[i][j] == 'E') { num++; } j++; } return num; } //calculate killed enemies for column j from row i private int killedEnemiesCol(char[][] grid, int i, int j) { int num = 0; while(i <= grid.length -1 && grid[i][j] != 'W'){ if(grid[i][j] == 'E') { num++; } i++; } return num; } } ================================================ FILE: leetcode/dynamic-programming/ClimbingStairs.java ================================================ // You are climbing a stair case. It takes n steps to reach to the top. // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? // Note: Given n will be a positive integer. public class ClimbingStairs { public int climbStairs(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i < dp.length; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[dp.length - 1]; } } ================================================ FILE: leetcode/dynamic-programming/CoinChange.java ================================================ //You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. //Example 1: //coins = [1, 2, 5], amount = 11 //return 3 (11 = 5 + 5 + 1) //Example 2: //coins = [2], amount = 3 //return -1. //Note: //You may assume that you have an infinite number of each kind of coin. class CoinChange { public int coinChange(int[] coins, int amount) { if(amount < 1) { return 0; } return coinChangeRecursive(coins, amount, new int[amount]); } public int coinChangeRecursive(int[] coins, int amount, int[] dp) { if(amount < 0) { return -1; } if(amount == 0) { return 0; } if(dp[amount - 1] != 0) { return dp[amount - 1]; } int min = Integer.MAX_VALUE; for(int coin: coins) { int result = coinChangeRecursive(coins, amount - coin, dp); if(result >= 0 && result < min) { min = 1 + result; } } dp[amount - 1] = min == Integer.MAX_VALUE ? -1 : min; return dp[amount - 1]; } } ================================================ FILE: leetcode/dynamic-programming/CombinationSumIV.java ================================================ // Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. // Example: // nums = [1, 2, 3] // target = 4 // The possible combination ways are: // (1, 1, 1, 1) // (1, 1, 2) // (1, 2, 1) // (1, 3) // (2, 1, 1) // (2, 2) // (3, 1) // Note that different sequences are counted as different combinations. // Therefore the output is 7. // Follow up: // What if negative numbers are allowed in the given array? // How does it change the problem? // What limitation we need to add to the question to allow negative numbers? public class CombinationSumIV { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < nums.length; j++) { if(i - nums[j] >= 0) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } } ================================================ FILE: leetcode/dynamic-programming/CountingBits.java ================================================ // 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. // Example: // For num = 5 you should return [0,1,1,2,1,2]. // Follow up: // 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? // Space complexity should be O(n). // Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. public class CountingBits { public int[] countBits(int num) { int[] bits = new int[num + 1]; bits[0] = 0; for(int i = 1; i <= num; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } } ================================================ FILE: leetcode/dynamic-programming/EditDistance.java ================================================ // Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) // You have the following 3 operations permitted on a word: // a) Insert a character // b) Delete a character // c) Replace a character public class EditDistance { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for(int i = 0; i <= m; i++) { dp[i][0] = i; } for(int i = 0; i <= n; i++) { dp[0][i] = i; } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(word1.charAt(i) == word2.charAt(j)) { dp[i + 1][j + 1] = dp[i][j]; } else { int a = dp[i][j]; int b = dp[i][j + 1]; int c = dp[i + 1][j]; dp[i + 1][j + 1] = Math.min(a, Math.min(b, c)); dp[i + 1][j + 1]++; } } } return dp[m][n]; } } ================================================ FILE: leetcode/dynamic-programming/HouseRobber.java ================================================ // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. public class Solution { public int rob(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; for(int i = 2; i < nums.length; i++) { dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); } return dp[dp.length - 1]; } } ================================================ FILE: leetcode/dynamic-programming/HouseRobberII.java ================================================ //Note: This is an extension of House Robber. (security system is tripped if two ajacent houses are robbed) //After robbing those houses on that street, the thief has found himself a new place for his thievery so that //he will not get too much attention. This time, all houses at this place are arranged in a circle. That means //the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the //same as for those in the previous street. //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. class HouseRobberII { public int rob(int[] nums) { if (nums.length == 0) { return 0; } if (nums.length < 2) { return nums[0]; } int[] first = new int[nums.length + 1]; int[] second = new int[nums.length + 1]; first[0] = 0; first[1] = nums[0]; second[0] = 0; second[1] = 0; for (int i = 2; i <= nums.length; i++) { first[i] = Math.max(first[i - 1], first[i - 2] + nums[i - 1]); second[i] = Math.max(second[i - 1], second[i - 2] + nums[i - 1]); } return Math.max(first[nums.length - 1], second[nums.length]); } } ================================================ FILE: leetcode/dynamic-programming/LongestIncreasingSubsequence.java ================================================ //Given an unsorted array of integers, find the length of longest increasing subsequence. //For example, //Given [10, 9, 2, 5, 3, 7, 101, 18], //The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. //Your algorithm should run in O(n2) complexity. //Follow up: Could you improve it to O(n log n) time complexity? class LongestIncreasingSubsequence { public int lengthOfLIS(int[] nums) { if(nums == null || nums.length < 1) { return 0; } int[] dp = new int[nums.length]; dp[0] = 1; int max = 1; for(int i = 1; i < dp.length; i++) { int currentMax = 0; for(int j = 0; j < i; j++) { if(nums[i] > nums[j]) { currentMax = Math.max(currentMax, dp[j]); } } dp[i] = 1 + currentMax; max = Math.max(max, dp[i]); } return max; } } ================================================ FILE: leetcode/dynamic-programming/MinCostClimbingStairs.java ================================================ //On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). // //Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. // //Example 1: //Input: cost = [10, 15, 20] //Output: 15 //Explanation: Cheapest is start on cost[1], pay that cost and go to the top. //Example 2: //Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] //Output: 6 //Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. //Note: //cost will have a length in the range [2, 1000]. //Every cost[i] will be an integer in the range [0, 999]. class MinCostClimbingStairs { public int minCostClimbingStairs(int[] cost) { if(cost == null || cost.length == 0) { return 0; } if(cost.length == 1) { return cost[0]; } if(cost.length == 2) { return Math.min(cost[0], cost[1]); } int[] dp = new int[cost.length]; dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < cost.length; i++) { dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]); } return Math.min(dp[cost.length - 1], dp[cost.length -2]); } } ================================================ FILE: leetcode/dynamic-programming/MinimumPathSum.java ================================================ //Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right //which minimizes the sum of all numbers along its path. //Note: You can only move either down or right at any point in time. //Example 1: //[[1,3,1], //[1,5,1], //[4,2,1]] //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. class MinimumPathSum { public int minPathSum(int[][] grid) { for(int i = 1; i < grid.length; i++) { grid[i][0] += grid[i - 1][0]; } for(int i = 1; i < grid[0].length; i++) { grid[0][i] += grid[0][i - 1]; } for(int i = 1; i < grid.length; i++) { for(int j = 1; j < grid[0].length; j++) { grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); } } return grid[grid.length - 1][grid[0].length - 1]; } } ================================================ FILE: leetcode/dynamic-programming/PaintFence.java ================================================ // There is a fence with n posts, each post can be painted with one of the k colors. // You have to paint all the posts such that no more than two adjacent fence posts have the same color. // Return the total number of ways you can paint the fence. // Note: // n and k are non-negative integers. public class PaintFence { public int numWays(int n, int k) { if(n <= 0) { return 0; } int sameColorCounts = 0; int differentColorCounts = k; for(int i = 2; i <= n; i++) { int temp = differentColorCounts; differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); sameColorCounts = temp; } return sameColorCounts + differentColorCounts; } } ================================================ FILE: leetcode/dynamic-programming/PaintHouse.java ================================================ //There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. //The cost of painting each house with a certain color is different. You have to paint all the houses such //that no two adjacent houses have the same color. //The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, //costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 //with color green, and so on... Find the minimum cost to paint all houses. //Note: //All costs are positive integers. class PaintHouse { public int minCost(int[][] costs) { if(costs == null || costs.length == 0) { return 0; } for(int i = 1; i < costs.length; i++) { costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]); costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]); } return Math.min(Math.min(costs[costs.length - 1][0], costs[costs.length - 1][1]), costs[costs.length - 1][2]); } } ================================================ FILE: leetcode/dynamic-programming/PaintHouseII.java ================================================ // There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. // Note: // All costs are positive integers. // Follow up: // Could you solve it in O(nk) runtime? public class PaintHouseII { public int minCostII(int[][] costs) { if(costs == null|| costs.length == 0) { return 0; } int m = costs.length; int n = costs[0].length; int min1 = -1; int min2 = -1; for(int i = 0; i < m; i++) { int last1 = min1; int last2 = min2; min1 = -1; min2 = -1; for(int j = 0; j < n; j++) { if(j != last1) { costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } if(min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if(min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[m - 1][min1]; } } ================================================ FILE: leetcode/dynamic-programming/PalindromicSubstrings.java ================================================ //Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } } ================================================ FILE: leetcode/dynamic-programming/RegularExpressionMatching.java ================================================ // Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } } ================================================ FILE: leetcode/dynamic-programming/SentenceScreenFitting.java ================================================ // Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. // Note: // A word cannot be split into two lines. // The order of words in the sentence must remain unchanged. // Two consecutive words in a line must be separated by a single space. // Total words in the sentence won't exceed 100. // Length of each word is greater than 0 and won't exceed 10. // 1 ≤ rows, cols ≤ 20,000. // Example 1: // Input: // rows = 2, cols = 8, sentence = ["hello", "world"] // Output: // 1 // Explanation: // hello--- // world--- // The character '-' signifies an empty space on the screen. // Example 2: // Input: // rows = 3, cols = 6, sentence = ["a", "bcd", "e"] // Output: // 2 // Explanation: // a-bcd- // e-a--- // bcd-e- // The character '-' signifies an empty space on the screen. // Example 3: // Input: // rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] // Output: // 1 // Explanation: // I-had // apple // pie-I // had-- // The character '-' signifies an empty space on the screen. public class SentenceScreenFitting { public int wordsTyping(String[] sentence, int rows, int cols) { String s = String.join(" ", sentence) + " "; int start = 0; int l = s.length(); for(int i = 0; i < rows; i++) { start += cols; if(s.charAt(start % l) == ' ') { start++; } else { while(start > 0 && s.charAt((start - 1) % l) != ' ') { start--; } } } return start / s.length(); } } ================================================ FILE: leetcode/dynamic-programming/UniqueBinarySearchTrees.java ================================================ // Given n, how many structurally unique BST's (binary search trees) that store values 1...n? // For example, // Given n = 3, there are a total of 5 unique BST's. // 1 3 3 2 1 // \ / / / \ \ // 3 2 1 1 3 2 // / / \ \ // 2 1 2 3 public class UniqueBinarySearchTree { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i <= n; i++) { for(int j = 1; j <= i; j++) { dp[i] += dp[i - j] * dp[j - 1]; } } return dp[n]; } } ================================================ FILE: leetcode/dynamic-programming/UniquePaths.java ================================================ //A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } } ================================================ FILE: leetcode/dynamic-programming/WordBreak.java ================================================ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } } ================================================ FILE: leetcode/greedy/BestTimeToBuyAndSellStockII.java ================================================ //Say you have an array for which the ith element is the price of a given stock on day i. //Design an algorithm to find the maximum profit. You may complete as many transactions as you //like (ie, buy one and sell one share of the stock multiple times). However, you may not engage //in multiple transactions at the same time (ie, you must sell the stock before you buy again). class BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) { return 0; } int profit = 0; for(int i = 0; i < prices.length - 1; i++) { if(prices[i] < prices[i + 1]) { profit += prices[i + 1] - prices[i]; } } return profit; } } ================================================ FILE: leetcode/hash-table/BinaryTreeVerticalOrderTraversal.java ================================================ // Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). // If two nodes are in the same row and column, the order should be from left to right. // Examples: // Given binary tree [3,9,20,null,null,15,7], // 3 // /\ // / \ // 9 20 // /\ // / \ // 15 7 // return its vertical order traversal as: // [ // [9], // [3,15], // [20], // [7] // ] // Given binary tree [3,9,8,4,0,1,7], // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // return its vertical order traversal as: // [ // [4], // [9], // [3,0,1], // [8], // [7] // ] // Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // /\ // / \ // 5 2 // return its vertical order traversal as: // [ // [4], // [9,5], // [3,0,1], // [8,2], // [7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeVerticalOrderTraversal { public List> verticalOrder(TreeNode root) { List> result = new ArrayList<>(); if(root == null) { return result; } Map> map = new HashMap<>(); Queue q = new LinkedList<>(); Queue cols = new LinkedList<>(); q.add(root); cols.add(0); int min = 0; int max = 0; while(!q.isEmpty()) { TreeNode node = q.poll(); int col = cols.poll(); if(!map.containsKey(col)) { map.put(col, new ArrayList()); } map.get(col).add(node.val); if(node.left != null) { q.add(node.left); cols.add(col - 1); min = Math.min(min, col - 1); } if(node.right != null) { q.add(node.right); cols.add(col + 1); max = Math.max(max, col + 1); } } for(int i = min; i <= max; i++) { result.add(map.get(i)); } return result; } } ================================================ FILE: leetcode/hash-table/BullsAndCows.java ================================================ //You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. // //Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. // //Please note that both secret number and friend's guess may contain duplicate digits. // //Example 1: // //Input: secret = "1807", guess = "7810" // //Output: "1A3B" // //Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. //Example 2: // //Input: secret = "1123", guess = "0111" // //Output: "1A1B" // //Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. //Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. class BullsAndCows { public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] counts = new int[10]; for(int i = 0; i < secret.length(); i++) { if(secret.charAt(i) == guess.charAt(i)) { bulls++; } else { if(counts[secret.charAt(i) - '0']++ < 0) { cows++; } if(counts[guess.charAt(i) - '0']-- > 0) { cows++; } } } return bulls + "A" + cows + "B"; } } ================================================ FILE: leetcode/hash-table/ContainsDuplicate.java ================================================ //Given an array of integers, find if the array contains any duplicates. Your function should return //true if any value appears at least twice in the array, and it should return false if every element is distinct. class ContainsDuplicate { public boolean containsDuplicate(int[] nums) { HashMap map = new HashMap(); for(int i: nums) { if(map.containsKey(i)) { return true; } else { map.put(i, 1); } } return false; } } ================================================ FILE: leetcode/hash-table/ContainsDuplicatesII.java ================================================ //Given an array of integers and an integer k, find out whether there are two distinct indices i and //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class ContainsDuplicatesII { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap(); for(int i = 0; i < nums.length; i++) { int current = nums[i]; if(map.containsKey(current) && i - map.get(current) <= k) { return true; } else { map.put(current, i); } } return false; } } ================================================ FILE: leetcode/hash-table/DailyTemperatures.java ================================================ //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack stack = new Stack(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } } ================================================ FILE: leetcode/hash-table/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: leetcode/hash-table/FindAnagramMappings.java ================================================ //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. //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. //These lists A and B may contain duplicates. If there are multiple answers, output any of them. //For example, given //A = [12, 28, 46, 32, 50] //B = [50, 12, 32, 46, 28] //We should return //[1, 4, 3, 2, 0] //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. class FindAnagramMappings { public int[] anagramMappings(int[] A, int[] B) { int[] mapping = new int[A.length]; HashMap map = new HashMap(); for(int i = 0; i < B.length; i++) { map.put(B[i], i); } for(int i = 0; i < A.length; i++) { mapping[i] = map.get(A[i]); } return mapping; } } ================================================ FILE: leetcode/hash-table/FindTheDifference.java ================================================ // Given two strings s and t which consist of only lowercase letters. // String t is generated by random shuffling string s and then add one more letter at a random position. // Find the letter that was added in t. // Example: // Input: // s = "abcd" // t = "abcde" // Output: // e // Explanation: // 'e' is the letter that was added. public class FindTheDifference { public char findTheDifference(String s, String t) { int charCodeS = 0; int charCodeT = 0; for(int i = 0; i < s.length(); i++) { charCodeS += (int)(s.charAt(i)); } for(int i = 0; i < t.length(); i++) { charCodeT += (int)(t.charAt(i)); } return (char)(charCodeT - charCodeS); } } ================================================ FILE: leetcode/hash-table/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: leetcode/hash-table/GroupAnagrams.java ================================================ // Given an array of strings, group anagrams together. // For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], // Return: // [ // ["ate", "eat","tea"], // ["nat","tan"], // ["bat"] // ] // Note: All inputs will be in lower-case. public class GroupAnagrams { public List> groupAnagrams(String[] strs) { if(strs == null || strs.length == 0) { return new ArrayList>(); } HashMap> map = new HashMap>(); Arrays.sort(strs); for(String s : strs) { char[] characters = s.toCharArray(); Arrays.sort(characters); String key = String.valueOf(characters); if(!map.containsKey(key)) { map.put(key, new ArrayList()); } map.get(key).add(s); } return new ArrayList>(map.values()); } } ================================================ FILE: leetcode/hash-table/GroupShiftedStrings.java ================================================ // Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List> groupStrings(String[] strings) { List> result = new ArrayList>(); HashMap> map = new HashMap>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List list = new ArrayList(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List list = map.get(key); Collections.sort(list); result.add(list); } return result; } } ================================================ FILE: leetcode/hash-table/InsertDeleteGetRandomO1.java ================================================ //Design a data structure that supports all following operations in average O(1) time. //insert(val): Inserts an item val to the set if not already present. //remove(val): Removes an item val from the set if present. //getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. //Example: // Init an empty set. //RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. //randomSet.insert(1); // Returns false as 2 does not exist in the set. //randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. //randomSet.insert(2); // getRandom should return either 1 or 2 randomly. //randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. //randomSet.remove(1); // 2 was already in the set, so return false. //randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. //randomSet.getRandom(); class RandomizedSet { HashMap map; ArrayList values; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap(); values = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(!map.containsKey(val)) { map.put(val, val); values.add(val); return true; } else { return false; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if(map.containsKey(val)) { map.remove(val); values.remove(values.indexOf(val)); return true; } return false; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * values.size()); int valueToReturn = values.get(random); return map.get(valueToReturn); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: leetcode/hash-table/IslandPerimeter.java ================================================ // You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. // Example: // [[0,1,0,0], // [1,1,1,0], // [0,1,0,0], // [1,1,0,0]] // Answer: 16 class IslandPerimeter { public int islandPerimeter(int[][] grid) { int perimeter = 0; if(grid == null || grid.length == 0) { return perimeter; } for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[i].length; j++) { if(grid[i][j] == 1) { perimeter += numNeighbors(grid, i, j); return perimeter; } } } return perimeter; } public int numNeighbors(int[][] grid, int x, int y) { if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] == 0) { return 1; } if(grid[x][y] == -1) { return 0; } grid[x][y] = -1; return numNeighbors(grid, x + 1, y) + numNeighbors(grid, x - 1, y) + numNeighbors(grid, x, y + 1) + numNeighbors(grid, x, y - 1); } } ================================================ FILE: leetcode/hash-table/JewelsAndStones.java ================================================ //You're given strings J representing the types of stones that are jewels, and S representing the stones you have. //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. //The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, //so "a" is considered a different type of stone from "A". class JewelsAndStones { public int numJewelsInStones(String J, String S) { HashMap map = new HashMap(); for(char c: J.toCharArray()) { map.put(c, 1); } int numberOfJewels = 0; for(char c: S.toCharArray()) { if(map.containsKey(c)) { numberOfJewels++; } } return numberOfJewels; } } ================================================ FILE: leetcode/hash-table/LoggerRateLimiter.java ================================================ // Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. // Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false. // It is possible that several messages arrive roughly at the same time. // Example: // Logger logger = new Logger(); // // logging string "foo" at timestamp 1 // logger.shouldPrintMessage(1, "foo"); returns true; // // logging string "bar" at timestamp 2 // logger.shouldPrintMessage(2,"bar"); returns true; // // logging string "foo" at timestamp 3 // logger.shouldPrintMessage(3,"foo"); returns false; // // logging string "bar" at timestamp 8 // logger.shouldPrintMessage(8,"bar"); returns false; // // logging string "foo" at timestamp 10 // logger.shouldPrintMessage(10,"foo"); returns false; // // logging string "foo" at timestamp 11 // logger.shouldPrintMessage(11,"foo"); returns true; public class LoggerRateLimiter { HashMap messages; /** Initialize your data structure here. */ public Logger() { this.messages = new HashMap(); } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */ public boolean shouldPrintMessage(int timestamp, String message) { if(messages.containsKey(message)) { if(timestamp - messages.get(message) >= 10) { messages.put(message, timestamp); return true; } else { return false; } } else { messages.put(message, timestamp); return true; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */ ================================================ FILE: leetcode/hash-table/MaximumSizeSubarraySumEqualsK.java ================================================ // Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. // Note: // The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. // Example 1: // Given nums = [1, -1, 5, -2, 3], k = 3, // return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest) // Example 2: // Given nums = [-2, -1, 2, 1], k = 1, // return 2. (because the subarray [-1, 2] sums to 1 and is the longest) // Follow Up: // Can you do it in O(n) time? public class MaximumSizeSubarraySumEqualsK { public int maxSubArrayLen(int[] nums, int k) { if(nums.length == 0) { return 0; } HashMap map = new HashMap(); int maxLength = 0; int total = 0; map.put(0, -1); for(int i = 0; i < nums.length; i++) { total += nums[i]; if(map.containsKey(total - k)) { maxLength = Math.max(maxLength, i - map.get(total - k)); } if(!map.containsKey(total)) { map.put(total, i); } } return maxLength; } } ================================================ FILE: leetcode/hash-table/MinimumWindowSubstring.java ================================================ // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // For example, // S = "ADOBECODEBANC" // T = "ABC" // Minimum window is "BANC". // Note: // If there is no such window in S that covers all characters in T, return the empty string "". // If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. public class MinimumWindowSubstring { public String minWindow(String s, String t) { HashMap map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } } ================================================ FILE: leetcode/hash-table/SingleNumberII.java ================================================ //Given an array of integers, every element appears three times except for one, //which appears exactly once. Find that single one. //Note: //Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? class SingleNumberII { public int singleNumber(int[] nums) { HashMap map = new HashMap(); for(int i: nums) { if(map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { map.put(i, 1); } } for(int key: map.keySet()) { if(map.get(key) == 1) { return key; } } //no unique integer in nums return -1; } } ================================================ FILE: leetcode/hash-table/SparseMatrixMultiplication.java ================================================ // Given two sparse matrices A and B, return the result of AB. // You may assume that A's column number is equal to B's row number. // Example: // A = [ // [ 1, 0, 0], // [-1, 0, 3] // ] // B = [ // [ 7, 0, 0 ], // [ 0, 0, 0 ], // [ 0, 0, 1 ] // ] // | 1 0 0 | | 7 0 0 | | 7 0 0 | // AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // | 0 0 1 | public class SparseMatrixMultiplication { public int[][] multiply(int[][] A, int[][] B) { int m = A.length; int n = A[0].length; int nB = B[0].length; int[][] C = new int[m][nB]; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(A[i][j] != 0) { for(int k = 0; k < nB; k++) { if(B[j][k] != 0) { C[i][k] += A[i][j] * B[j][k]; } } } } } return C; } } ================================================ FILE: leetcode/hash-table/StrobogrammaticNumber.java ================================================ // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). // Write a function to determine if a number is strobogrammatic. The number is represented as a string. // For example, the numbers "69", "88", and "818" are all strobogrammatic. public class StrobogrammaticNumber { public boolean isStrobogrammatic(String num) { for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { return false; } } return true; } } ================================================ FILE: leetcode/hash-table/TwoSum.java ================================================ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // Example: // Given nums = [2, 7, 11, 15], target = 9, // Because nums[0] + nums[1] = 2 + 7 = 9, // return [0, 1]. public class TwoSum { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(map.containsKey(target - nums[i])) { result[1] = i; result[0] = map.get(target - nums[i]); return result; } map.put(nums[i], i); } return result; } } ================================================ FILE: leetcode/hash-table/UniqueWordAbbreviation.java ================================================ // An abbreviation of a word follows the form . Below are some examples of word abbreviations: // a) it --> it (no abbreviation) // 1 // b) d|o|g --> d1g // 1 1 1 // 1---5----0----5--8 // c) i|nternationalizatio|n --> i18n // 1 // 1---5----0 // d) l|ocalizatio|n --> l10n // Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. // Example: // Given dictionary = [ "deer", "door", "cake", "card" ] // isUnique("dear") -> // false // isUnique("cart") -> // true // isUnique("cane") -> // false // isUnique("make") -> // true import java.util.ArrayList; public class UniqueWordAbbreviation { HashMap map; public ValidWordAbbr(String[] dictionary) { this.map = new HashMap(); for(String word : dictionary) { String key = getKey(word); if(map.containsKey(key)) { if(!map.get(key).equals(word)) { map.put(key, ""); } } else { map.put(key, word); } } } public boolean isUnique(String word) { return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word); } public String getKey(String word) { if(word.length() <= 2) { return word; } return word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1); } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord"); ================================================ FILE: leetcode/hash-table/ValidAnagram.java ================================================ class ValidAnagram { public boolean isAnagram(String s, String t) { HashMap map = new HashMap(); for(char c: s.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } for(char c: t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c) - 1); } else { return false; } } for(char c: map.keySet()) { if(map.get(c) != 0) { return false; } } return true; } } ================================================ FILE: leetcode/hash-table/ValidSudoku.java ================================================ //Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx) //The Sudoku board could be partially filled, where empty cells are filled with the character '.'. //A partially filled sudoku which is valid. //Note: //A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. class ValidSudoku { public boolean isValidSudoku(char[][] board) { for(int i = 0; i < board.length; i++){ HashSet rows = new HashSet(); HashSet columns = new HashSet(); HashSet box = new HashSet(); for (int j = 0; j < board[0].length; j++){ if(board[i][j] != '.' && !rows.add(board[i][j])) { return false; } if(board[j][i]!='.' && !columns.add(board[j][i])) { return false; } int rowIndex = (i / 3) * 3; int columnIndex = (i % 3) * 3; if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) { return false; } } } return true; } } ================================================ FILE: leetcode/linked-list/AddTwoNumbers.java ================================================ // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 0 -> 8 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode current1 = l1; ListNode current2 = l2; ListNode head = new ListNode(0); ListNode currentHead = head; int sum = 0; while(current1 != null || current2 != null) { sum /= 10; if(current1 != null) { sum += current1.val; current1 = current1.next; } if(current2 != null) { sum += current2.val; current2 = current2.next; } currentHead.next = new ListNode(sum % 10); currentHead = currentHead.next; } if(sum / 10 == 1) { currentHead.next = new ListNode(1); } return head.next; } } ================================================ FILE: leetcode/linked-list/DeleteNodeInALinkedList.java ================================================ // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. // 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. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class DeleteNodeInALinkedList { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } } ================================================ FILE: leetcode/linked-list/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: leetcode/linked-list/MergeKSortedLists.java ================================================ // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists==null||lists.length==0) { return null; } PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val stack = new Stack(); ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null) { stack.push(slow.val); fast = fast.next.next; slow = slow.next; } if(fast != null) { slow = slow.next; } while(slow != null) { if(stack.pop() != slow.val) { return false; } slow = slow.next; } return true; } } ================================================ FILE: leetcode/linked-list/PlusOneLinkedList.java ================================================ // Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. // You may assume the integer do not contain any leading zero, except the number 0 itself. // The digits are stored such that the most significant digit is at the head of the list. // Example: // Input: // 1->2->3 // Output: // 1->2->4 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class PlusOneLinkedList { public ListNode plusOne(ListNode head) { if(plusOneRecursive(head) == 0) { return head; } else { ListNode newHead = new ListNode(1); newHead.next = head; return newHead; } } private int plusOneRecursive(ListNode head) { if(head == null) { return 1; } int carry = plusOneRecursive(head.next); if(carry == 0) { return 0; } int value = head.val + 1; head.val = value % 10; return value/10; } } ================================================ FILE: leetcode/linked-list/ReverseLinkedList.java ================================================ // Reverse a singly linked list. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null) { return head; } ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } } ================================================ FILE: leetcode/math/AddDigits.java ================================================ //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } } ================================================ FILE: leetcode/math/BulbSwitcher.java ================================================ //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. //Example: //Given n = 3. //At first, the three bulbs are [off, off, off]. //After first round, the three bulbs are [on, on, on]. //After second round, the three bulbs are [on, off, on]. //After third round, the three bulbs are [on, off, off]. //So you should return 1, because there is only one bulb is on. class BulbSwitcher { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } } ================================================ FILE: leetcode/math/EncodeAndDecodeTinyURL.java ================================================ //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl //and it returns a short URL such as http://tinyurl.com/4e9iAk. // //Design the encode and decode methods for the TinyURL service. There is no restriction on how your //encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL //and the tiny URL can be decoded to the original URL. public class EncodeAndDecodeTinyURL { HashMap map = new HashMap(); String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int count = 1; public String getKey() { String key = ""; while(count > 0) { count--; key += characters.charAt(count); count /= characters.length(); } return key; } // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key = getKey(); map.put(key, longUrl); count++; return "http://tinyurl.com/" + key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.replace("http://tinyurl.com/", "")); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url)); ================================================ FILE: leetcode/math/PalindromeNumber.java ================================================ //Determine whether an integer is a palindrome. Do this without extra space. class PalindromeNumber { public boolean isPalindrome(int x) { if(x < 0) { return false; } int num = x; int reversed = 0; while(num != 0) { reversed = reversed * 10 + num % 10; num /= 10; } return x == reversed; } } ================================================ FILE: leetcode/math/PlusOne.java ================================================ //Given a non-empty array of digits representing a non-negative integer, plus one to the integer. // //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. // //You may assume the integer does not contain any leading zero, except the number 0 itself. // //Example 1: // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. //Example 2: // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ================================================ FILE: leetcode/math/PoorPigs.java ================================================ //There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. //They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the //minimum amount of pigs you need to figure out which bucket contains the poison within one hour. //Answer this question, and write an algorithm for the follow-up general case. //Follow-up: //If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) //you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison. class PoorPigs { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int numPigs = 0; while (Math.pow(minutesToTest / minutesToDie + 1, numPigs) < buckets) { numPigs++; } return numPigs; } } ================================================ FILE: leetcode/math/PowerOfTwo.java ================================================ //Given an integer, write a function to determine if it is a power of two. // //Example 1: // //Input: 1 //Output: true //Example 2: // //Input: 16 //Output: true //Example 3: // //Input: 218 //Output: false class PowerOfTwo { public boolean isPowerOfTwo(int n) { long i = 1; while(i < n) { i <<= 1; } return i == n; } } ================================================ FILE: leetcode/queue/MovingAverageFromDataStream.java ================================================ // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. // For example, // MovingAverage m = new MovingAverage(3); // m.next(1) = 1 // m.next(10) = (1 + 10) / 2 // m.next(3) = (1 + 10 + 3) / 3 // m.next(5) = (10 + 3 + 5) / 3 /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */ public class MovingAverageFromDataStream { double previousSum = 0.0; int maxSize; Queue window; /** Initialize your data structure here. */ public MovingAverage(int size) { this.maxSize = size; window = new LinkedList(); } public double next(int val) { if(window.size() == maxSize) { previousSum -= window.remove(); } window.add(val); previousSum += val; return previousSum / window.size(); } } ================================================ FILE: leetcode/sort/MeetingRooms.java ================================================ // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return false. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class MeetingRooms { public boolean canAttendMeetings(Interval[] intervals) { if(intervals == null) { return false; } // Sort the intervals by start time Arrays.sort(intervals, new Comparator() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); for(int i = 1; i < intervals.length; i++) { if(intervals[i].start < intervals[i - 1].end) { return false; } } return true; } } ================================================ FILE: leetcode/sort/MeetingRoomsII.java ================================================ // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return 2. /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class MeetingRoomsII { public int minMeetingRooms(Interval[] intervals) { int[] starts = new int[intervals.length]; int[] ends = new int[intervals.length]; for(int i=0; i stack; public BSTIterator(TreeNode root) { stack = new Stack(); while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return stack.isEmpty() ? false : true; } /** @return the next smallest number */ public int next() { TreeNode nextSmallest = stack.pop(); TreeNode addToStack = nextSmallest.right; while(addToStack != null) { stack.add(addToStack); addToStack = addToStack.left; } return nextSmallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: leetcode/stack/DailyTemperatures.java ================================================ //Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack stack = new Stack(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } } ================================================ FILE: leetcode/stack/DecodeString.java ================================================ // Given an encoded string, return it's decoded string. // The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. // You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. // Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. public class DecodeString { public String decodeString(String s) { //declare empty string String decoded = ""; //initialize stack to hold counts Stack countStack = new Stack(); //initalize stack to hold decoded string Stack decodedStack = new Stack(); //initialize index to zero int index = 0; //iterate through entire string while(index < s.length()) { //if the current character is numeric... if(Character.isDigit(s.charAt(index))) { int count = 0; //determine the number while(Character.isDigit(s.charAt(index))) { count = 10 * count + (s.charAt(index) - '0'); index++; } //push the number onto the count stack countStack.push(count); } else if(s.charAt(index) == '[') { //if the current character is an opening bracket decodedStack.push(decoded); decoded = ""; index++; } else if(s.charAt(index) == ']') { //if the current character is a closing bracket StringBuilder temp = new StringBuilder(decodedStack.pop()); int repeatTimes = countStack.pop(); for(int i = 0; i < repeatTimes; i++) { temp.append(decoded); } decoded = temp.toString(); index++; } else { //otherwise, append the current character to the decoded string decoded += s.charAt(index); index++; } } //return the decoded string return decoded; } } ================================================ FILE: leetcode/stack/ExclusiveTimeOfFunctions.java ================================================ //Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List logs) { Stack stack = new Stack (); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } } ================================================ FILE: leetcode/stack/FlattenNestedListIterator.java ================================================ // Given a nested list of integers, implement an iterator to flatten it. // Each element is either an integer, or a list -- whose elements may also be integers or other lists. // Example 1: // Given the list [[1,1],2,[1,1]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. // Example 2: // Given the list [1,[4,[6]]], // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List getList(); * } */ public class FlattenNestedListIterator implements Iterator { Stack stack = new Stack(); public NestedIterator(List nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger current = stack.peek(); if(current.isInteger()) { return true; } stack.pop(); for(int i = current.getList().size() - 1; i >= 0; i--) { stack.push(current.getList().get(i)); } } return false; } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */ ================================================ FILE: leetcode/stack/MinStack.java ================================================ //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } } ================================================ FILE: leetcode/stack/TrappingRainWater.java ================================================ // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // For example, // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. public class TrappingRainWater { public int trap(int[] height) { int water = 0; int leftIndex = 0; int rightIndex = height.length - 1; int leftMax = 0; int rightMax = 0; while(leftIndex <= rightIndex) { leftMax = Math.max(leftMax, height[leftIndex]); rightMax = Math.max(rightMax, height[rightIndex]); if(leftMax < rightMax) { water += leftMax - height[leftIndex]; leftIndex++; } else { water += rightMax - height[rightIndex]; rightIndex--; } } return water; } } ================================================ FILE: leetcode/string/AddBinary.java ================================================ // Given two binary strings, return their sum (also a binary string). // For example, // a = "11" // b = "1" // Return "100" public class AddBinary { public String addBinary(String a, String b) { StringBuilder result = new StringBuilder(); int carry = 0; int i = a.length() - 1; int j = b.length() - 1; while(i >= 0 || j >= 0) { int sum = carry; if(i >= 0) { sum += a.charAt(i--) - '0'; } if(j >= 0) { sum += b.charAt(j--) - '0'; } result.append(sum % 2); carry = sum / 2; } if(carry != 0) { result.append(carry); } return result.reverse().toString(); } } ================================================ FILE: leetcode/string/CountAndSay.java ================================================ // The count-and-say sequence is the sequence of integers beginning as follows: // 1, 11, 21, 1211, 111221, ... // 1 is read off as "one 1" or 11. // 11 is read off as "two 1s" or 21. // 21 is read off as "one 2, then one 1" or 1211. // Given an integer n, generate the nth sequence. // Note: The sequence of integers will be represented as a string. public class CountAndSay { public String countAndSay(int n) { String s = "1"; for(int i = 1; i < n; i++) { s = helper(s); } return s; } public String helper(String s) { StringBuilder sb = new StringBuilder(); char c = s.charAt(0); int count = 1; for(int i = 1; i < s.length(); i++) { if(s.charAt(i) == c) { count++; } else { sb.append(count); sb.append(c); c = s.charAt(i); count = 1; } } sb.append(count); sb.append(c); return sb.toString(); } } ================================================ FILE: leetcode/string/DecodeWays.java ================================================ // A message containing letters from A-Z is being encoded to numbers using the following mapping: // 'A' -> 1 // 'B' -> 2 // ... // 'Z' -> 26 // Given an encoded message containing digits, determine the total number of ways to decode it. // For example, // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). // The number of ways decoding "12" is 2. public class DecodeWays { public int numDecodings(String s) { int n = s.length(); if(n == 0) { return 0; } int[] dp = new int[n + 1]; dp[n] = 1; dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; for(int i = n - 2; i >= 0; i--) { if(s.charAt(i) == '0') { continue; } else { dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; } } return dp[0]; } } ================================================ FILE: leetcode/string/EditDistance.java ================================================ // Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) // You have the following 3 operations permitted on a word: // a) Insert a character // b) Delete a character // c) Replace a character public class EditDistance { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for(int i = 0; i <= m; i++) { dp[i][0] = i; } for(int i = 0; i <= n; i++) { dp[0][i] = i; } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(word1.charAt(i) == word2.charAt(j)) { dp[i + 1][j + 1] = dp[i][j]; } else { int a = dp[i][j]; int b = dp[i][j + 1]; int c = dp[i + 1][j]; dp[i + 1][j + 1] = Math.min(a, Math.min(b, c)); dp[i + 1][j + 1]++; } } } return dp[m][n]; } } ================================================ FILE: leetcode/string/FirstUniqueCharacterInAString.java ================================================ //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. // //Examples: // //s = "leetcode" //return 0. // //s = "loveleetcode", //return 2. //Note: You may assume the string contain only lowercase letters. class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { HashMap characters = new HashMap(); for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); if(characters.containsKey(current)) { characters.put(current, -1); } else { characters.put(current, i); } } int min = Integer.MAX_VALUE; for(char c: characters.keySet()) { if(characters.get(c) > -1 && characters.get(c) < min) { min = characters.get(c); } } return min == Integer.MAX_VALUE ? -1 : min; } } ================================================ FILE: leetcode/string/GenerateParentheses.java ================================================ //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. // //For example, given n = 3, a solution set is: // //[ //"((()))", //"(()())", //"(())()", //"()(())", //"()()()" //] class GenerateParentheses { public List generateParenthesis(int n) { List result = new ArrayList(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } } ================================================ FILE: leetcode/string/IntegerToEnglishWords.java ================================================ // Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. // For example, // 123 -> "One Hundred Twenty Three" // 12345 -> "Twelve Thousand Three Hundred Forty Five" // 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" public class IntegerToEnglishWords { private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private final String[] TENS = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; private final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" }; public String numberToWords(int num) { if(num == 0) { return "Zero"; } int i = 0; String words = ""; while(num > 0) { if(num % 1000 != 0) { words = helper(num % 1000) + THOUSANDS[i] + " " + words; } num /= 1000; i++; } return words.trim(); } private String helper(int num) { if(num == 0) { return ""; } else if(num < 20) { return LESS_THAN_20[num] + " "; } else if(num < 100) { return TENS[num / 10] + " " + helper(num % 10); } else { return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); } } } ================================================ FILE: leetcode/string/JudgeRouteCircle.java ================================================ //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. // //The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. // //Example 1: //Input: "UD" //Output: true //Example 2: //Input: "LL" //Output: false class JudgeRouteCircle { public boolean judgeCircle(String moves) { int UD = 0; int LR = 0; for(int i = 0; i < moves.length(); i++) { if(moves.charAt(i) == 'U') { UD++; } else if(moves.charAt(i) == 'D') { UD--; } else if(moves.charAt(i) == 'L') { LR++; } else if(moves.charAt(i) == 'R') { LR--; } } return UD == 0 && LR == 0; } } ================================================ FILE: leetcode/string/LongestCommonPrefix.java ================================================ class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) { return ""; } String s = strs[0]; for(int i = 0; i < s.length(); i++) { char current = s.charAt(i); for(int j = 1; j < strs.length; j++) { if(i >= strs[j].length() || strs[j].charAt(i) != current) { return s.substring(0, i); } } } return s; } } ================================================ FILE: leetcode/string/LongestPalindrome.java ================================================ public class LongestPalindrome { public int longestPalindrome(String s) { HashMap map = new HashMap(); int count = 0; for(int i = 0; i < s.length(); i++) { if(!map.containsKey(s.charAt(i))) { map.put(s.charAt(i), (int)(s.charAt(i))); } else { map.remove(s.charAt(i)); count++; } } return map.isEmpty() ? count * 2 : count * 2 + 1; } } ================================================ FILE: leetcode/string/LongestPalindromicSubstring.java ================================================ //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. //Example: //Input: "babad" //Output: "bab" //Note: "aba" is also a valid answer. //Example: //Input: "cbbd" //Output: "bb" class LongestPalindromicSubstring { public String longestPalindrome(String s) { if(s == null || s.length() == 0) { return ""; } String longestPalindromicSubstring = ""; for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) { longestPalindromicSubstring = s.substring(i, j); } } } return longestPalindromicSubstring; } public boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; while(i <= j) { if(s.charAt(i++) != s.charAt(j--)) { return false; } } return true; } } ================================================ FILE: leetcode/string/LongestSubstringWithAtMostKDistinctCharacters.java ================================================ // Given a string, find the length of the longest substring T that contains at most k distinct characters. // For example, Given s = “eceba” and k = 2, // T is "ece" which its length is 3. public class LongestSubstringWithAtMostKDistinctCharacters { public int lengthOfLongestSubstringKDistinct(String s, int k) { int[] count = new int[256]; // there are 256 ASCII characters in the world int i = 0; // i will be behind j int num = 0; int res = 0; for (int j = 0; j < s.length(); j++) { if (count[s.charAt(j)] == 0) { // if count[s.charAt(j)] == 0, we know that it is a distinct character num++; } count[s.charAt(j)]++; while (num > k && i < s.length()) { // sliding window count[s.charAt(i)]--; if (count[s.charAt(i)] == 0){ num--; } i++; } res = Math.max(res, j - i + 1); } return res; } } ================================================ FILE: leetcode/string/MinimumWindowSubstring.java ================================================ // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // For example, // S = "ADOBECODEBANC" // T = "ABC" // Minimum window is "BANC". // Note: // If there is no such window in S that covers all characters in T, return the empty string "". // If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. public class MinimumWindowSubstring { public String minWindow(String s, String t) { HashMap map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } } ================================================ FILE: leetcode/string/MultiplyStrings.java ================================================ // Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // Note: // The length of both num1 and num2 is < 110. // Both num1 and num2 contains only digits 0-9. // Both num1 and num2 does not contain any leading zero. // You must not use any built-in BigInteger library or convert the inputs to integer directly. public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) if(!(sb.length() == 0 && p == 0)) { sb.append(p); } return sb.length() == 0 ? "0" : sb.toString(); } } ================================================ FILE: leetcode/string/OneEditDistance.java ================================================ // Given two strings S and T, determine if they are both one edit distance apart. public class OneEditDistance { public boolean isOneEditDistance(String s, String t) { //iterate through the length of the smaller string for(int i = 0; i < Math.min(s.length(), t.length()); i++) { //if the current characters of the two strings are not equal if(s.charAt(i) != t.charAt(i)) { //return true if the remainder of the two strings are equal, false otherwise if(s.length() == t.length()) { return s.substring(i + 1).equals(t.substring(i + 1)); } else if(s.length() < t.length()) { //return true if the strings would be the same if you deleted a character from string t return s.substring(i).equals(t.substring(i + 1)); } else { //return true if the strings would be the same if you deleted a character from string s return t.substring(i).equals(s.substring(i + 1)); } } } //if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1 return Math.abs(s.length() - t.length()) == 1; } } ================================================ FILE: leetcode/string/PalindromePermutation.java ================================================ public class PalindromePermutation { public boolean canPermutePalindrome(String s) { char[] characters = new char[256]; for(int i = 0; i < s.length(); i++) { characters[s.charAt(i)]++; } int oddCount = 0; for(int i = 0; i < characters.length; i++) { if(!(characters[i] % 2 == 0)) { oddCount++; if(oddCount > 1) { return false; } } } return true; } } ================================================ FILE: leetcode/string/PalindromicSubstrings.java ================================================ //Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } } ================================================ FILE: leetcode/string/ReverseVowelsOfAString.java ================================================ // Write a function that takes a string as input and reverse only the vowels of a string. // Example 1: // Given s = "hello", return "holle". // Example 2: // Given s = "leetcode", return "leotcede". // Note: // The vowels does not include the letter "y". public class ReverseVowelsOfAString { public String reverseVowels(String s) { if(s == null || s.length() == 0) { return s; } String vowels = "aeiouAEIOU"; char[] chars = s.toCharArray(); int start = 0; int end = s.length() - 1; while(start < end) { while(start < end && !vowels.contains(chars[start] + "")) { start++; } while(start < end && !vowels.contains(chars[end] + "")) { end--; } char temp = chars[start]; chars[start] = chars[end]; chars[end] = temp; start++; end--; } return new String(chars); } } ================================================ FILE: leetcode/string/ReverseWordsInAString.java ================================================ //Given an input string, reverse the string word by word. //For example, //Given s = "the sky is blue", //return "blue is sky the". public class ReverseWordsInAString { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); String result = ""; for(int i = words.length - 1; i > 0; i--) { result += words[i] + " "; } return result + words[0]; } } ================================================ FILE: leetcode/string/RomanToInteger.java ================================================ // Given a roman numeral, convert it to an integer. // Input is guaranteed to be within the range from 1 to 3999 public class RomanToInteger { public int romanToInt(String s) { HashMap map = new HashMap(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int total = 0; for(int i = 0; i < s.length() - 1; i++) { if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { total -= map.get(s.charAt(i)); } else { total += map.get(s.charAt(i)); } } total += map.get(s.charAt(s.length() - 1)); return total; } } ================================================ FILE: leetcode/string/ValidPalindrome.java ================================================ public class ValidPalindrome { public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while(left < right) { while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { left++; } while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { right--; } if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } } ================================================ FILE: leetcode/string/ValidParentheses.java ================================================ // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public class ValidParentheses { public boolean isValid(String s) { if(s.length() % 2 == 1) { return false; } Stack stack = new Stack(); for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') { stack.pop(); } else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') { stack.pop(); } else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') { stack.pop(); } else { return false; } } return stack.isEmpty(); } } ================================================ FILE: leetcode/tree/BinaryTreeMaximumPathSum.java ================================================ // Given a binary tree, find the maximum path sum. // For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. // For example: // Given the below binary tree, // 1 // / \ // 2 3 // Return 6. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeMaximumPathSum { int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxPathSumRecursive(root); return max; } private int maxPathSumRecursive(TreeNode root) { if(root == null) { return 0; } int left = Math.max(maxPathSumRecursive(root.left), 0); int right = Math.max(maxPathSumRecursive(root.right), 0); max = Math.max(max, root.val + left + right); return root.val + Math.max(left, right); } } ================================================ FILE: leetcode/tree/BinaryTreePaths.java ================================================ // Given a binary tree, return all root-to-leaf paths. // For example, given the following binary tree: // 1 // / \ // 2 3 // \ // 5 // All root-to-leaf paths are: // ["1->2->5", "1->3"] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreePaths { public List binaryTreePaths(TreeNode root) { List result = new ArrayList(); if(root == null) { return result; } helper(new String(), root, result); return result; } public void helper(String current, TreeNode root, List result) { if(root.left == null && root.right == null) { result.add(current + root.val); } if(root.left != null) { helper(current + root.val + "->", root.left, result); } if(root.right != null) { helper(current + root.val + "->", root.right, result); } } } ================================================ FILE: leetcode/tree/InorderSuccessorInBST.java ================================================ // Given a binary search tree and a node in it, find the in-order successor of that node in the BST. // Note: If the given node has no in-order successor in the tree, return null. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InorderSuccessorInBST { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode successor = null; while(root != null) { if(p.val < root.val) { successor = root; root = root.left; } else { root = root.right; } } return successor; } } ================================================ FILE: leetcode/tree/InvertBinaryTree.java ================================================ // Invert a binary tree. // 4 // / \ // 2 7 // / \ / \ // 1 3 6 9 // to // 4 // / \ // 7 2 // / \ / \ // 9 6 3 1 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InvertBinaryTree { public TreeNode invertTree(TreeNode root) { if(root == null) { return root; } TreeNode temp = root.left; root.left = invertTree(root.right); root.right = invertTree(temp); return root; } } ================================================ FILE: leetcode/tree/LowestCommonAncestorOfABinaryTree.java ================================================ // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } } ================================================ FILE: leetcode/tree/SumOfLeftLeaves.java ================================================ // Find the sum of all left leaves in a given binary tree. // Example: // 3 // / \ // 9 20 // / \ // 15 7 // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SumOfLeftLeaves { public int sumOfLeftLeaves(TreeNode root) { if(root == null) { return 0; } int total = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) { total += root.left.val; } else { total += sumOfLeftLeaves(root.left); } } total += sumOfLeftLeaves(root.right); return total; } } ================================================ FILE: leetcode/tree/TrimABinarySearchTree.java ================================================ //Given a binary search tree and the lowest and highest boundaries as L and R, trim the //tree so that all its elements lies in [L, R] (R >= L). You might need to change the root //of the tree, so the result should return the new root of the trimmed binary search tree. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class TrimABinarySearchTree { public TreeNode trimBST(TreeNode root, int L, int R) { if(root == null) { return root; } if(root.val < L) { return trimBST(root.right, L, R); } if(root.val > R) { return trimBST(root.left, L, R); } root.left = trimBST(root.left, L, R); root.right = trimBST(root.right, L, R); return root; } } ================================================ FILE: leetcode/tree/ValidateBinarySearchTree.java ================================================ // Given a binary tree, determine if it is a valid binary search tree (BST). // Assume a BST is defined as follows: // The left subtree of a node contains only nodes with keys less than the node's key. // The right subtree of a node contains only nodes with keys greater than the node's key. // Both the left and right subtrees must also be binary search trees. // Example 1: // 2 // / \ // 1 3 // Binary tree [2,1,3], return true. // Example 2: // 1 // / \ // 2 3 // Binary tree [1,2,3], return false. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ValidateBinarySearchTree { public boolean isValidBST(TreeNode root) { if(root == null) { return true; } return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) { if(root == null) { return true; } else if(root.val >= maxValue || root.val <= minValue) { return false; } else { return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue); } } } ================================================ FILE: leetcode/trie/AddAndSearchWordDataStructureDesign.java ================================================ // Design a data structure that supports the following two operations: // void addWord(word) // bool search(word) // search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. // For example: // addWord("bad") // addWord("dad") // addWord("mad") // search("pad") -> false // search("bad") -> true // search(".ad") -> true // search("b..") -> true // Note: // You may assume that all words are consist of lowercase letters a-z. public class AddAndSearchWordDataStructure { public class TrieNode { public TrieNode[] children = new TrieNode[26]; public String item = ""; } private TrieNode root = new TrieNode(); public void addWord(String word) { TrieNode node = root; for (char c : word.toCharArray()) { if (node.children[c - 'a'] == null) { node.children[c - 'a'] = new TrieNode(); } node = node.children[c - 'a']; } node.item = word; } public boolean search(String word) { return match(word.toCharArray(), 0, root); } private boolean match(char[] chs, int k, TrieNode node) { if (k == chs.length) { return !node.item.equals(""); } if (chs[k] != '.') { return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']); } else { for (int i = 0; i < node.children.length; i++) { if (node.children[i] != null) { if (match(chs, k + 1, node.children[i])) { return true; } } } } return false; } } ================================================ FILE: leetcode/trie/ImplementTrie.java ================================================ // Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap(); this.character = character; this.last = false; } } public class ImplementTrie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } } ================================================ FILE: leetcode/trie/WordSquares.java ================================================ // Given a set of words (without duplicates), find all word squares you can build from them. // A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). // For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. // b a l l // a r e a // l e a d // l a d y // Note: // There are at least 1 and at most 1000 words. // All words will have the exact same length. // Word length is at least 1 and at most 5. // Each word contains only lowercase English alphabet a-z. public class WordSquares { public List> wordSquares(String[] words) { List> ret = new ArrayList>(); if(words.length==0 || words[0].length()==0) { return ret; } Map> map = new HashMap<>(); int squareLen = words[0].length(); // create all prefix for(int i=0;i()); } map.get(words[i].substring(0, j+1)).add(words[i]); } } helper(ret, new ArrayList(), 0, squareLen, map); return ret; } public void helper(List> ret, List cur, int matched, int total, Map> map){ if(matched == total) { ret.add(new ArrayList(cur)); return; } // build search string StringBuilder sb = new StringBuilder(); for(int i=0;i<=matched-1;i++) { sb.append(cur.get(i).charAt(matched)); } // bachtracking Set cand = map.get(sb.toString()); if(cand==null) { return; } for(String str:cand){ cur.add(str); helper(ret, cur, matched+1, total, map); cur.remove(cur.size()-1); } } } ================================================ FILE: leetcode/two-pointers/3Sum.java ================================================ // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // Note: The solution set must not contain duplicate triplets. // For example, given array S = [-1, 0, 1, 2, -1, -4], // A solution set is: // [ // [-1, 0, 1], // [-1, -1, 2] // ] public class 3Sum { public List> threeSum(int[] nums) { List> result = new ArrayList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; int target = -nums[i]; while(j < k) { if(nums[j] + nums[k] == target) { ArrayList temp = new ArrayList(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); result.add(temp); j++; k--; while(j < k && nums[j] == nums[j - 1]) { j++; } while(j < k && nums[k] == nums[k + 1]) { k--; } } else if(nums[j] + nums[k] > target) { k--; } else { j++; } } } return result; } } ================================================ FILE: leetcode/two-pointers/3SumSmaller.java ================================================ // Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. // For example, given nums = [-2, 0, 1, 3], and target = 2. // Return 2. Because there are two triplets which sums are less than 2: // [-2, 0, 1] // [-2, 0, 3] // Follow up: // Could you solve it in O(n2) runtime? public class 3SumSmaller { public int threeSumSmaller(int[] nums, int target) { //initialize total count to zero int count = 0; //sort the array Arrays.sort(nums); //loop through entire array for(int i = 0; i < nums.length - 2; i++) { //set left to i + 1 int left = i + 1; //set right to end of array int right = nums.length - 1; //while left index < right index while(left < right) { //if the 3 indices add to less than the target increment count if(nums[i] + nums[left] + nums[right] < target) { //increment the count by the distance between left and right because the array is sorted count += right - left; //decrement right pointer left++; } else { //if they sum to a value greater than target... //increment left pointer right--; } } } return count; } } ================================================ FILE: leetcode/two-pointers/LinkedListCycle.java ================================================ //Given a linked list, determine if it has a cycle in it. //Follow up: //Can you solve it without using extra space? /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null && fast != slow) { slow = slow.next; fast = fast.next.next; } return fast == slow; } } ================================================ FILE: leetcode/two-pointers/MergeSortedArray.java ================================================ // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. // Note: // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. public class MergeSortedArray { public void merge(int[] A, int m, int[] B, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1; while(i >= 0 && j >= 0) { A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } while(j >= 0) { A[k--] = B[j--]; } } } ================================================ FILE: leetcode/two-pointers/MinimumSizeSubarraySum.java ================================================ // Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. // For example, given the array [2,3,1,2,4,3] and s = 7, // the subarray [4,3] has the minimal length under the problem constraint. public class MinimumSizeSubarraySum { public int minSubArrayLen(int s, int[] nums) { if(nums == null || nums.length == 0) { return 0; } int i = 0; int j = 0; int result = Integer.MAX_VALUE; int total = 0; while(i < nums.length) { total += nums[i++]; while(total >= s) { result = Math.min(result, i - j); total -= nums[j++]; } } return result == Integer.MAX_VALUE ? 0 : result; } } ================================================ FILE: leetcode/two-pointers/MoveZeros.java ================================================ // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. // Note: // You must do this in-place without making a copy of the array. // Minimize the total number of operations. public class MoveZeros { public void moveZeroes(int[] nums) { if(nums == null || nums.length == 0) { return; } int index = 0; for(int num : nums) { if(num != 0) { nums[index] = num; index++; } } while(index < nums.length) { nums[index] = 0; index++; } } } ================================================ FILE: leetcode/two-pointers/RemoveDuplicatesFromSortedArray.java ================================================ // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. // Do not allocate extra space for another array, you must do this in place with constant memory. // For example, // Given input array nums = [1,1,2], // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. public class RemoveDuplicatesFromSortedArray { public int removeDuplicates(int[] nums) { if(nums.length == 0 || nums == null) { return 0; } if(nums.length < 2) { return nums.length; } int index = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[i - 1]) { nums[index++] = nums[i]; } } return index; } } ================================================ FILE: leetcode/two-pointers/RemoveElement.java ================================================ //Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums = [3,2,2,3], val = 3, //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } } ================================================ FILE: leetcode/two-pointers/ReverseString.java ================================================ // Write a function that takes a string as input and returns the string reversed. // Example: // Given s = "hello", return "olleh". public class ReverseString { public String reverseString(String s) { if(s == null || s.length() == 1 || s.length() == 0) { return s; } char[] word = s.toCharArray(); for(int i = 0, j = s.length() - 1; i < j; i++, j--) { char temp = word[i]; word[i] = word[j]; word[j] = temp; } return new String(word); } } ================================================ FILE: leetcode/two-pointers/SortColors.java ================================================ // Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. // Note: // You are not suppose to use the library's sort function for this problem. public class SortColors { public void sortColors(int[] nums) { int wall = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] < 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } for(int i = 0; i < nums.length; i++) { if(nums[i] == 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } } } ================================================ FILE: uva/AddingReversedNumbers.java ================================================ /** * The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient * plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies * into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, * although all the things change to their opposites. For example the numbers: if any number appears in * the tragedy, it must be converted to its reversed form before being accepted into the comedy play. * Reversed number is a number written in arabic numerals but the order of digits is reversed. The * first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the * tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the * number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed * number never has any trailing zeros. * ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and * output their reversed sum. Of course, the result is not unique because any particular number is a * reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must * assume that no zeros were lost by reversing (e.g. assume that the original number was 12). * Input * The input consists of N cases. The first line of the input contains only positive integer N. Then follow * the cases. Each case consists of exactly one line with two positive integers separated by space. These * are the reversed numbers you are to add. Numbers will be at most 200 characters long. * Output * For each case, print exactly one line containing only one integer — the reversed sum of two reversed * numbers. Omit any leading zeros in the output. * Sample Input * 3 * 24 1 * 4358 754 * 305 794 * Sample Output * 34 * 1998 * 1 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=654 import java.math.BigInteger; import java.util.Scanner; public class AddingReversedNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger first = input.nextBigInteger(); BigInteger second = input.nextBigInteger(); StringBuilder firstString = new StringBuilder(first + ""); StringBuilder secondString = new StringBuilder(second + ""); BigInteger firstReversed = new BigInteger(firstString.reverse() .toString()); BigInteger secondReversed = new BigInteger(secondString.reverse() .toString()); BigInteger result = firstReversed.add(secondReversed); String resultReversed = new StringBuilder(result + "").reverse() .toString(); System.out.println(resultReversed.replaceFirst("^0*", "")); numberOfTestCases--; } } } ================================================ FILE: uva/Ants.java ================================================ // An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When // a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn // back and start walking in opposite directions. We know the original positions of ants on the pole, // unfortunately, we do not know the directions in which the ants are walking. Your task is to compute // the earliest and the latest possible times needed for all ants to fall off the pole. // Input // The first line of input contains one integer giving the number of cases that follow. The data for each // case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing // on the pole. These two numbers are followed by n integers giving the position of each ant on the pole // as the distance measured from the left end of the pole, in no particular order. All input integers are // not bigger than 1000000 and they are separated by whitespace. // Output // For each case of input, output two numbers separated by a single space. The first number is the earliest // possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) // and the second number is the latest possible such time. // Sample Input // 2 // 10 3 // 2 6 7 // 214 7 // 11 12 7 13 176 23 191 // Sample Output // 4 8 // 38 207 import java.util.Scanner; /** * Created by kdn251 on 2/22/17. */ public class Ants { public static void main(String args[]) throws Exception { //initialize buffered reader Scanner sc = new Scanner(System.in); //initialize test cases int testCases = sc.nextInt(); //declare current ant int currentAnt; while(testCases > 0) { //initialize length of rod and number of ants int length = sc.nextInt(); int numberOfAnts = sc.nextInt(); //initialize min and max to zero int min = 0; int max = 0; //iterate while there are still remaining ants to process while(numberOfAnts > 0) { //read in current ant currentAnt = sc.nextInt(); //calculate whether ant is closer to left side of rod or right side of rod currentAnt = currentAnt < length - currentAnt ? currentAnt : length - currentAnt; //update minimum time to most restrictive ant minimum time if(currentAnt > min) { min = currentAnt; } //update maximum time to most restrictive ant maximum time if(length - currentAnt > max) { max = length - currentAnt; } //decrement number of ants remaining numberOfAnts--; } //print min and max of current test case System.out.println(min + " " + max); //decrement number of test cases remaining testCases--; } } } //source: https://github.com/morris821028/UVa/blob/master/volume107/10714%20-%20Ants.cpp ================================================ FILE: uva/ArchaeologistsDilemma.java ================================================ /** * An archeologist seeking proof of the presence of extraterrestrials in the Earth’s past, stumbles upon a * partially destroyed wall containing strange chains of numbers. The left-hand part of these lines of digits * is always intact, but unfortunately the right-hand one is often lost by erosion of the stone. However, * she notices that all the numbers with all its digits intact are powers of 2, so that the hypothesis that * all of them are powers of 2 is obvious. To reinforce her belief, she selects a list of numbers on which it * is apparent that the number of legible digits is strictly smaller than the number of lost ones, and asks * you to find the smallest power of 2 (if any) whose first digits coincide with those of the list. * Thus you must write a program such that given an integer, it determines (if it exists) the smallest * exponent E such that the first digits of 2 * E coincide with the integer (remember that more than half of * the digits are missing). * Input * It is a set of lines with a positive integer N not bigger than 2147483648 in each of them. * Output * For every one of these integers a line containing the smallest positive integer E such that the first digits * of 2 * E are precisely the digits of N, or, if there is no one, the sentence ‘no power of 2’. * Sample Input * 1 * 2 * 10 * Sample Output * 7 * 8 * 20 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=642 import java.io.IOException; import java.util.Scanner; public class ArchaeologistsDilemma { public static final boolean DEBUG = true; public static final boolean DEBUG_INPUT = true; final static double LOG2 = Math.log(2.0); final static double LOG2_10 = Math.log(10) / LOG2; public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { long N = input.nextLong(); int k = (N + "").length() + 1; long lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10); long upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10); while (lowerBound == upperBound) { k++; lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10); upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10); } System.out.println(upperBound); } } } ================================================ FILE: uva/AverageSpeed.java ================================================ /** * You have bought a car in order to drive from Waterloo to a big city. The odometer on their car is * broken, so you cannot measure distance. But the speedometer and cruise control both work, so the car * can maintain a constant speed which can be adjusted from time to time in response to speed limits, * traffic jams, and border queues. You have a stopwatch and note the elapsed time every time the speed * changes. From time to time you wonder, “how far have I come?”. To solve this problem you must write * a program to run on your laptop computer in the passenger seat. * Input * Standard input contains several lines of input: Each speed change is indicated by a line specifying the * elapsed time since the beginning of the trip (hh:mm:ss), followed by the new speed in km/h. Each * query is indicated by a line containing the elapsed time. At the outset of the trip the car is stationary. * Elapsed times are given in non-decreasing order and there is at most one speed change at any given * time. * Output * For each query in standard input, you should print a line giving the time and the distance travelled, in * the format below. * Sample Input * 00:00:01 100 * 00:15:01 * 00:30:01 * 01:00:01 50 * 03:00:01 * 03:00:05 140 * Sample Output * 00:15:01 25.00 km * 00:30:01 50.00 km * 03:00:01 200.00 km */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1222 import java.text.DecimalFormat; import java.util.Scanner; public class AverageSpeed { public static void main(String[] args) { int speed = 0; boolean reachedTheEnd = false; Scanner input = new Scanner(System.in); String nextLine = input.nextLine(); double hour = 0; double baseHour = 0; double kilometersPassed = 0; while (!reachedTheEnd) { String[] time1 = nextLine.split(" "); String[] time = nextLine.split(":"); String[] extendedTime = new String[2]; DecimalFormat formatter = new DecimalFormat("#0.00"); hour = calcHours(time1[0]); kilometersPassed += (hour - baseHour) * speed; if (time[2].contains(" ")) { extendedTime = time[2].split(" "); speed = Integer.valueOf(extendedTime[1]); } else { System.out.print(nextLine + " " + formatter.format(kilometersPassed) + " km\n"); } baseHour = hour; nextLine = input.nextLine(); } } private static double calcHours(String s) { String[] arr = s.split(":"); return (Integer.parseInt(arr[0]) * 3600 + Integer.parseInt(arr[1]) * 60 + Integer .parseInt(arr[2])) * 1.0 / 3600; } } ================================================ FILE: uva/BackToIntermediateMath.java ================================================ /** * Umm! So, you claim yourself as an intelligent one? Let me check. As, computer science students always * insist on optimization whenever possible, I give you an elementary problem of math to optimize. * You are trying to cross a river of width d meters. You are given that, the river flows at v ms−1 and * you know that you can speed up the boat in u ms−1 * . There may be two goals how to cross the river: * One goal (called fastest path) is to cross it in fastest time, and it does not matter how far the flow of * the river takes the boat. The other goal (called shortest path) is to steer the boat in a direction so that * the flow of the river doesn’t take the boat away, and the boat passes the river in a line perpendicular to * the boarder of the river. Is it always possible to have two different paths, one to pass at shortest time * and the other at shortest path? If possible then, what is the difference (Let P s) between the times * needed to cross the river in the different ways? * Input * The first line in the input file is an integer representing the number of test cases. Each of the test cases * follows below. Each case consists three real numbers (all are nonnegative, d is positive) denoting the * value of d, v and u respectively. * Output * For each test case, first print the serial number of the case, a colon, an space and then print ‘can’t * determine’ (without the quotes) if it is not possible to find different paths as stated above, else print * the value of P corrected to three digits after decimal point. Check the sample input & output. * Sample Input * 3 * 8 5 6 * 1 2 3 * 1 5 6 * Sample Output * Case 1: 1.079 * Case 2: 0.114 * Case 3: 0.135 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1714 import java.text.DecimalFormat; import java.util.Scanner; public class BackToIntermediateMath { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); DecimalFormat formatter = new DecimalFormat("#0.000"); for (int i = 0; i < numberOfTestCases; i++) { double distance = input.nextDouble(); double riverSpeed = input.nextDouble(); double boatSpeed = input.nextDouble(); if (riverSpeed == 0 || boatSpeed == 0 || boatSpeed <= riverSpeed) { System.out.println("Case " + (i + 1) + ": can't determine"); } else { double P1 = distance / boatSpeed; double P2 = distance / Math.sqrt(boatSpeed * boatSpeed - riverSpeed * riverSpeed); System.out.print("Case " + (i + 1) + ": " + formatter.format(Math.abs(P1 - P2)) + "\n"); } } } } ================================================ FILE: uva/BasicRemains.java ================================================ /** * Given a base b and two non-negative base b integers * p and m, compute p mod m and print the * result as a base-b integer. p mod m is defined * as the smallest non-negative integer k such that * p = a ∗ m + k for some integer a. * Input * Input consists of a number of cases. Each case is * represented by a line containing three unsigned * integers. The first, b, is a decimal number between * 2 and 10. The second, p, contains up to 1000 digits between 0 and b − 1. The third, m, contains * up to 9 digits between 0 and b − 1. The last case is followed by a line containing ‘0’. * Output * For each test case, print a line giving p mod m as a base-b integer. * Sample Input * 2 1100 101 * 10 123456789123456789123456789 1000 * 0 * Sample Output * 10 * 789 * */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1492 import java.math.BigInteger; import java.util.Scanner; public class BasicRemains { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { int baseNumber = input.nextInt(); if (baseNumber == 0) { break; } BigInteger p = new BigInteger(input.next(), baseNumber); BigInteger m = new BigInteger(input.next(), baseNumber); System.out.println((p.mod(m)).toString(baseNumber)); } } } ================================================ FILE: uva/BasicallySpeaking.java ================================================ /** * The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super * Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato * if this new calculator could convert among number bases. The company thought this was a stupendous * idea and has asked your team to come up with the prototype program for doing base conversion. The * project manager of the Super Neato Model I calculator has informed you that the calculator will have * the following neato features: * • It will have a 7-digit display. * • Its buttons will include the capital letters A through F in addition to the digits 0 through 9. * • It will support bases 2 through 16. * Input * The input for your prototype program will consist of one base conversion per line. There will be three * numbers per line. The first number will be the number in the base you are converting from. It may have * leading ‘0’s. The second number is the base you are converting from. The third number is the base you * are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There * are several lines of input and your program should continue to read until the end of file is reached. * Output * The output will only be the converted number as it would appear on the display of the calculator. * The number should be right justified in the 7-digit display. If the number is to large to appear on the * display, then print ‘ERROR’ (without the quotes) right justified in the display. * Sample Input * 1111000 2 10 * 1111000 2 16 * 2102101 3 10 * 2102101 3 15 * 12312 4 2 * 1A 15 2 * ABCD 16 15 * 03 13 10 * Sample Output * 120 * 78 * 1765 * 7CA * ERROR * 11001 * D071 * 3 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=325 import java.math.BigInteger; import java.util.Scanner; public class BasicallySpeaking { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String numberAsString = input.next(); int fromBase = input.nextInt(); int toBase = input.nextInt(); BigInteger number = new BigInteger(numberAsString, fromBase); String numberThatIsPrinted = number.toString(toBase); String answer = numberThatIsPrinted.toUpperCase(); if (numberThatIsPrinted.length() > 7) { answer = "ERROR"; } System.out.printf("%7s\n", answer); } } } ================================================ FILE: uva/BigMod.java ================================================ /** * Calculate * R := B * P mod M * for large values of B, P, and M using an efficient algorithm. (That’s right, this problem has a time * dependency !!!.) * Input * The input will contain several test cases, each of them as described below. Consecutive test cases are * separated by a single blank line. * Three integer values (in the order B, P, M) will be read one number per line. B and P are integers * in the range 0 to 2147483647 inclusive. M is an integer in the range 1 to 46340 inclusive. * Output * For each test, the result of the computation. A single integer on a line by itself. * Sample Input * 3 * 18132 * 17 * 17 * 1765 * 3 * 2374859 * 3029382 * 36123 * Sample Output * 13 * 2 * 13195 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=727&page=show_problem&problem=310 import java.math.BigInteger; import java.util.Scanner; public class BigMod { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { BigInteger b = input.nextBigInteger(); BigInteger p = input.nextBigInteger(); BigInteger m = input.nextBigInteger(); System.out.println(b.modPow(p, m)); } } } ================================================ FILE: uva/BrickGame.java ================================================ /** * There is a village in Bangladesh, where brick game is very popular. Brick game is a team game. Each * team consists of odd number of players. Number of players must be greater than 1 but cannot be * greater than 10. Age of each player must be within 11 and 20. No two players can have the same age. * There is a captain for each team. The communication gap between two players depends on their age * difference, i.e. the communication gap is larger if the age difference is larger. Hence they select the * captain of a team in such a way so that the number of players in the team who are younger than that * captain is equal to the number of players who are older than that captain. * Ages of all members of the team are provided. You have to determine the age of the captain. * Input * Input starts with an integer T (T ≤ 100), the number of test cases. * Each of the next T lines will start with an integer N (1 < N < 11), number of team members * followed by N space separated integers representing ages of all of the members of a team. Each of these * N integers will be between 11 and 20 (inclusive). Note that, ages will be given in strictly increasing * order or strictly decreasing order. We will not mention which one is increasing and which one is * decreasing, you have to be careful enough to handle both situations. * Output * For each test case, output one line in the format ‘Case x: a’ (quotes for clarity), where x is the case * number and a is the age of the captain. * Sample Input * 2 * 5 19 17 16 14 12 * 5 12 14 16 17 18 * Sample Output * Case 1: 16 * Case 2: 16 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2986 import static java.lang.Integer.parseInt; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class BrickGame { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); int caseNum = 1; while (numberOfTestCases != 0) { String[] numbersString = input.nextLine().split(" "); int numberOfMembers = parseInt(numbersString[0]); List numbers = new ArrayList(); for (int i = 0; i < numberOfMembers + 1; i++) { numbers.add(parseInt(numbersString[i])); } Collections.sort(numbers); System.out.print("Case " + caseNum + ": " + numbers.subList(1, numbers.size()).get( numberOfMembers / 2) + "\n"); numberOfTestCases--; caseNum++; } } } ================================================ FILE: uva/CoconutsRevisited.java ================================================ /** * The short story titled Coconuts, by Ben Ames Williams, appeared in the Saturday Evening Post on * October 9, 1926. The story tells about five men and a monkey who were shipwrecked on an island. * They spent the first night gathering coconuts. During the night, one man woke up and decided to take * his share of the coconuts. He divided them into five piles. One coconut was left over so he gave it to * the monkey, then hid his share and went back to sleep. * Soon a second man woke up and did the same thing. After dividing the coconuts into five piles, * one coconut was left over which he gave to the monkey. He then hid his share and went back to bed. * The third, fourth, and fifth man followed exactly the same procedure. The next morning, after they * all woke up, they divided the remaining coconuts into five equal shares. This time no coconuts were * left over. * An obvious question is “how many coconuts did they originally gather?” There are an infinite * number of answers, but the lowest of these is 3,121. But that’s not our problem here. * Suppose we turn the problem around. If we know the number of coconuts that were gathered, what * is the maximum number of persons (and one monkey) that could have been shipwrecked if the same * procedure could occur? * Input * The input will consist of a sequence of integers, each representing the number of coconuts gathered by * a group of persons (and a monkey) that were shipwrecked. The sequence will be followed by a negative * number. * Output * For each number of coconuts, determine the largest number of persons who could have participated in * the procedure described above. Display the results similar to the manner shown below, in the Sample * Output. There may be no solution for some of the input cases; if so, state that observation. * Sample Input * 25 * 30 * 3121 * -1 * Sample Output * 25 coconuts, 3 people and 1 monkey * 30 coconuts, no solution * 3121 coconuts, 5 people and 1 monkey */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=557 import java.util.Scanner; public class CoconutsRevisited { public static void main(String[] args) { Scanner input = new Scanner(System.in); int i, rez, j; boolean isValid; while (true) { isValid = false; int num = input.nextInt(); if (num == -1) { break; } for (i = (int) (Math.sqrt(num) + 1); i > 1; i--) { rez = num; for (j = 0; j < i && rez % i == 1; j++) { rez = rez - rez / i - 1; } if (rez % i == 0 && i == j) { isValid = true; break; } } if (isValid) { System.out.println(num + " coconuts, " + i + " people and 1 monkey"); } else { System.out.println(num + " coconuts, no solution"); } } } } ================================================ FILE: uva/DigitCounting.java ================================================ /** * Trung is bored with his mathematics homeworks. He takes a piece of chalk and starts writing a sequence * of consecutive integers starting with 1 to N (1 < N < 10000). After that, he counts the number of * times each digit (0 to 9) appears in the sequence. For example, with N = 13, the sequence is: * 12345678910111213 * In this sequence, 0 appears once, 1 appears 6 times, 2 appears 2 times, 3 appears 3 times, and each * digit from 4 to 9 appears once. After playing for a while, Trung gets bored again. He now wants to * write a program to do this for him. Your task is to help him with writing this program. * Input * The input file consists of several data sets. The first line of the input file contains the number of data * sets which is a positive integer and is not bigger than 20. The following lines describe the data sets. * For each test case, there is one single line containing the number N. * Output * For each test case, write sequentially in one line the number of digit 0, 1, . . . 9 separated by a space. * Sample Input * 2 * 3 * 13 * Sample Output * 0 1 1 1 0 0 0 0 0 0 * 1 6 2 2 1 1 1 1 1 1 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3666 import static java.lang.Integer.parseInt; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; public class DigitCounting { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { int[] numbers = new int[10]; int number = input.nextInt(); for (int i = number; i > 0; i--) { int j = i; while (j != 0) { numbers[j % 10]++; j = j / 10; } } for (int i = 0; i < 10; i++) { if (i != 0) { System.out.print(" "); } System.out.print(numbers[i]); } System.out.println(); numberOfTestCases--; } } } ================================================ FILE: uva/FactorialFrequenices.java ================================================ /** * In an attempt to bolster her sagging palm-reading business, Madam Phoenix has decided to offer * several numerological treats to her customers. She has been able to convince them that the frequency * of occurrence of the digits in the decimal representation of factorials bear witness to their futures. * Unlike palm-reading, however, she can’t just conjure up these frequencies, so she has employed you to * determine these values. * (Recall that the definition of n! (that is, n factorial) is just 1 × 2 × 3 × · · · × n. As she expects to use * either the day of the week, the day of the month, or the day of the year as the value of n, you must be * able to determine the number of occurrences of each decimal digit in numbers as large as 366 factorial * (366!), which has 781 digits. * Madam Phoenix will be forever (or longer) in your debt; she might even give you a trip if you do * your job well! * Input * The input data for the program is simply a list of integers for which the digit counts are desired. All * of these input values will be less than or equal to 366 and greater than 0, except for the last integer, * which will be zero. Don’t bother to process this zero value; just stop your program at that point. * Output * The output format isn’t too critical, but you should make your program produce results that look * similar to those shown below. * Sample Input * 3 * 8 * 100 * 0 * Sample Output * 3! -- * (0) 0 (1) 0 (2) 0 (3) 0 (4) 0 * (5) 0 (6) 1 (7) 0 (8) 0 (9) 0 * 8! -- * (0) 2 (1) 0 (2) 1 (3) 1 (4) 1 * (5) 0 (6) 0 (7) 0 (8) 0 (9) 0 * 100! -- * (0) 30 (1) 15 (2) 19 (3) 10 (4) 10 * (5) 14 (6) 19 (7) 7 (8) 14 (9) 20 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=260 import java.math.BigInteger; import java.util.Scanner; public class FactorialFrequenices { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); while (number != 0) { BigInteger product = BigInteger.ONE; for (int i = 2; i < number + 1; i++) { product = product.multiply(BigInteger.valueOf(i)); } int[] digitCounter = new int[10]; BigInteger productValue = product; while (!productValue.equals(BigInteger.ZERO)) { digitCounter[Integer.valueOf(productValue.mod(BigInteger.TEN) .toString())]++; productValue = productValue.divide(BigInteger.TEN); } formatOutput(number, digitCounter); number = input.nextInt(); } } private static void formatOutput(int number, int[] digits) { System.out.println(number + "! --"); for (int i = 0; i < 10; i++) { if (i != 0 || i != 9 || i != 4) System.out.printf(" "); System.out.printf("(%d)%5d", i, digits[i]); if (i == 4 || i == 9) System.out.printf("\n"); } } } ================================================ FILE: uva/FiveHundredFactorial.java ================================================ /** * In these days you can more and more often happen to see programs which perform some useful calculations * being executed rather then trivial screen savers. Some of them check the system message queue * and in case of finding it empty (for examples somebody is editing a file and stays idle for some time) * execute its own algorithm. * As an examples we can give programs which calculate primary numbers. * One can also imagine a program which calculates a factorial of given numbers. In this case it is not * the time complexity of order O(n) which makes troubles, but the memory requirements. Considering * the fact that 500! gives 1135-digit number. No standard, neither integer nor floating, data type is * applicable here. * Your task is to write a programs which calculates a factorial of a given number. * Input * Any number of lines, each containing value n for which you should provide value of n! * Output * 2 lines for each input case. First should contain value n followed by character ‘!’. The second should * contain calculated value n!. * Assumptions: * • Value of a number n which factorial should be calculated of does not exceed 1000 (although 500! * is the name of the problem, 500 is a small limit). * • Mind that visually big number of case 4 is broken after 80 characters, but this is not the case in * the real output file. * Sample Input * 10 * 30 * 50 * 100 * Sample Output * 10! * 3628800 * 30! * 265252859812191058636308480000000 * 50! * 30414093201713378043612608166064768844377641568960512000000000000 * 100! * 93326215443944152681699238856266700490715968264381621468592963895217599993229915 * 608941463976156518286253697920827223758251185210916864000000000000000000000000 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=564 import java.math.BigInteger; import java.util.Scanner; public class FiveHundredFactorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { int number = input.nextInt(); BigInteger product = BigInteger.ONE; for (int i = 2; i < number + 1; i++) { product = product.multiply(BigInteger.valueOf(i)); } System.out.println(number + "!\n" + product); } } } ================================================ FILE: uva/Friends.java ================================================ // There is a town with N citizens. It is known that some pairs of people are friends. According to the // famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends // and B and C are friends then A and C are friends, too. // Your task is to count how many people there are in the largest group of friends. // Input // Input consists of several datasets. The first line of the input consists of a line with the number of test // cases to follow. // The first line of each dataset contains tho numbers N and M, where N is the number of town’s // citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known // to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N, // A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs // Output // The output for each test case should contain (on a line by itself) one number denoting how many people // there are in the largest group of friends on a line by itself. // Sample Input // 2 // 3 2 // 1 2 // 2 3 // 10 12 // 1 2 // 3 1 // 3 4 // 5 4 // 3 5 // 4 6 // 5 2 // 2 1 // 7 1 // 1 2 // 9 10 // 8 9 // Sample Output // 3 // 7 import java.io.*; import java.util.*; /** * Created by kdn251 on 2/15/17. */ public class Friends { //initialize globals to track each individual person and their relationships public static int[] people = new int[30001]; public static int[] relationships = new int[50001]; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); //store number of test cases int testCases = Integer.parseInt(line); for(int i = 0; i < testCases; i++) { //determine number of people and pairs of people (N and M) String[] info = br.readLine().split(" "); int numberOfPeople = Integer.parseInt(info[0]); int numberOfRelationship = Integer.parseInt(info[1]); startUnion(numberOfPeople, people, relationships); //iterate through all relationships for(int j = 0; j < numberOfRelationship ; j++) { //split current line to determine person and friend String[] currentLine = br.readLine().split(" "); int person = Integer.parseInt(currentLine[0]); int friend = Integer.parseInt(currentLine[1]); union(person, friend); } //initialize maxGroup to one because each group has one person initially int maxGroup = 1; //iterate through relationships to find the largest group for(int j = 0; j <= numberOfPeople; j++) { //update max as needed maxGroup = relationships[j] > maxGroup ? relationships[j] : maxGroup; } //print result System.out.println(maxGroup); } } public static void startUnion(int numberOfPeople, int[] people, int[] relationships) { for(int i = 0; i <= numberOfPeople; i++) { //initialize each individual person people[i] = i; //each person initially has a group of one (themselves) relationships[i] = 1; } } public static void union(int person, int friend) { //find parents in tree person = find(person); friend = find(friend); if(person != friend) { //add connection between person and friend join(person, friend); } } public static int find(int person) { //traverse parents of tree if possible if(people[person] != person) { people[person] = find(people[person]); } return people[person]; } public static void join(int person, int friend) { //find larger group of the two and make sure both person and friend point to it if(relationships[person] > relationships[friend]) { relationships[person] += relationships[friend]; people[friend] = person; } else { relationships[friend] += relationships[person]; people[person] = friend; } } } //source: https://github.com/morris821028/UVa/blob/master/volume106/10608%20-%20Friends.cpp#L27 ================================================ FILE: uva/GoldbachConjecture.java ================================================ /** * In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in * which he made the following conjecture: * Every number greater than 2 can be written as the sum of three prime numbers. * Goldbach was considering 1 as a primer number, a convention that is no longer followed. Later on, * Euler re-expressed the conjecture as: * Every even number greater than or equal to 4 can be expressed as the sum of two prime * numbers. * For example: * • 8 = 3 + 5. Both 3 and 5 are odd prime numbers. * • 20 = 3 + 17 = 7 + 13. * • 42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23. * Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but * it is too long to write it on the margin of this page.) * Anyway, your task is now to verify Goldbach’s conjecture as expressed by Euler for all even numbers * less than a million. * Input * The input file will contain one or more test cases. * Each test case consists of one even integer n with 6 ≤ n < 1000000. * Input will be terminated by a value of 0 for n. * Output * For each test case, print one line of the form n = a + b, where a and b are odd primes. Numbers and * operators should be separated by exactly one blank like in the sample output below. If there is more * than one pair of odd primes adding up to n, choose the pair where the difference b − a is maximized. * If there is no such pair, print a line saying ‘Goldbach's conjecture is wrong.’ * Sample Input * 8 * 20 * 42 * 0 * Sample Output * 8 = 3 + 5 * 20 = 3 + 17 * 42 = 5 + 37 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=484 import java.util.Scanner; public class GoldbachConjecture { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean[] isPrime = sieveOfEratosthenes(1000000); int number = input.nextInt(); while (number != 0) { boolean found = false; for (int i = 3; i < number && !found; i++) { if (isPrime[i]) { int currentPrime = i; int j = number - currentPrime; if (isPrime[j]) { System.out.println(number + " = " + currentPrime + " + " + j); found = true; } } } if (!found) { System.out.println("Goldbach's conjecture is wrong."); } number = input.nextInt(); } } private static boolean[] sieveOfEratosthenes(int number) { boolean[] isPrime = new boolean[number + 1]; for (int i = 2; i < number + 1; i++) { isPrime[i] = true; } for (int factor = 2; factor * factor <= number; factor++) { if (isPrime[factor]) { for (int j = factor; factor * j <= number; j++) { isPrime[factor * j] = false; } } } return isPrime; } } ================================================ FILE: uva/GoogleIsFeelingLucky.java ================================================ // Google is one of the most famous Internet search engines which hosts and develops a number of Internetbased // services and products. On its search engine website, an interesting button ‘I’m feeling lucky’ // attracts our eyes. This feature could allow the user skip the search result page and goes directly to the // first ranked page. Amazing! It saves a lot of time. // The question is, when one types some keywords and presses ‘I’m feeling lucky’ button, which web // page will appear? Google does a lot and comes up with excellent approaches to deal with it. In this // simplified problem, let us just consider that Google assigns every web page an integer-valued relevance. // The most related page will be chosen. If there is a tie, all the pages with the highest relevance are // possible to be chosen. // Your task is simple, given 10 web pages and their relevance. Just pick out all the possible candidates // which will be served to the user when ‘I’m feeling lucky’. // Input // The input contains multiple test cases. The number of test cases T is in the first line of the input file. // For each test case, there are 10 lines, describing the web page and the relevance. Each line contains // a character string without any blank characters denoting the URL of this web page and an integer // Vi denoting the relevance of this web page. The length of the URL is between 1 and 100 inclusively. // (1 ≤ Vi ≤ 100) // Output // For each test case, output several lines which are the URLs of the web pages which are possible to be // chosen. The order of the URLs is the same as the input. Please look at the sample output for further // information of output format. // Sample Input // 2 // www.youtube.com 1 // www.google.com 2 // www.google.com.hk 3 // www.alibaba.com 10 // www.taobao.com 5 // www.bad.com 10 // www.good.com 7 // www.fudan.edu.cn 8 // www.university.edu.cn 9 // acm.university.edu.cn 10 // www.youtube.com 1 // www.google.com 2 // www.google.com.hk 3 // www.alibaba.com 11 // www.taobao.com 5 // www.bad.com 10 // www.good.com 7 // www.fudan.edu.cn 8 // acm.university.edu.cn 9 // acm.university.edu.cn 10 // Sample Output // Case #1: // www.alibaba.com // www.bad.com // acm.university.edu.cn // Case #2: // www.alibaba.com /** * Created by kdn251 on 1/30/17. */ import java.util.*; public class GoogleIsFeelingLucky { public static void main(String args[]) { HashMap> map = new HashMap>(); Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); int max = Integer.MIN_VALUE; int caseCount = 1; for(int i = 0; i < testCases * 10; i++) { String website = sc.next(); int relevance = sc.nextInt(); if(i % 10 == 0 && i != 0) { List allCandidates = map.get(max); System.out.println("Case #" + caseCount + ":"); caseCount++; for(String s : allCandidates) { System.out.println(s); } map = new HashMap>(); max = Integer.MIN_VALUE; } if(map.containsKey(relevance)) { map.get(relevance).add(website); } if(!map.containsKey(relevance)) { List list = new ArrayList(); map.put(relevance, list); map.get(relevance).add(website); } if(relevance > max) { max = relevance; } } System.out.println("Case #" + caseCount + ":"); for(String s : map.get(max)) { System.out.println(s); } } } ================================================ FILE: uva/HashmatWarriors.java ================================================ /** * Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to * fight against his opponents. Before Fighting he just calculates one thing, the difference between his * soldier number and the opponent’s soldier number. From this difference he decides whether to fight or * not. Hashmat’s soldier number is never greater than his opponent. * Input * The input contains two numbers in every line. These two numbers in each line denotes the number * soldiers in Hashmat’s army and his opponent’s army or vice versa. The input numbers are not greater * than 232. Input is terminated by ‘End of File’. * Output * For each line of input, print the difference of number of soldiers between Hashmat’s army and his * opponent’s army. Each output should be in seperate line. * Sample Input * 10 12 * 10 14 * 100 200 * Sample Output * 2 * 4 * 100 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=996 import java.util.Scanner; public class HashmatWarriors { public static void main(String[] args) { Scanner input = new Scanner(System.in); String nextLine = input.nextLine(); while (!"".equals(nextLine)) { String[] nums = nextLine.split(" "); long firstNum = Long.valueOf(nums[0]); long secondNum = Long.valueOf(nums[1]); System.out.println(Math.abs(secondNum - firstNum)); nextLine = input.nextLine(); } } } ================================================ FILE: uva/HighPrecisionNumber.java ================================================ /** * A number with 30 decimal digits of precision can be represented by a structure type as shown in the * examples below. It includes a 30-element integer array (digits), a single integer (decpt) to represent * the position of the decimal point and an integer (or character) to represent the sign (+/-). * Your task is to write a program to calculate the sum of high-precision numbers. * Input * The first line contains a positive integer n (1 ≤ n ≤ 100) indicating the number of groups of highprecision * numbers (maximum 30 significant digits). Each group includes high-precision numbers (one * number in a line) and a line with only 0 indicating the end of each group. A group can contain 100 * numbers at most. * Output * For each group, print out the sum of high-precision numbers (one value in a line). All zeros after the * decimal point located behind the last non-zero digit must be discarded * * Sample Input * 4 * 4.12345678900000000005 * -0.00000000012 * 0 * -1300.1 * 1300.123456789 * 0.0000000012345678912345 * 0 * 1500.61345975 * -202.004285 * -8.60917475 * 0 * -218.302869584 * 200.0000123456789 * 0 * * Sample Output * 4.12345678888000000005 * 0.0234567902345678912345 * 1290 * -18.3028572383211 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2921 import java.math.BigDecimal; import java.util.Scanner; public class HighPrecisionNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfGroups = input.nextInt(); while (numberOfGroups != 0) { BigDecimal sum = BigDecimal.ZERO; BigDecimal number = input.nextBigDecimal(); while (!number.equals(BigDecimal.ZERO)) { sum = sum.add(number); number = input.nextBigDecimal(); } System.out.println(sum.toPlainString().replaceFirst( "\\.0*$|(\\.\\d*?)0+$", "$1")); numberOfGroups--; } } } ================================================ FILE: uva/HighSchoolPhysics.java ================================================ /** * A particle has initial velocity and acceleration. If its velocity after certain time is v then what will its * displacement be in twice of that time? * Input * The input will contain two integers in each line. Each line makes one set of input. These two integers * denote the value of v (−100 ≤ v ≤ 100) and t (0 ≤ t ≤ 200) (t means at the time the particle gains * that velocity) * Output * For each line of input print a single integer in one line denoting the displacement in double of that time. * Sample Input * 0 0 * 5 12 * Sample Output * 0 * 120 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1012 import java.util.Scanner; public class HighSchoolPhysics { public static void main(String[] args) { Scanner input = new Scanner(System.in); String line = input.nextLine(); while (!"".equals(line)) { String[] numbers = line.split(" "); int v = Integer.valueOf(numbers[0]); int t = Integer.valueOf(numbers[1]) * 2; System.out.println(v * t); line = input.nextLine(); } } } ================================================ FILE: uva/ICanGuessTheDataStructure.java ================================================ // There is a bag-like data structure, supporting two operations: // 1 x Throw an element x into the bag. // 2 Take out an element from the bag. // Given a sequence of operations with return values, you’re going to guess the data structure. It is // a stack (Last-In, First-Out), a queue (First-In, First-Out), a priority-queue (Always take out larger // elements first) or something else that you can hardly imagine! // Input: // There are several test cases. Each test case begins with a line containing a single integer n (1 ≤ n ≤ // 1000). Each of the next n lines is either a type-1 command, or an integer 2 followed by an integer x. // That means after executing a type-2 command, we get an element x without error. The value of x // is always a positive integer not larger than 100. The input is terminated by end-of-file (EOF). // Output: // For each test case, output one of the following: // stack It’s definitely a stack. // queue It’s definitely a queue. // priority queue It’s definitely a priority queue. // impossible It can’t be a stack, a queue or a priority queue. // not sure It can be more than one of the three data structures mentioned // above. // Sample Input // 6 // 1 1 // 1 2 // 1 3 // 2 1 // 2 2 // 2 3 // 6 // 1 1 // 1 2 // 1 3 // 2 3 // 2 2 // 2 1 // 2 // 1 1 // 2 2 // 4 // 1 2 // 1 1 // 2 1 // 2 2 // 7 // 1 2 // 1 5 // 1 1 // 1 3 // 2 5 // 1 4 // 2 4 // Sample Output // queue // not sure // impossible // stack // priority queue /** * Created by kdn251 on 2/10/17. */ import java.util.*; import java.io.*; public class ICanGuessTheDataStructure { public static void main(String args[]) throws Exception { //initialize data structures Stack stack = new Stack(); Queue queue = new LinkedList(); //initialize max priority queue PriorityQueue priorityQueue = new PriorityQueue(Collections.reverseOrder()); //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate through all test cases while ((line = br.readLine()) != null) { //initialize removals for each data structure int stackRemovals = 0; int queueRemovals = 0; int priorityQueueRemovals = 0; int totalRemovals = 0; //get number of test cases int numberOfCases = Integer.parseInt(line); //clear contents of data structures queue.clear(); priorityQueue.clear(); stack.clear(); //iterate over all test cases for (int i = 0; i < numberOfCases; i++) { String[] currentLineSplit = br.readLine().split(" "); int command = Integer.parseInt(currentLineSplit[0]); int number = Integer.parseInt(currentLineSplit[1]); //if command is 1, push number into all data structures if (command == 1) { stack.push(number); queue.add(number); priorityQueue.add(number); } else { //check which data structure to remove from and increment its removal count if (!stack.isEmpty() && stack.peek() == number && stackRemovals == totalRemovals) { stackRemovals++; stack.pop(); } if (!queue.isEmpty() && queue.peek() == number && queueRemovals == totalRemovals) { queueRemovals++; queue.remove(); } if (!priorityQueue.isEmpty() && priorityQueue.peek() == number && priorityQueueRemovals == totalRemovals) { priorityQueueRemovals++; priorityQueue.remove(); } totalRemovals++; } } //check all removal counts for each data structure vs. total removal count and print the appropriate data structure if ((stackRemovals == totalRemovals && queueRemovals == totalRemovals) || (stackRemovals == totalRemovals && stackRemovals == priorityQueueRemovals) || (queueRemovals == totalRemovals && priorityQueueRemovals == totalRemovals)) { System.out.println("not sure"); } else if (stackRemovals == totalRemovals) { System.out.println("stack"); } else if (queueRemovals == totalRemovals) { System.out.println("queue"); } else if (priorityQueueRemovals == totalRemovals) { System.out.println("priority queue"); } else { System.out.println("impossible"); } } } } ================================================ FILE: uva/IntegerInquiry.java ================================================ /** * One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of * powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers. * “This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.” * (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky * apartments on Third Street.) * Input * The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. * Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no * VeryLongInteger will be negative). * The final input line will contain a single zero on a line by itself. * Output * Your program should output the sum of the VeryLongIntegers given in the input. * Sample Input * 123456789012345678901234567890 * 123456789012345678901234567890 * 123456789012345678901234567890 * 0 * Sample Output * 370370367037037036703703703670 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=365 import java.math.BigInteger; import java.util.Scanner; public class IntegerInquiry { public static void main(String[] args) { Scanner input = new Scanner(System.in); BigInteger sum = BigInteger.ZERO; while (true) { BigInteger number = input.nextBigInteger(); if (number.equals(BigInteger.ZERO)) { break; } sum = sum.add(number); } System.out.println(sum); } } ================================================ FILE: uva/JollyJumpers.java ================================================ /** * A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between * successive elements take on all the values 1 through n − 1. For instance, * 1 4 2 3 * is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies * that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether * or not each of a number of sequences is a jolly jumper. * Input * Each line of input contains an integer n ≤ 3000 followed by n integers representing the sequence. * Output * For each line of input, generate a line of output saying ‘Jolly’ or ‘Not jolly’. * Sample Input * 4 1 4 2 3 * 5 1 4 2 -1 6 * Sample Output * Jolly * Not jolly */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=979 import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class JollyJumpers { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { Set numbersAlreadyAdded = new HashSet(); int numberOfElements = input.nextInt(); int[] numbers = new int[numberOfElements]; for (int i = 0; i < numberOfElements; i++) { numbers[i] = input.nextInt(); } for (int i = 0; i < numberOfElements - 1; i++) { int difference = Math.abs(numbers[i] - numbers[i + 1]); if (difference > 0 && difference < numberOfElements) { numbersAlreadyAdded.add(difference); } } if (numbersAlreadyAdded.size() == (numberOfElements - 1)) { System.out.println("Jolly"); } else { System.out.println("Not jolly"); } } } } ================================================ FILE: uva/LargestPrimeDivisor.java ================================================ /** * All integer numbers are divisible by primes. If a number is divisible by more than one prime number, * then it obviously has a largest prime divisor. The numbers which do not fall in this category do not * have a largest prime divisor. Given a number N your job is to write a program that finds its largest * prime divisor. An integer number n is divisible by another integer number m if there is an integer t * such that mt = n. * Input * The input file contains at most 450 sets of inputs. Each line contains a decimal integer N. N does * not have more than 14 digits. Input is terminated by a line containing a single zero. So no other line * except the last line contains a zero in the input. This line need not be processed. * Output * For each line of the input produce one line of output. This line contains an integer LPD, which is the * largest prime divisor of the input number N. If the input number is not divisible by more than one * prime number output a ‘-1’. * Sample Input * 2 * 6 * 100 * 0 * Sample Output * -1 * 3 * 5 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2461 import java.util.Scanner; public class LargestPrimeDivisor { public static void main(String[] args) { Scanner input = new Scanner(System.in); long number = input.nextLong(); while (number != 0) { number = (long) (Math.abs(number)); long largestPrimeDivisor = -1; int numberOfPrimeDivisors = 0; int sqrtOfNumber = (int) (Math.sqrt(number)); for (int i = 2; i <= sqrtOfNumber; i++) { if (number % i == 0) { numberOfPrimeDivisors++; largestPrimeDivisor = i; while (number % i == 0) { number = number / i; } } } if (largestPrimeDivisor != -1 && number != 1) { System.out.println(number); } else if (numberOfPrimeDivisors <= 1) { System.out.println(-1); } else { System.out.println(largestPrimeDivisor); } number = input.nextLong(); } } } ================================================ FILE: uva/LightMoreLight.java ================================================ /** * There is man named ”mabu” for switching on-off light in our University. He switches on-off the lights * in a corridor. Every bulb has its own toggle switch. That is, if it is pressed then the bulb turns on. * Another press will turn it off. To save power consumption (or may be he is mad or something else) * he does a peculiar thing. If in a corridor there is n bulbs, he walks along the corridor back and forth * n times and in i-th walk he toggles only the switches whose serial is divisable by i. He does not press * any switch when coming back to his initial position. A i-th walk is defined as going down the corridor * (while doing the peculiar thing) and coming back again. Now you have to determine what is the final * condition of the last bulb. Is it on or off? * Input * The input will be an integer indicating the n’th bulb in a corridor. Which is less then or equals 232 −1. * A zero indicates the end of input. You should not process this input. * Output * Output ‘yes’ if the light is on otherwise ‘no’, in a single line. * Sample Input * 3 * 6241 * 8191 * 0 * Sample Output * no * yes * no */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=1051 import java.util.Scanner; public class LightMoreLight { public static void main(String[] args) { Scanner input = new Scanner(System.in); long number = input.nextLong(); while (number != 0) { if (isAPerfectSquare(number)) { System.out.println("yes"); } else { System.out.println("no"); } number = input.nextLong(); } } private static boolean isAPerfectSquare(long number) { long squareRoot = (long) Math.sqrt(number); return squareRoot * squareRoot == number; } } ================================================ FILE: uva/MischievousChildren.java ================================================ /** * Adam’s parents put up a sign that says “CONGRATULATIONS”. The sign is so big that exactly one * letter fits on each panel. Some of Adam’s younger cousins got bored during the reception and decided * to rearrange the panels. How many unique ways can the panels be arranged (counting the original * arrangement)? * Input * The first line of input is a single non-negative integer. It indicates the number of data sets to follow. * Its value will be less than 30001. * Each data set consists of a single word, in all capital letters. * Each word will have at most 20 letters. There will be no spaces or other punctuation. * The number of arrangements will always be able to fit into an unsigned long int. Note that 12! * is the largest factorial that can fit into an unsigned long int. * Output * For each word, output the number of unique ways that the letters can be rearranged (counting the * original arrangement). Use the format shown in Sample Output, below. * Sample Input * 3 * HAPPY * WEDDING * ADAM * Sample Output * Data set 1: 60 * Data set 2: 2520 * Data set 3: 12 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1279 import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class MischievousChildren { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfCases = input.nextInt(); int currentCase = 1; while (numberOfCases != 0) { String line = input.next(); int numberOfLetters = line.length(); Map letterCounter = new HashMap(); for (int i = 0; i < numberOfLetters; i++) { char c = line.charAt(i); if (letterCounter.containsKey(c)) { int previousOccurrences = letterCounter.get(c); letterCounter.replace(c, previousOccurrences + 1); } else { letterCounter.put(c, 1); } } String lineWithoutDuplicates = ""; for (int i = 0; i < numberOfLetters; i++) { char c = line.charAt(i); if (!lineWithoutDuplicates.contains(c + "")) { lineWithoutDuplicates = lineWithoutDuplicates + c; } } long nFactorial = computeFactorial(numberOfLetters); for (int i = 0; i < letterCounter.size(); i++) { char c = lineWithoutDuplicates.charAt(i); int numberOfOccurrences = letterCounter.get(c); if (numberOfOccurrences != 1) { long currentProduct = computeFactorial(numberOfOccurrences); nFactorial = nFactorial / currentProduct; } } System.out.println("Data set " + currentCase + ": " + nFactorial); currentCase++; numberOfCases--; } } private static long computeFactorial(int number) { long product = 1; for (int i = 2; i < number + 1; i++) { product = product * i; } return product; } } ================================================ FILE: uva/Modex.java ================================================ /** * Many well-known cryptographic operations require modular exponentiation. That is, given integers x, * y and n, compute x * y mod n. In this question, you are tasked to program an efficient way to execute * this calculation. * Input * The input consists of a line containing the number c of datasets, followed by c datasets, followed by a * line containing the number ‘0’. * Each dataset consists of a single line containing three positive integers, x, y, and n, separated by * blanks. You can assume that 1 < x, n < 2 * 15 = 32768, and 0 < y < 2 * 31 = 2147483648. * Output * The output consists of one line for each dataset. The i-th line contains a single positive integer z such * that * z = x * y mod n * for the numbers x, y, z given in the i-th input dataset. * Sample Input * 2 * 2 3 5 * 2 2147483647 13 * 0 * Sample Output * 3 * 11 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3671 import java.math.BigInteger; import java.util.Scanner; public class Modex { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger x = input.nextBigInteger(); BigInteger y = input.nextBigInteger(); BigInteger n = input.nextBigInteger(); BigInteger result = x.modPow(y, n); System.out.println(result); numberOfTestCases--; } } } ================================================ FILE: uva/MultipleOfSeventeen.java ================================================ /** * Theorem: If you drop the last digit d of an integer n (n ≥ 10), subtract 5d from the * remaining integer, then the difference is a multiple of 17 if and only if n is a multiple of 17. * For example, 34 is a multiple of 17, because 3-20=-17 is a multiple of 17; 201 is not a multiple of * 17, because 20-5=15 is not a multiple of 17. * Given a positive integer n, your task is to determine whether it is a multiple of 17. * Input * There will be at most 10 test cases, each containing a single line with an integer n (1 ≤ n ≤ 10100). * The input terminates with n = 0, which should not be processed. * Output * For each case, print 1 if the corresponding integer is a multiple of 17, print 0 otherwise. * Sample Input * 34 * 201 * 2098765413 * 1717171717171717171717171717171717171717171717171718 * 0 * Sample Output * 1 * 0 * 1 * 0 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=3001 import java.math.BigInteger; import java.util.Scanner; public class MultipleOfSeventeen { private static final BigInteger BIGINTEGER_FIVE = new BigInteger("5"); private static final BigInteger BIGINTEGER_SEVENTEEN = new BigInteger("17"); private static final BigInteger BIGINTEGER_ZERO = new BigInteger("0"); public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { BigInteger number = input.nextBigInteger(); if (number.equals(BIGINTEGER_ZERO)) { break; } BigInteger lastDigit = number.mod(BigInteger.TEN); number = number.divide(BigInteger.TEN); BigInteger product5D = lastDigit.multiply(BIGINTEGER_FIVE); BigInteger difference = number.subtract(product5D); if (difference.mod(BIGINTEGER_SEVENTEEN).equals(BIGINTEGER_ZERO)) { System.out.println("1"); } else { System.out.println("0"); } } } } ================================================ FILE: uva/Newspaper.java ================================================ /** * News agency pays money for articles according to some rules. Each character has its own value (some * characters may have value equals to zero). Author gets his payment as a sum of all character’s values * in the article. You have to determine the amount of money that news agency must pay to an author. * Input * The first line contains integer N (0 < N ≤ 5), it is a number of tests. Each test describes an integer * K (0 < K ≤ 100), the number of paid characters. On next K lines there are table of paid characters * and its values (character values are written in cents). If character can not be found in the table, then * its value is equal to zero. Next, there is integer M (0 < M ≤ 150000). Next M lines contain an article * itself. Each line can be up to 10000 characters length. Be aware of a large input size, the whole input * file is about 7MB. * Output * For each test print how much money publisher must pay for an article in format ‘x.yy$’. Where x is * a number of dollars without leading zeros, and yy number of cents with one leading zero if necessary. * Examples: ‘3.32$’, ‘13.07$’, ‘71.30$’, ‘0.09$’. * Sample Input * 1 * 7 * a 3 * W 10 * A 100 * , 10 * k 7 * . 3 * I 13 * 7 * ACM International Collegiate Programming Contest (abbreviated * as ACM-ICPC or just ICPC) is an annual multi-tiered competition * among the universities of the world. The ICPC challenges students * to set ever higher standards of excellence for themselves * through competition that rewards team work, problem analysis, * and rapid software development. * From Wikipedia. * Sample Output * 3.74$ */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2315 import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Newspaper { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { Map values = new HashMap(); int numberOfValuableCharacters = input.nextInt(); while (numberOfValuableCharacters != 0) { values.put(input.next(), input.nextInt()); numberOfValuableCharacters--; } int numberOfLines = input.nextInt(); input.nextLine(); double sum = 0; while (numberOfLines != 0) { String textAsString = input.nextLine(); for (int i = 0; i < textAsString.length(); i++) { String c = textAsString.charAt(i) + ""; if (values.containsKey(c)) { sum = sum + values.get(c); } } numberOfLines--; } sum = sum / 100; DecimalFormat formatter = new DecimalFormat("0.00"); String sumFormatted = formatter.format(sum); System.out.println(sumFormatted + "$"); numberOfTestCases--; } } } ================================================ FILE: uva/NumberTheoryForNewbies.java ================================================ /** * Given any positive integer, if we permute its digits, the difference between the number we get and the * given number will always be divisible by 9. * For example, if the given number is 123, we may rearrange the digits to get 321. The difference = * 321 - 123 = 198, which is a multiple of 9 (198 = 9 × 22). * We can prove this fact fairly easily, but since we are not having a maths contest, we instead try to * illustrate this fact with the help of a computer program. * Input * Each line of input gives a positive integer n (≤ 2000000000). You are to find two integers a and b * formed by rearranging the digits of n, such that a − b is maximum. a and b should NOT have leading * zeros. * Output * You should then show that a − b is a multiple of 9, by expressing it as ‘9 * k’, where k is an integer. * See the sample output for the correct output format. * Sample Input * 123 * 2468 * Sample Output * 321 - 123 = 198 = 9 * 22 * 8642 - 2468 = 6174 = 9 * 686 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2366 import java.util.Arrays; import java.util.Scanner; public class NumberTheoryForNewbies { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNextLong()) { String inputValue = input.nextLine(); StringBuilder minimal = new StringBuilder(); StringBuilder maximal = new StringBuilder(); char[] characters = inputValue.toCharArray(); int length = characters.length; Arrays.sort(characters); int index; for (index = 0; index < length; index++) { if (characters[index] != '0') { break; } } if (index != 0) { characters[0] = characters[index]; characters[index] = '0'; } for (int i = 0; i < length; i++) { minimal.append(characters[i]); } Arrays.sort(characters); for (int i = length - 1; i > -1; i--) { maximal.append(characters[i]); } long maximalNumber = Long.valueOf(maximal.toString()); long minimalNumber = Long.valueOf(minimal.toString()); long difference = maximalNumber - minimalNumber; System.out.println(maximal + " - " + minimal + " = " + difference + " = 9 * " + (difference / 9)); } } } ================================================ FILE: uva/NumberingRoads.java ================================================ /**In my country, streets dont have names, each of them are * just given a number as name. These numbers are supposed * to be unique but that is not always the case. The local * government allocates some integers to name the roads and * in many case the number of integers allocated is less that * the total number of roads. In that case to make road * names unique some single character suffixes are used. So * roads are named as 1, 2, 3, 1A, 2B, 3C, etc. Of course the * number of suffixes is also always limited to 26 (A, B, . . . , * Z). For example if there are 4 roads and 2 different integers * are allocated for naming then some possible assignments * of names can be: * 1, 2, 1A, 2B * 1, 2, 1A, 2C * 3, 4, 3A, 4A * 1, 2, 1B, 1C * Given the number of roads (R) and the numbers of * integers allocated for naming (N), your job is to determine * minimum how many different suffixes will be required (of * all possible namings) to name the streets assuming that * no two streets can have same names. * Input * The input file can contain up to 10002 lines of inputs. Each line contains two integers R and N * (0 < N, R < 10001). Here R is the total number of streets to be named and N denotes number integers * allocated for naming. * Output * For each line of input produce one line of output. This line contains the serial of output followed by * an integer D which denotes the minimum number of suffixes required to name the streets. If it is not * possible to name all the streets print ‘impossible’ instead (without the quotes). * Sample Input * 8 5 * 100 2 * 0 0 * Sample Output * Case 1: 1 * Case 2: impossible */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2823 import java.util.Scanner; public class NumberingRoads { public static void main(String[] args) { Scanner input = new Scanner(System.in); int caseNumber = 1; while (true) { int first = input.nextInt(); int second = input.nextInt(); if (first == 0 && second == 0) { break; } boolean found = false; for (int i = 0; i < 27 && !found; i++) { int sum = second + second * i; if (sum >= first) { System.out.print("Case " + caseNumber + ": " + i + "\n"); found = true; } } if (!found) { System.out.print("Case " + caseNumber + ": impossible\n"); } caseNumber = caseNumber + 1; } } } ================================================ FILE: uva/OpenSource.java ================================================ // At an open-source fair held at a major university, // leaders of open-source projects put sign-up // sheets on the wall, with the project name at the // top in capital letters for identification. // Students then signed up for projects using // their userids. A userid is a string of lower-case // letters and numbers starting with a letter. // The organizer then took all the sheets off the // wall and typed in the information. // Your job is to summarize the number of // students who have signed up for each project. // Some students were overly enthusiastic and put // their name down several times for the same // project. That’s okay, but they should only count // once. Students were asked to commit to a single // project, so any student who has signed up for more // than one project should not count for any project. // There are at most 10,000 students at the university, // and at most 100 projects were advertised. // Input // The input contains several test cases, each one ending with a line that starts with the digit 1. The last // test case is followed by a line starting with the digit 0. // Each test case consists of one or more project sheets. A project sheet consists of a line containing // the project name in capital letters, followed by the userids of students, one per line. // Output // For each test case, output a summary of each project sheet. The summary is one line with the name // of the project followed by the number of students who signed up. These lines should be printed in // decreasing order of number of signups. If two or more projects have the same number of signups, they // should be listed in alphabetical order. // Sample Input // UBQTS TXT // tthumb // LIVESPACE BLOGJAM // philton // aeinstein // YOUBOOK // j97lee // sswxyzy // j97lee // aeinstein // SKINUX // 1 // 0 // Sample Output // YOUBOOK 2 // LIVESPACE BLOGJAM 1 // UBQTS TXT 1 // SKINUX 0 import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.*; import static java.lang.Character.isUpperCase; /** * Created by kdn251 on 3/7/17. */ public class OpenSource { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while(!(line = br.readLine()).equals("0")) { HashMap projects = new HashMap(); HashMap students = new HashMap(); String project = line; projects.put(project, 0); while(!(line = br.readLine()).equals("1")) { if(isUpperCase(line.charAt(0))) { project = line; projects.put(project, 0); } else { if(students.containsKey(line)) { if(students.get(line).equals("")) { continue; } else { if(!students.get(line).equals(project)) { projects.put(students.get(line), projects.get(students.get(line)) - 1); students.put(line, ""); } } } else { projects.put(project, projects.get(project) + 1); students.put(line, project); } } } List pairs = new ArrayList(); int count = 0; for(String s : projects.keySet()) { pairs.add(new Pair(s, projects.get(s))); } Collections.sort(pairs,new Comparator() { public int compare(Pair o1, Pair o2) { if(-Integer.compare(o1.total, o2.total) == 0) { return o1.name.compareTo(o2.name); } return -Integer.compare(o1.total, o2.total); } }); for(Pair p : pairs) { System.out.println(p.name + " " + p.total); } } } } class Pair { String name; int total; Pair(String name, int total) { this.name = name; this.total = total; } } ================================================ FILE: uva/Parity.java ================================================ /** * We define the parity of an integer n as the sum of the bits in binary representation computed modulo * two. As an example, the number 21 = 101012 has three 1s in its binary representation so it has parity * 3(mod2), or 1. * In this problem you have to calculate the parity of an integer 1 ≤ I ≤ 2147483647. * Input * Each line of the input has an integer I and the end of the input is indicated by a line where I = 0 that * should not be processed. * Output * For each integer I in the inputt you should print a line ‘The parity of B is P (mod 2).’, where B * is the binary representation of I. * Sample Input * 1 * 2 * 10 * 21 * 0 * Sample Output * The parity of 1 is 1 (mod 2). * The parity of 10 is 1 (mod 2). * The parity of 1010 is 2 (mod 2). * The parity of 10101 is 3 (mod 2). */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1872 import java.util.Scanner; public class Parity { public static void main(String[] args) { while (true) { Scanner input = new Scanner(System.in); int number = input.nextInt(); if (number == 0) { break; } String binaryInString = convertToBinary(number); int count = 0; for (int i = 0; i < binaryInString.length(); i++) { if ("1".equals(binaryInString.charAt(i) + "")) { count++; } } System.out.println("The parity of " + binaryInString + " is " + count + " (mod 2)."); } } private static String convertToBinary(int number) { StringBuilder s = new StringBuilder(""); while (number != 0) { s = s.append(number % 2); number = number / 2; } return s.reverse().toString(); } } ================================================ FILE: uva/PeskyPalindromes.java ================================================ // A palindrome is a sequence of one or more characters that reads the same from the left as it does from // the right. For example, Z, TOT and MADAM are palindromes, but ADAM is not. // Your job, should you choose to accept it, is to write a program that reads a sequence of strings and // for each string determines the number of UNIQUE palindromes that are substrings. // Input // The input file consists of a number of strings (one per line), of at most 80 characters each, starting in // column 1. // Output // For each non-empty input line, the output consists of one line containing the message: // The string 'input string' contains nnnn palindromes. // where input string is replaced by the actual input string and nnnn is replaced by the number of // UNIQUE palindromes that are substrings. // Note: // See below the explanation of the sample below // • The 3 unique palindromes in ‘boy’ are ‘b’, ‘o’ and ‘y’. // • The 4 unique palindromes in ‘adam’ are ‘a’, ‘d’, ‘m’, and ‘ada’. // • The 5 unique palindromes in ‘madam’ are ‘m’, ‘a’, ‘d’, ‘ada’, and ‘madam’. // • The 3 unique palindromes in ‘tot’ are ‘t’, ‘o’ and ‘tot’. // Sample input // boy // adam // madam // tot // Sample output // The string 'boy' contains 3 palindromes. // The string 'adam' contains 4 palindromes. // The string 'madam' contains 5 palindromes. // The string 'tot' contains 3 palindromes. import java.util.*; public class PeskyPalindromes { public static void main(String args[]) { int x; Scanner sc = new Scanner(System.in); while(sc.hasNext()) { String currentString = sc.next(); List allSubstrings = generateSubstrings(currentString); int uniquePalindromes = findUniquePalindromes(allSubstrings); System.out.println("The string " + "'" + currentString + "'" + " contains " + uniquePalindromes + " palindromes."); } } public static List generateSubstrings(String s) { List allSubstrings = new ArrayList(); for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { String currentSubstring = s.substring(i, j); if(!allSubstrings.contains(currentSubstring)) { allSubstrings.add(currentSubstring); } } } return allSubstrings; } public static int findUniquePalindromes(List allSubstrings) { int totalUniquePalindromes = 0; for(String s : allSubstrings) { int left = 0; int right = s.length() - 1; boolean isPalindrome = true; while(left < right) { if(s.charAt(left) != s.charAt(right)) { isPalindrome = false; break; } left++; right--; } if(isPalindrome) { totalUniquePalindromes++; } } return totalUniquePalindromes; } } ================================================ FILE: uva/PrimeFactors.java ================================================ /** * The most relevant definition for this problem is 2a: An integer g > 1 is said to be prime if and only * if its only positive divisors are itself and one (otherwise it is said to be composite). For example, the * number 21 is composite; the number 23 is prime. Note that the decompositon of a positive number g * into its prime factors, i.e., * g = f1 × f2 × · · · × fn * is unique if we assert that fi > 1 for all i and fi ≤ fj for i < j. * One interesting class of prime numbers are the so-called Mersenne primes which are of the form * 2 * p − 1. Euler proved that 2 * 31 − 1 is prime in 1772 — all without the aid of a computer. * Input * The input will consist of a sequence of numbers. Each line of input will contain one number g in the * range −2 * 31 < g < 2 * 31, but different of -1 and 1. The end of input will be indicated by an input line * having a value of zero. * Output * For each line of input, your program should print a line of output consisting of the input number and * its prime factors. For an input number g > 0, g = f1 × f2 × · · · × fn, where each fi * is a prime number * greater than unity (with fi ≤ fj for i < j), the format of the output line should be * g = f1 x f2 x . . . x fn * When g < 0, if | g |= f1 × f2 × · · · × fn, the format of the output line should be * g = -1 x f1 x f2 x . . . x fn * Sample Input * -190 * -191 * -192 * -193 * -194 * 195 * 196 * 197 * 198 * 199 * 200 * 0 * Sample Output * -190 = -1 x 2 x 5 x 19 * -191 = -1 x 191 * -192 = -1 x 2 x 2 x 2 x 2 x 2 x 2 x 3 * -193 = -1 x 193 * -194 = -1 x 2 x 97 * 195 = 3 x 5 x 13 * 196 = 2 x 2 x 7 x 7 * 197 = 197 * 198 = 2 x 3 x 3 x 11 * 199 = 199 * 200 = 2 x 2 x 2 x 5 x 5 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=524 import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class PrimeFactors { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = input.nextInt(); boolean[] isPrime = generatePrimeNumbers(); while (number != 0) { boolean isNegative = false; if (number < 0) { isNegative = true; number = Math.abs(number); } int originalNumber = number; formatOutput(originalNumber, sieveOfEratosthenes(isPrime, originalNumber), isNegative); number = input.nextInt(); } } public static List sieveOfEratosthenes(boolean[] isPrime, int number) { List primeFactors = new ArrayList(); int squareRootOfOriginalNumber = (int) Math.sqrt(number); for (int i = 2; i <= squareRootOfOriginalNumber; i++) { if (isPrime[i]) { while (number % i == 0) { primeFactors.add(i); number = number / i; } } } if (number != 1) { primeFactors.add(number); } return primeFactors; } static void formatOutput(int number, List primeFactors, boolean isNegative) { if (isNegative) { number *= -1; } StringBuilder output = new StringBuilder(number + " = "); int numberOfPrimeFactors = primeFactors.size(); if (numberOfPrimeFactors == 1) { if (isNegative) { output.append("-1 x " + (number * (-1))); } else { output.append(number); } } else { Collections.sort(primeFactors); if (isNegative) { output.append("-1 x "); } for (int i = 0; i < numberOfPrimeFactors - 1; i++) { output.append(primeFactors.get(i) + " x "); } output.append(primeFactors.get(numberOfPrimeFactors - 1)); } System.out.println(output); } static boolean[] generatePrimeNumbers() { int number = (int) Math.sqrt(Integer.MAX_VALUE); boolean[] isPrime = new boolean[number + 1]; for (int i = 2; i < number + 1; i++) { isPrime[i] = true; } for (int factor = 2; factor * factor < number + 1; factor++) { if (isPrime[factor]) { for (int j = factor; j * factor < number + 1; j++) { isPrime[j * factor] = false; } } } return isPrime; } } ================================================ FILE: uva/PseudoPrimeNumbers.java ================================================ /** * Fermat’s theorem states that for any * prime number p and for any integer a > 1, * a * p == a (mod p). That is, if we raise a to * the pth power and divide by p, the remainder * is a. Some (but not very many) nonprime * values of p, known as base-a pseudoprimes, * have this property for some a. * (And some, known as Carmichael Numbers, * are base-a pseudoprimes for all a.) * Given 2 < p ≤ 1, 000, 000, 000 and 1 < * a < p, determine whether or not p is a * base-a pseudoprime. * Input * Input contains several test cases followed by a line containing ‘0 0’. Each test case consists of a line * containing p and a. * Output * For each test case, output ‘yes’ if p is a base-a pseudoprime; otherwise output ‘no’. * Sample Input * 3 2 * 10 3 * 341 2 * 341 3 * 1105 2 * 1105 3 * 0 0 * Sample Output * no * no * yes * no * yes * yes */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2262 import java.math.BigInteger; import java.util.Scanner; public class PseudoPrimeNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { int p = input.nextInt(); int a = input.nextInt(); if (a == 0 && p == 0) { break; } BigInteger pAsBigInteger = new BigInteger(p + ""); BigInteger aAsBigInteger = new BigInteger(a + ""); String answer = ""; if (!pAsBigInteger.isProbablePrime(10)) { BigInteger result = aAsBigInteger.modPow(pAsBigInteger, pAsBigInteger); if (result.equals(aAsBigInteger)) { answer = "yes"; } else { answer = "no"; } } else { answer = "no"; } System.out.println(answer); } } } ================================================ FILE: uva/SimplifyingFractions.java ================================================ /** * You are to write a program that reduces a fraction into its lowest terms. * Input * The first line of the input file gives the number of test cases N (≤ 20). Each of the following N lines * contains a fraction in the form of p/q (1 ≤ p, q ≤ 1030). * Output * For each test case, output the fraction after simplification. * Sample Input * 4 * 1 / 2 * 2 / 4 * 3 / 3 * 4 / 2 * Sample Output * 1 / 2 * 1 / 2 * 1 / 1 * 2 / 1 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1755 import java.math.BigInteger; import java.util.Scanner; public class SimplifyingFractions { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { String pAsString = input.next(); input.next(); String qAsString = input.next(); BigInteger p = new BigInteger(pAsString); BigInteger q = new BigInteger(qAsString); BigInteger greatestCommonDivisor = p.gcd(q); if (!greatestCommonDivisor.equals(BigInteger.ONE)) { p = p.divide(greatestCommonDivisor); q = q.divide(greatestCommonDivisor); } System.out.println(p + " / " + q); numberOfTestCases--; } } } ================================================ FILE: uva/SimplyEmirp.java ================================================ /** * An integer greater than 1 is called a prime number if its only positive divisors (factors) are 1 and itself. * Prime numbers have been studied over the years by a lot of mathematicians. Applications of prime * numbers arise in Cryptography and Coding Theory among others. * Have you tried reversing a prime? For most primes, you get a composite (43 becomes 34). An * Emirp (Prime spelt backwards) is a Prime that gives you a different Prime when its digits are reversed. * For example, 17 is Emirp because 17 as well as 71 are Prime. * In this problem, you have to decide whether a number N is Non-prime or Prime or Emirp. Assume * that 1 < N < 1000000. * Interestingly, Emirps are not new to NTU students. We have been boarding 199 and 179 buses for * quite a long time! * Input * Input consists of several lines specifying values for N. * Output * For each N given in the input, output should contain one of the following: * 1. ‘N is not prime.’, if N is not a Prime number. * 2. ‘N is prime.’, if N is Prime and N is not Emirp. * 3. ‘N is emirp.’, if N is Emirp. * Sample Input * 17 * 18 * 19 * 179 * 199 * Sample Output * 17 is emirp. * 18 is not prime. * 19 is prime. * 179 is emirp. * 199 is emirp. */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1176 import java.math.BigInteger; import java.util.Scanner; public class SimplyEmirp { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String inputGiven = input.next(); BigInteger number = new BigInteger(inputGiven); if (!number.isProbablePrime(10)) { System.out.println(number + " is not prime."); } else { String numberReversedAsString = new StringBuilder( number.toString()).reverse().toString(); BigInteger numberReversed = new BigInteger( numberReversedAsString); if (numberReversed.isProbablePrime(10) && numberReversed.compareTo(number) != 0) { System.out.println(number + " is emirp."); } else { System.out.println(number + " is prime."); } } } } } ================================================ FILE: uva/SkewBinary.java ================================================ /** * When a number is expressed in decimal, the k-th digit represents a multiple of 10k. (Digits are numbered * from right to left, where the least significant digit is number 0.) For example, * 8130710 = 8 × 104 + 1 × 103 + 3 × 102 + 0 × 101 + 7 × 100 = 80000 + 1000 + 300 + 0 + 7 = 81307. * When a number is expressed in binary, the k-th digit represents a multiple of 2 * k. For example, * 100112 = 1 × 2 * 4 + 0 × 2 * 3 + 0 × 2 * 2 + 1 × 2 * 1 + 1 × 2 * 0 = 16 + 0 + 0 + 2 + 1 = 19. * In skew binary, the k-th digit represents a multiple of 2 * k+1 − 1. The only possible digits are 0 * and 1, except that the least-significant nonzero digit can be a 2. For example, * 10120skew = 1×(25 −1)+ 0×(24 −1)+ 1×(23 −1)+ 2×(22 −1)+ 0×(21 −1) = 31+ 0+ 7+ 6+ 0 = 44. * The first 10 numbers in skew binary are 0, 1, 2, 10, 11, 12, 20, 100, 101, and 102. (Skew binary is * useful in some applications because it is possible to add 1 with at most one carry. However, this has * nothing to do with the current problem.) * Input * The input file contains one or more lines, each of which contains an integer n. If n = 0 it signals the * end of the input, and otherwise n is a nonnegative integer in skew binary. * Output * For each number, output the decimal equivalent. The decimal value of n will be at most 2 * 31 − 1 = * 2147483647. * Sample Input * 10120 * 200000000000000000000000000000 * 10 * 1000000000000000000000000000000 * 11 * 100 * 11111000001110000101101102000 * 0 * Sample Output * 44 * 2147483646 * 3 * 2147483647 * 4 * 7 * 1041110737 */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=516 import java.math.BigInteger; import java.util.Scanner; public class SkewBinary { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { BigInteger number = input.nextBigInteger(); if (number.equals(BigInteger.ZERO)) { break; } int length = (number + "").length(); BigInteger sum = BigInteger.ZERO; for (int i = 0; i < length; i++) { BigInteger mod10 = number.mod(BigInteger.TEN); BigInteger insideBrackets = BigInteger.valueOf((long) (Math .pow(2, i + 1) - 1)); sum = sum.add((mod10).multiply(insideBrackets)); number = number.divide(BigInteger.TEN); } System.out.println(sum); } } } ================================================ FILE: uva/SolveEquation.java ================================================ /** * Let us look at a boring mathematics problem. :-) We have three different * integers, x, y and z, which satisfy the following three relations: • x + y + * z = A • xyz = B • x 2 + y 2 + z 2 = C You are asked to write a program that * solves for x, y and z for given values of A, B and C. Input The first line of * the input file gives the number of test cases N (N < 20). Each of the * following N lines gives the values of A, B and C (1 ≤ A, B, C ≤ 10000). * Output For each test case, output the corresponding values of x, y and z. If * there are many possible answers, choose the one with the least value of x. If * there is a tie, output the one with the least value of y. If there is no * solution, output the line ‘No solution.’ instead. Sample Input 2 1 2 3 6 6 14 * Sample Output No solution. 1 2 3 */ // https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2612 import java.util.Scanner; public class SolveEquation { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { int A = input.nextInt(); int B = input.nextInt(); int C = input.nextInt(); boolean hasSolution = false; for (int x = -22; x <= 22 && !hasSolution; x++) { if (x * x <= C) { for (int y = -100; y <= 100 && !hasSolution; y++) { if (x != y && y * y <= C && (x * x + y * y <= C)) { int z = A - x - y; if ((z != y && z != x && x * x + y * y + z * z == C) && x * y * z == B) { hasSolution = true; System.out.println(x + " " + y + " " + z); } } } } } if (!hasSolution) { System.out.println("No solution."); } numberOfTestCases--; } } } ================================================ FILE: uva/SplittingNumbers.java ================================================ // We define the operation of splitting // a binary number n into two numbers // a(n), b(n) as follows. Let 0 ≤ i1 < i2 < // . . . < ik be the indices of the bits (with // the least significant bit having index 0) in // n that are 1. Then the indices of the bits // of a(n) that are 1 are i1, i3, i5, . . . and the // indices of the bits of b(n) that are 1 are // i2, i4, i6, . . . // For example, if n is 110110101 in binary // then, again in binary, we have a = // 010010001 and b = 100100100. // Input // Each test case consists of a single integer // n between 1 and 231 − 1 written in standard decimal (base 10) format on a single line. Input is // terminated by a line containing ‘0’ which should not be processed. // Output // The output for each test case consists of a single line, containing the integers a(n) and b(n) separated // by a single space. Both a(n) and b(n) should be written in decimal format. // Sample Input // 6 // 7 // 13 // 0 // Sample Output // 2 4 // 5 2 // 9 4 /** * Created by kdn251 on 2/10/17. */ import java.util.*; import java.io.*; public class SplittingNumbers { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while((line = br.readLine()) != null) { //read number int number = Integer.parseInt(line); //terminate if number is zero if(number == 0) break; //intialize variables int count = 0; int a = 0; int b = 0; while(number > 0) { //get lowest set bit int currentBit = number ^ (number & (number - 1)); //if count is even or a with current bit if(count % 2 == 0) { a |= currentBit; } //if count is odd or b with current bit else { b |= currentBit; } //increment count count++; //clear lowest set bit for next iteration number &= (number - 1); } //print a and b System.out.println(a + " " + b); } } } ================================================ FILE: uva/TheHugeOne.java ================================================ /** * Your girlfriend Marry has some problems with programming task teacher gave her. Since you have * the great programming skills it won’t be a problem for you to help her. And certainly you don’t want * Marry to have her time spent on this task because you were planning to go to the cinema with her this * weekend. If you accomplish this task Marry will be very grateful and will definitely go with you to the * cinema and maybe even more. So it’s up to you now * That’s the task she was given: * Number 0 ≤ M ≤ 101000 is given, and a set S of different numbers from the interval [1;12]. All * numbers in this set are integers. Number M is said to be wonderful if it is divisible by all numbers in * set S. Find out whether or not number M is wonderful. * Input * First line of input data contains number N (0 < N ≤ 2000). Then N tests follow each described on * two lines. First line of each test case contains number M. Second line contains the number of elements * in a set S followed by a space and the numbers in the set. Numbers of this set are separated by a space * character. * Output * Output one line for each test case: ‘M - Wonderful.’, if the number is wonderful or ‘M - Simple.’ * if it is not. Replace M character with the corresponding number. Refer output data for details. * Sample Input * 4 * 0 * 12 1 2 3 4 5 6 7 8 9 10 11 12 * 379749833583241 * 1 11 * 3909821048582988049 * 1 7 * 10 * 3 1 2 9 * Sample Output * 0 - Wonderful. * 379749833583241 - Wonderful. * 3909821048582988049 - Wonderful. * 10 - Simple. */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2319 import java.math.BigInteger; import java.util.Scanner; public class TheHugeOne { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger M = input.nextBigInteger(); input.nextLine(); String[] elementsLine = input.nextLine().split(" "); boolean found = false; for (int i = 1; i < elementsLine.length; i++) { BigInteger number = new BigInteger(elementsLine[i]); if (!M.mod(number).equals(BigInteger.ZERO)) { System.out.println(M + " - Simple."); found = true; break; } } if (!found) { System.out.println(M + " - Wonderful."); } numberOfTestCases--; } } } ================================================ FILE: uva/TheLastNonZeroDigit.java ================================================ /** * In this problem you will be given two decimal integer number N, M. You will have to find the last * non-zero digit of the P * N * M . This means no of permutations of N things taking M at a time. * Input * The input file contains several lines of input. Each line of the input file contains two integers N * (0 ≤ N ≤ 20000000), M (0 ≤ M ≤ N). Input is terminated by end-of-file. * Output * For each line of the input file you should output a single digit, which is the last non-zero digit of P * N * M . * For example, if P * N * M is 720 then the last non-zero digit is 2. So in this case your output should be 2. * Sample Input * 10 10 * 10 5 * 25 6 * Sample Output * 8 * 4 * 2 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1153 import java.util.Scanner; public class TheLastNonZeroDigit { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { long n = input.nextInt(); long m = input.nextInt(); long product = 1; for (long i = (n - m + 1); i < n + 1; i++) { product = product * i; while (product % 10 == 0) { product = product / 10; } product = product % (long) (Math.pow(10, 11)); } String number = product + ""; for (int i = number.length() - 1; i > -1; i--) { char c = number.charAt(i); if (c != '0') { System.out.println(c); break; } } } } } ================================================ FILE: uva/TheSettlersOfCatan.java ================================================ // Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge between node x and node y String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp ================================================ FILE: uva/VeryEasy.java ================================================ /** * Most of the times, the students of Computer Science & Engineering of BUET deal with bogus, tough and * very complex formulae. That is why, sometimes, even for a easy problem they think very hard and make * the problem much complex to solve. But, the team members of the team “BUET PESSIMISTIC” * are the only exceptions. Just like the opposite manner, they treat every hard problem as easy and so * cannot do well in any contest. Today, they try to solve a series but fail for treating it as hard. Let * them help. * Input * Just try to determine the answer for the following series * ∑ * N * i=1 * iAi * You are given the value of integers N and A (1 ≤ N ≤ 150, 0 ≤ A ≤ 15). * Output * For each line of the input, your correct program should output the integer value of the sum in separate * lines for each pair of values of N and A. * Sample Input * 3 3 * 4 4 * Sample Output * 102 * 1252 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1464 import java.math.BigInteger; import java.util.Scanner; public class VeryEasy { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { BigInteger sum = BigInteger.ZERO; int N = input.nextInt(); int A = input.nextInt(); BigInteger aAsBigInteger = BigInteger.valueOf(A); BigInteger product = BigInteger.ONE; for (int i = 1; i < N + 1; i++) { product = BigInteger.valueOf(i).multiply(aAsBigInteger.pow(i)); sum = sum.add(product); } System.out.println(sum); } } } ================================================ FILE: uva/VirtualFriends.java ================================================ // These days, you can do all sorts of things online. For example, you can use various websites to make // virtual friends. For some people, growing their social network (their friends, their friends’ friends, their // friends’ friends’ friends, and so on), has become an addictive hobby. Just as some people collect stamps, // other people collect virtual friends. // Your task is to observe the interactions on such a website and keep track of the size of each person’s // network. // Assume that every friendship is mutual. If Fred is Barney’s friend, then Barney is also Fred’s friend. // Input // The first line of input contains one integer specifying the number of test cases to follow. Each test case // begins with a line containing an integer F, the number of friendships formed, which is no more than // 100 000. Each of the following F lines contains the names of two people who have just become friends, // separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase). // Output // Whenever a friendship is formed, print a line containing one integer, the number of people in the social // network of the two people who have just become friends // Sample Input // 1 // 3 // Fred Barney // Barney Betty // Betty Wilma // Sample Output // 2 // 3 // 4 import java.io.*; import java.util.Arrays; import java.util.HashMap; /** * Created by kdn251 on 3/7/17. */ public class VirtualFriends { public static int[] people = new int[1000001]; public static int[] relationships = new int[1000001]; public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); while(cases-- > 0) { startUnion(people.length); HashMap map = new HashMap(); int friendships = Integer.parseInt(br.readLine()); int numberOfPeople = 0; for(int i = 0; i < friendships; i++) { String[] line = br.readLine().split("\\s+"); String x = line[0]; String y = line[1]; if (x.equals(y)) { System.out.println(1); continue; } if (!map.containsKey(x)) { map.put(x, ++numberOfPeople); } if (!map.containsKey(y)) { map.put(y, ++numberOfPeople); } //print answer for current test case System.out.println(union(map.get(x), map.get(y))); } } } public static void startUnion(int numberOfPeople) { for(int i = 0; i < numberOfPeople; i++) { //initialize each individual person people[i] = i; //each person initially has a group of one (themselves) relationships[i] = 1; } } public static int union(int person, int friend) { //find parents in tree person = find(person); friend = find(friend); if(person != friend) { //add connection between person and friend //find larger group of the two and make sure both person and friend point to it if(relationships[person] > relationships[friend]) { relationships[person] += relationships[friend]; people[friend] = person; return relationships[person]; } else { relationships[friend] += relationships[person]; people[person] = friend; return relationships[friend]; } } return relationships[person]; } public static int find(int person) { //traverse parents of tree if possible if(people[person] != person) { people[person] = find(people[person]); } return people[person]; } } ================================================ FILE: uva/WhatBaseIsThis.java ================================================ /** * In positional notation we know the position of a digit indicates the weight of that digit toward the * value of a number. For example, in the base 10 number 362 we know that 2 has the weight 100 * , 6 * has the weight 101 * , and 3 has the weight 102 * , yielding the value 3 × 102 + 6 × 101 + 2 × 100 * , or just * 300 + 60 + 2. The same mechanism is used for numbers expressed in other bases. While most people * assume the numbers they encounter everyday are expressed using base 10, we know that other bases * are possible. In particular, the number 362 in base 9 or base 14 represents a totally different value than * 362 in base 10. * For this problem your program will presented with a sequence of pairs of integers. Let’s call the * members of a pair X and Y . What your program is to do is determine the smallest base for X and the * smallest base for Y (likely different from that for X) so that X and Y represent the same value. * Consider, for example, the integers 12 and 5. Certainly these are not equal if base 10 is used for * each. But suppose 12 was a base 3 number and 5 was a base 6 number? 12 base 3 = 1 × 3 * 1 + 2 × 3 * 0 * , * or 5 base 10, and certainly 5 in any base is equal to 5 base 10. So 12 and 5 can be equal, if you select * the right bases for each of them! * Input * On each line of the input data there will be a pair of integers, X and Y , separated by one or more blanks; * leading and trailing blanks may also appear on each line, are are to be ignored. The bases associated * with X and Y will be between 1 and 36 (inclusive), and as noted above, need not be the same for X and * Y . In representing these numbers the digits 0 through 9 have their usual decimal interpretations. The * uppercase alphabetic characters A through Z represent digits with values 10 through 35, respectively. * Output * For each pair of integers in the input display a message similar to those shown in the examples shown * below. Of course if the two integers cannot be equal regardless of the assumed base for each, then print * an appropriate message; a suitable illustration is given in the examples. * Sample Input * 12 5 * 10 A * 12 34 * 123 456 * 1 2 * 10 2 * Sample Output * 12 (base 3) = 5 (base 6) * 10 (base 10) = A (base 11) * 12 (base 17) = 34 (base 5) * 123 is not equal to 456 in any base 2..36 * 1 is not equal to 2 in any base 2..36 * 10 (base 2) = 2 (base 3) */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=279 import java.math.BigInteger; import java.util.Scanner; public class WhatBaseIsThis { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String x = input.next(); String y = input.next(); boolean found = false; for (int i = 2; i < 37 && !found; i++) { BigInteger xConvertedToBase; try { xConvertedToBase = new BigInteger(x, i); } catch (Exception e) { continue; } for (int j = 2; j < 37; j++) { BigInteger yConvertedToBase; try { yConvertedToBase = new BigInteger(y, j); } catch (Exception e) { continue; } if (xConvertedToBase.equals(yConvertedToBase)) { System.out.println(x + " (base " + i + ") = " + y + " (base " + j + ")"); found = true; break; } } } if (!found) { System.out.println(x + " is not equal to " + y + " in any base 2..36"); } } } } ================================================ FILE: uva/WhoSaidCrisis.java ================================================ /** * The company Assistance for Critical Moments (ACM) is helping other companies to overcome the * current economical crisis. As experts in computing machinery, their job is to calculate the cost/benefit * balance of the other companies. They receive two numbers, indicating the total amount of benefits and * costs, and they have to compute the final balance. * You have to solve the complex business problem of computing balances. You are given two positive * integer numbers, corresponding to the benefits and the costs. You have to obtain the total balance, * i.e., the difference between benefits and costs. * Input * The first line of the input contains an integer indicating the number of test cases. * For each test case, there is a line with two positive integer numbers, A and B, corresponding to the * benefits and the costs, respectively. Both numbers are between 0 and a googol (10100) to the power of * a hundred. * Output * For each test case, the output should consist of a line indicating the balance: A − B. * Sample Input * 4 * 10 3 * 4 9 * 0 8 * 5 2 * Sample Output * 7 * -5 * -8 * 3 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2443 import java.math.BigInteger; import java.util.Scanner; public class WhoSaidCrisis { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger first = input.nextBigInteger(); BigInteger second = input.nextBigInteger(); System.out.println(first.subtract(second)); numberOfTestCases--; } } }